]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
55039b963ca356a172ef76148e266f67a07d0650
[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.14.1.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The following macros are used to cast pointers to integers and
321 ** integers to pointers.  The way you do this varies from one compiler
322 ** to the next, so we have developed the following set of #if statements
323 ** to generate appropriate macros for a wide range of compilers.
324 **
325 ** The correct "ANSI" way to do this is to use the intptr_t type. 
326 ** Unfortunately, that typedef is not available on all compilers, or
327 ** if it is available, it requires an #include of specific headers
328 ** that vary from one machine to the next.
329 **
330 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
331 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
332 ** So we have to define the macros in different ways depending on the
333 ** compiler.
334 */
335 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
336 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
337 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
338 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
339 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
340 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
341 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
342 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
343 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
344 #else                          /* Generates a warning - but it always works */
345 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
346 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
347 #endif
348
349 /*
350 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351 ** 0 means mutexes are permanently disable and the library is never
352 ** threadsafe.  1 means the library is serialized which is the highest
353 ** level of threadsafety.  2 means the libary is multithreaded - multiple
354 ** threads can use SQLite as long as no two threads try to use the same
355 ** database connection at the same time.
356 **
357 ** Older versions of SQLite used an optional THREADSAFE macro.
358 ** We support that for legacy.
359 */
360 #if !defined(SQLITE_THREADSAFE)
361 #if defined(THREADSAFE)
362 # define SQLITE_THREADSAFE THREADSAFE
363 #else
364 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365 #endif
366 #endif
367
368 /*
369 ** Powersafe overwrite is on by default.  But can be turned off using
370 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
371 */
372 #ifndef SQLITE_POWERSAFE_OVERWRITE
373 # define SQLITE_POWERSAFE_OVERWRITE 1
374 #endif
375
376 /*
377 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
378 ** It determines whether or not the features related to 
379 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
380 ** be overridden at runtime using the sqlite3_config() API.
381 */
382 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
383 # define SQLITE_DEFAULT_MEMSTATUS 1
384 #endif
385
386 /*
387 ** Exactly one of the following macros must be defined in order to
388 ** specify which memory allocation subsystem to use.
389 **
390 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
391 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
392 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
393 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
394 **
395 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
396 ** assert() macro is enabled, each call into the Win32 native heap subsystem
397 ** will cause HeapValidate to be called.  If heap validation should fail, an
398 ** assertion will be triggered.
399 **
400 ** (Historical note:  There used to be several other options, but we've
401 ** pared it down to just these three.)
402 **
403 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
404 ** the default.
405 */
406 #if defined(SQLITE_SYSTEM_MALLOC) \
407   + defined(SQLITE_WIN32_MALLOC) \
408   + defined(SQLITE_ZERO_MALLOC) \
409   + defined(SQLITE_MEMDEBUG)>1
410 # error "Two or more of the following compile-time configuration options\
411  are defined but at most one is allowed:\
412  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
413  SQLITE_ZERO_MALLOC"
414 #endif
415 #if defined(SQLITE_SYSTEM_MALLOC) \
416   + defined(SQLITE_WIN32_MALLOC) \
417   + defined(SQLITE_ZERO_MALLOC) \
418   + defined(SQLITE_MEMDEBUG)==0
419 # define SQLITE_SYSTEM_MALLOC 1
420 #endif
421
422 /*
423 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
424 ** sizes of memory allocations below this value where possible.
425 */
426 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
427 # define SQLITE_MALLOC_SOFT_LIMIT 1024
428 #endif
429
430 /*
431 ** We need to define _XOPEN_SOURCE as follows in order to enable
432 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
433 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
434 ** so it is omitted there.  See ticket #2673.
435 **
436 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
437 ** implemented on some systems.  So we avoid defining it at all
438 ** if it is already defined or if it is unneeded because we are
439 ** not doing a threadsafe build.  Ticket #2681.
440 **
441 ** See also ticket #2741.
442 */
443 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
444 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
445 #endif
446
447 /*
448 ** The TCL headers are only needed when compiling the TCL bindings.
449 */
450 #if defined(SQLITE_TCL) || defined(TCLSH)
451 # include <tcl.h>
452 #endif
453
454 /*
455 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
456 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
457 ** make it true by defining or undefining NDEBUG.
458 **
459 ** Setting NDEBUG makes the code smaller and run faster by disabling the
460 ** number assert() statements in the code.  So we want the default action
461 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
462 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
463 ** feature.
464 */
465 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
466 # define NDEBUG 1
467 #endif
468 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
469 # undef NDEBUG
470 #endif
471
472 /*
473 ** The testcase() macro is used to aid in coverage testing.  When 
474 ** doing coverage testing, the condition inside the argument to
475 ** testcase() must be evaluated both true and false in order to
476 ** get full branch coverage.  The testcase() macro is inserted
477 ** to help ensure adequate test coverage in places where simple
478 ** condition/decision coverage is inadequate.  For example, testcase()
479 ** can be used to make sure boundary values are tested.  For
480 ** bitmask tests, testcase() can be used to make sure each bit
481 ** is significant and used at least once.  On switch statements
482 ** where multiple cases go to the same block of code, testcase()
483 ** can insure that all cases are evaluated.
484 **
485 */
486 #ifdef SQLITE_COVERAGE_TEST
487 SQLITE_PRIVATE   void sqlite3Coverage(int);
488 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
489 #else
490 # define testcase(X)
491 #endif
492
493 /*
494 ** The TESTONLY macro is used to enclose variable declarations or
495 ** other bits of code that are needed to support the arguments
496 ** within testcase() and assert() macros.
497 */
498 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
499 # define TESTONLY(X)  X
500 #else
501 # define TESTONLY(X)
502 #endif
503
504 /*
505 ** Sometimes we need a small amount of code such as a variable initialization
506 ** to setup for a later assert() statement.  We do not want this code to
507 ** appear when assert() is disabled.  The following macro is therefore
508 ** used to contain that setup code.  The "VVA" acronym stands for
509 ** "Verification, Validation, and Accreditation".  In other words, the
510 ** code within VVA_ONLY() will only run during verification processes.
511 */
512 #ifndef NDEBUG
513 # define VVA_ONLY(X)  X
514 #else
515 # define VVA_ONLY(X)
516 #endif
517
518 /*
519 ** The ALWAYS and NEVER macros surround boolean expressions which 
520 ** are intended to always be true or false, respectively.  Such
521 ** expressions could be omitted from the code completely.  But they
522 ** are included in a few cases in order to enhance the resilience
523 ** of SQLite to unexpected behavior - to make the code "self-healing"
524 ** or "ductile" rather than being "brittle" and crashing at the first
525 ** hint of unplanned behavior.
526 **
527 ** In other words, ALWAYS and NEVER are added for defensive code.
528 **
529 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
530 ** be true and false so that the unreachable code then specify will
531 ** not be counted as untested code.
532 */
533 #if defined(SQLITE_COVERAGE_TEST)
534 # define ALWAYS(X)      (1)
535 # define NEVER(X)       (0)
536 #elif !defined(NDEBUG)
537 # define ALWAYS(X)      ((X)?1:(assert(0),0))
538 # define NEVER(X)       ((X)?(assert(0),1):0)
539 #else
540 # define ALWAYS(X)      (X)
541 # define NEVER(X)       (X)
542 #endif
543
544 /*
545 ** Return true (non-zero) if the input is a integer that is too large
546 ** to fit in 32-bits.  This macro is used inside of various testcase()
547 ** macros to verify that we have tested SQLite for large-file support.
548 */
549 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
550
551 /*
552 ** The macro unlikely() is a hint that surrounds a boolean
553 ** expression that is usually false.  Macro likely() surrounds
554 ** a boolean expression that is usually true.  GCC is able to
555 ** use these hints to generate better code, sometimes.
556 */
557 #if defined(__GNUC__) && 0
558 # define likely(X)    __builtin_expect((X),1)
559 # define unlikely(X)  __builtin_expect((X),0)
560 #else
561 # define likely(X)    !!(X)
562 # define unlikely(X)  !!(X)
563 #endif
564
565 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
566 /************** Begin file sqlite3.h *****************************************/
567 /*
568 ** 2001 September 15
569 **
570 ** The author disclaims copyright to this source code.  In place of
571 ** a legal notice, here is a blessing:
572 **
573 **    May you do good and not evil.
574 **    May you find forgiveness for yourself and forgive others.
575 **    May you share freely, never taking more than you give.
576 **
577 *************************************************************************
578 ** This header file defines the interface that the SQLite library
579 ** presents to client programs.  If a C-function, structure, datatype,
580 ** or constant definition does not appear in this file, then it is
581 ** not a published API of SQLite, is subject to change without
582 ** notice, and should not be referenced by programs that use SQLite.
583 **
584 ** Some of the definitions that are in this file are marked as
585 ** "experimental".  Experimental interfaces are normally new
586 ** features recently added to SQLite.  We do not anticipate changes
587 ** to experimental interfaces but reserve the right to make minor changes
588 ** if experience from use "in the wild" suggest such changes are prudent.
589 **
590 ** The official C-language API documentation for SQLite is derived
591 ** from comments in this file.  This file is the authoritative source
592 ** on how SQLite interfaces are suppose to operate.
593 **
594 ** The name of this file under configuration management is "sqlite.h.in".
595 ** The makefile makes some minor changes to this file (such as inserting
596 ** the version number) and changes its name to "sqlite3.h" as
597 ** part of the build process.
598 */
599 #ifndef _SQLITE3_H_
600 #define _SQLITE3_H_
601 #include <stdarg.h>     /* Needed for the definition of va_list */
602
603 /*
604 ** Make sure we can call this stuff from C++.
605 */
606 #if 0
607 extern "C" {
608 #endif
609
610
611 /*
612 ** Add the ability to override 'extern'
613 */
614 #ifndef SQLITE_EXTERN
615 # define SQLITE_EXTERN extern
616 #endif
617
618 #ifndef SQLITE_API
619 # define SQLITE_API
620 #endif
621
622
623 /*
624 ** These no-op macros are used in front of interfaces to mark those
625 ** interfaces as either deprecated or experimental.  New applications
626 ** should not use deprecated interfaces - they are support for backwards
627 ** compatibility only.  Application writers should be aware that
628 ** experimental interfaces are subject to change in point releases.
629 **
630 ** These macros used to resolve to various kinds of compiler magic that
631 ** would generate warning messages when they were used.  But that
632 ** compiler magic ended up generating such a flurry of bug reports
633 ** that we have taken it all out and gone back to using simple
634 ** noop macros.
635 */
636 #define SQLITE_DEPRECATED
637 #define SQLITE_EXPERIMENTAL
638
639 /*
640 ** Ensure these symbols were not defined by some previous header file.
641 */
642 #ifdef SQLITE_VERSION
643 # undef SQLITE_VERSION
644 #endif
645 #ifdef SQLITE_VERSION_NUMBER
646 # undef SQLITE_VERSION_NUMBER
647 #endif
648
649 /*
650 ** CAPI3REF: Compile-Time Library Version Numbers
651 **
652 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
653 ** evaluates to a string literal that is the SQLite version in the
654 ** format "X.Y.Z" where X is the major version number (always 3 for
655 ** SQLite3) and Y is the minor version number and Z is the release number.)^
656 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
657 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
658 ** numbers used in [SQLITE_VERSION].)^
659 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
660 ** be larger than the release from which it is derived.  Either Y will
661 ** be held constant and Z will be incremented or else Y will be incremented
662 ** and Z will be reset to zero.
663 **
664 ** Since version 3.6.18, SQLite source code has been stored in the
665 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
666 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
667 ** a string which identifies a particular check-in of SQLite
668 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
669 ** string contains the date and time of the check-in (UTC) and an SHA1
670 ** hash of the entire source tree.
671 **
672 ** See also: [sqlite3_libversion()],
673 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
674 ** [sqlite_version()] and [sqlite_source_id()].
675 */
676 #define SQLITE_VERSION        "3.7.14.1"
677 #define SQLITE_VERSION_NUMBER 3007014
678 #define SQLITE_SOURCE_ID      "2012-10-04 19:37:12 091570e46d04e84b67228e0bdbcd6e1fb60c6bdb"
679
680 /*
681 ** CAPI3REF: Run-Time Library Version Numbers
682 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
683 **
684 ** These interfaces provide the same information as the [SQLITE_VERSION],
685 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
686 ** but are associated with the library instead of the header file.  ^(Cautious
687 ** programmers might include assert() statements in their application to
688 ** verify that values returned by these interfaces match the macros in
689 ** the header, and thus insure that the application is
690 ** compiled with matching library and header files.
691 **
692 ** <blockquote><pre>
693 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
694 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
695 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
696 ** </pre></blockquote>)^
697 **
698 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
699 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
700 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
701 ** function is provided for use in DLLs since DLL users usually do not have
702 ** direct access to string constants within the DLL.  ^The
703 ** sqlite3_libversion_number() function returns an integer equal to
704 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
705 ** a pointer to a string constant whose value is the same as the 
706 ** [SQLITE_SOURCE_ID] C preprocessor macro.
707 **
708 ** See also: [sqlite_version()] and [sqlite_source_id()].
709 */
710 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
711 SQLITE_API const char *sqlite3_libversion(void);
712 SQLITE_API const char *sqlite3_sourceid(void);
713 SQLITE_API int sqlite3_libversion_number(void);
714
715 /*
716 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
717 **
718 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
719 ** indicating whether the specified option was defined at 
720 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
721 ** option name passed to sqlite3_compileoption_used().  
722 **
723 ** ^The sqlite3_compileoption_get() function allows iterating
724 ** over the list of options that were defined at compile time by
725 ** returning the N-th compile time option string.  ^If N is out of range,
726 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
727 ** prefix is omitted from any strings returned by 
728 ** sqlite3_compileoption_get().
729 **
730 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
731 ** and sqlite3_compileoption_get() may be omitted by specifying the 
732 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
733 **
734 ** See also: SQL functions [sqlite_compileoption_used()] and
735 ** [sqlite_compileoption_get()] and the [compile_options pragma].
736 */
737 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
738 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
739 SQLITE_API const char *sqlite3_compileoption_get(int N);
740 #endif
741
742 /*
743 ** CAPI3REF: Test To See If The Library Is Threadsafe
744 **
745 ** ^The sqlite3_threadsafe() function returns zero if and only if
746 ** SQLite was compiled with mutexing code omitted due to the
747 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
748 **
749 ** SQLite can be compiled with or without mutexes.  When
750 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
751 ** are enabled and SQLite is threadsafe.  When the
752 ** [SQLITE_THREADSAFE] macro is 0, 
753 ** the mutexes are omitted.  Without the mutexes, it is not safe
754 ** to use SQLite concurrently from more than one thread.
755 **
756 ** Enabling mutexes incurs a measurable performance penalty.
757 ** So if speed is of utmost importance, it makes sense to disable
758 ** the mutexes.  But for maximum safety, mutexes should be enabled.
759 ** ^The default behavior is for mutexes to be enabled.
760 **
761 ** This interface can be used by an application to make sure that the
762 ** version of SQLite that it is linking against was compiled with
763 ** the desired setting of the [SQLITE_THREADSAFE] macro.
764 **
765 ** This interface only reports on the compile-time mutex setting
766 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
767 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
768 ** can be fully or partially disabled using a call to [sqlite3_config()]
769 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
770 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
771 ** sqlite3_threadsafe() function shows only the compile-time setting of
772 ** thread safety, not any run-time changes to that setting made by
773 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
774 ** is unchanged by calls to sqlite3_config().)^
775 **
776 ** See the [threading mode] documentation for additional information.
777 */
778 SQLITE_API int sqlite3_threadsafe(void);
779
780 /*
781 ** CAPI3REF: Database Connection Handle
782 ** KEYWORDS: {database connection} {database connections}
783 **
784 ** Each open SQLite database is represented by a pointer to an instance of
785 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
786 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
787 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
788 ** and [sqlite3_close_v2()] are its destructors.  There are many other
789 ** interfaces (such as
790 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
791 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
792 ** sqlite3 object.
793 */
794 typedef struct sqlite3 sqlite3;
795
796 /*
797 ** CAPI3REF: 64-Bit Integer Types
798 ** KEYWORDS: sqlite_int64 sqlite_uint64
799 **
800 ** Because there is no cross-platform way to specify 64-bit integer types
801 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
802 **
803 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
804 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
805 ** compatibility only.
806 **
807 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
808 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
809 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
810 ** between 0 and +18446744073709551615 inclusive.
811 */
812 #ifdef SQLITE_INT64_TYPE
813   typedef SQLITE_INT64_TYPE sqlite_int64;
814   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
815 #elif defined(_MSC_VER) || defined(__BORLANDC__)
816   typedef __int64 sqlite_int64;
817   typedef unsigned __int64 sqlite_uint64;
818 #else
819   typedef long long int sqlite_int64;
820   typedef unsigned long long int sqlite_uint64;
821 #endif
822 typedef sqlite_int64 sqlite3_int64;
823 typedef sqlite_uint64 sqlite3_uint64;
824
825 /*
826 ** If compiling for a processor that lacks floating point support,
827 ** substitute integer for floating-point.
828 */
829 #ifdef SQLITE_OMIT_FLOATING_POINT
830 # define double sqlite3_int64
831 #endif
832
833 /*
834 ** CAPI3REF: Closing A Database Connection
835 **
836 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
837 ** for the [sqlite3] object.
838 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
839 ** the [sqlite3] object is successfully destroyed and all associated
840 ** resources are deallocated.
841 **
842 ** ^If the database connection is associated with unfinalized prepared
843 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
844 ** will leave the database connection open and return [SQLITE_BUSY].
845 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
846 ** and unfinished sqlite3_backups, then the database connection becomes
847 ** an unusable "zombie" which will automatically be deallocated when the
848 ** last prepared statement is finalized or the last sqlite3_backup is
849 ** finished.  The sqlite3_close_v2() interface is intended for use with
850 ** host languages that are garbage collected, and where the order in which
851 ** destructors are called is arbitrary.
852 **
853 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
854 ** [sqlite3_blob_close | close] all [BLOB handles], and 
855 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
856 ** with the [sqlite3] object prior to attempting to close the object.  ^If
857 ** sqlite3_close() is called on a [database connection] that still has
858 ** outstanding [prepared statements], [BLOB handles], and/or
859 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
860 ** of resources is deferred until all [prepared statements], [BLOB handles],
861 ** and [sqlite3_backup] objects are also destroyed.
862 **
863 ** ^If an [sqlite3] object is destroyed while a transaction is open,
864 ** the transaction is automatically rolled back.
865 **
866 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
867 ** must be either a NULL
868 ** pointer or an [sqlite3] object pointer obtained
869 ** from [sqlite3_open()], [sqlite3_open16()], or
870 ** [sqlite3_open_v2()], and not previously closed.
871 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
872 ** argument is a harmless no-op.
873 */
874 SQLITE_API int sqlite3_close(sqlite3*);
875 SQLITE_API int sqlite3_close_v2(sqlite3*);
876
877 /*
878 ** The type for a callback function.
879 ** This is legacy and deprecated.  It is included for historical
880 ** compatibility and is not documented.
881 */
882 typedef int (*sqlite3_callback)(void*,int,char**, char**);
883
884 /*
885 ** CAPI3REF: One-Step Query Execution Interface
886 **
887 ** The sqlite3_exec() interface is a convenience wrapper around
888 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
889 ** that allows an application to run multiple statements of SQL
890 ** without having to use a lot of C code. 
891 **
892 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
893 ** semicolon-separate SQL statements passed into its 2nd argument,
894 ** in the context of the [database connection] passed in as its 1st
895 ** argument.  ^If the callback function of the 3rd argument to
896 ** sqlite3_exec() is not NULL, then it is invoked for each result row
897 ** coming out of the evaluated SQL statements.  ^The 4th argument to
898 ** sqlite3_exec() is relayed through to the 1st argument of each
899 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
900 ** is NULL, then no callback is ever invoked and result rows are
901 ** ignored.
902 **
903 ** ^If an error occurs while evaluating the SQL statements passed into
904 ** sqlite3_exec(), then execution of the current statement stops and
905 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
906 ** is not NULL then any error message is written into memory obtained
907 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
908 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
909 ** on error message strings returned through the 5th parameter of
910 ** of sqlite3_exec() after the error message string is no longer needed.
911 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
912 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
913 ** NULL before returning.
914 **
915 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
916 ** routine returns SQLITE_ABORT without invoking the callback again and
917 ** without running any subsequent SQL statements.
918 **
919 ** ^The 2nd argument to the sqlite3_exec() callback function is the
920 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
921 ** callback is an array of pointers to strings obtained as if from
922 ** [sqlite3_column_text()], one for each column.  ^If an element of a
923 ** result row is NULL then the corresponding string pointer for the
924 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
925 ** sqlite3_exec() callback is an array of pointers to strings where each
926 ** entry represents the name of corresponding result column as obtained
927 ** from [sqlite3_column_name()].
928 **
929 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
930 ** to an empty string, or a pointer that contains only whitespace and/or 
931 ** SQL comments, then no SQL statements are evaluated and the database
932 ** is not changed.
933 **
934 ** Restrictions:
935 **
936 ** <ul>
937 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
938 **      is a valid and open [database connection].
939 ** <li> The application must not close [database connection] specified by
940 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
941 ** <li> The application must not modify the SQL statement text passed into
942 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
943 ** </ul>
944 */
945 SQLITE_API int sqlite3_exec(
946   sqlite3*,                                  /* An open database */
947   const char *sql,                           /* SQL to be evaluated */
948   int (*callback)(void*,int,char**,char**),  /* Callback function */
949   void *,                                    /* 1st argument to callback */
950   char **errmsg                              /* Error msg written here */
951 );
952
953 /*
954 ** CAPI3REF: Result Codes
955 ** KEYWORDS: SQLITE_OK {error code} {error codes}
956 ** KEYWORDS: {result code} {result codes}
957 **
958 ** Many SQLite functions return an integer result code from the set shown
959 ** here in order to indicate success or failure.
960 **
961 ** New error codes may be added in future versions of SQLite.
962 **
963 ** See also: [SQLITE_IOERR_READ | extended result codes],
964 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
965 */
966 #define SQLITE_OK           0   /* Successful result */
967 /* beginning-of-error-codes */
968 #define SQLITE_ERROR        1   /* SQL error or missing database */
969 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
970 #define SQLITE_PERM         3   /* Access permission denied */
971 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
972 #define SQLITE_BUSY         5   /* The database file is locked */
973 #define SQLITE_LOCKED       6   /* A table in the database is locked */
974 #define SQLITE_NOMEM        7   /* A malloc() failed */
975 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
976 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
977 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
978 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
979 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
980 #define SQLITE_FULL        13   /* Insertion failed because database is full */
981 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
982 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
983 #define SQLITE_EMPTY       16   /* Database is empty */
984 #define SQLITE_SCHEMA      17   /* The database schema changed */
985 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
986 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
987 #define SQLITE_MISMATCH    20   /* Data type mismatch */
988 #define SQLITE_MISUSE      21   /* Library used incorrectly */
989 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
990 #define SQLITE_AUTH        23   /* Authorization denied */
991 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
992 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
993 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
994 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
995 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
996 /* end-of-error-codes */
997
998 /*
999 ** CAPI3REF: Extended Result Codes
1000 ** KEYWORDS: {extended error code} {extended error codes}
1001 ** KEYWORDS: {extended result code} {extended result codes}
1002 **
1003 ** In its default configuration, SQLite API routines return one of 26 integer
1004 ** [SQLITE_OK | result codes].  However, experience has shown that many of
1005 ** these result codes are too coarse-grained.  They do not provide as
1006 ** much information about problems as programmers might like.  In an effort to
1007 ** address this, newer versions of SQLite (version 3.3.8 and later) include
1008 ** support for additional result codes that provide more detailed information
1009 ** about errors. The extended result codes are enabled or disabled
1010 ** on a per database connection basis using the
1011 ** [sqlite3_extended_result_codes()] API.
1012 **
1013 ** Some of the available extended result codes are listed here.
1014 ** One may expect the number of extended result codes will be expand
1015 ** over time.  Software that uses extended result codes should expect
1016 ** to see new result codes in future releases of SQLite.
1017 **
1018 ** The SQLITE_OK result code will never be extended.  It will always
1019 ** be exactly zero.
1020 */
1021 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1022 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1023 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1024 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1025 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1026 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1027 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1028 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1029 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1030 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1031 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1032 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1033 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1034 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1035 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1036 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1037 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1038 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1039 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1040 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1041 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1042 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1043 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1044 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1045 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1046 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1047 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1048 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1049 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1050 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1051
1052 /*
1053 ** CAPI3REF: Flags For File Open Operations
1054 **
1055 ** These bit values are intended for use in the
1056 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1057 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1058 */
1059 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1060 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1061 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1062 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1063 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1064 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1065 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1066 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1067 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1068 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1069 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1070 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1071 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1072 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1073 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1074 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1075 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1076 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1077 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1078 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1079
1080 /* Reserved:                         0x00F00000 */
1081
1082 /*
1083 ** CAPI3REF: Device Characteristics
1084 **
1085 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1086 ** object returns an integer which is a vector of these
1087 ** bit values expressing I/O characteristics of the mass storage
1088 ** device that holds the file that the [sqlite3_io_methods]
1089 ** refers to.
1090 **
1091 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1092 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1093 ** mean that writes of blocks that are nnn bytes in size and
1094 ** are aligned to an address which is an integer multiple of
1095 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1096 ** that when data is appended to a file, the data is appended
1097 ** first then the size of the file is extended, never the other
1098 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1099 ** information is written to disk in the same order as calls
1100 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1101 ** after reboot following a crash or power loss, the only bytes in a
1102 ** file that were written at the application level might have changed
1103 ** and that adjacent bytes, even bytes within the same sector are
1104 ** guaranteed to be unchanged.
1105 */
1106 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1107 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1108 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1109 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1110 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1111 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1112 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1113 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1114 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1115 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1116 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1117 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1118 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1119
1120 /*
1121 ** CAPI3REF: File Locking Levels
1122 **
1123 ** SQLite uses one of these integer values as the second
1124 ** argument to calls it makes to the xLock() and xUnlock() methods
1125 ** of an [sqlite3_io_methods] object.
1126 */
1127 #define SQLITE_LOCK_NONE          0
1128 #define SQLITE_LOCK_SHARED        1
1129 #define SQLITE_LOCK_RESERVED      2
1130 #define SQLITE_LOCK_PENDING       3
1131 #define SQLITE_LOCK_EXCLUSIVE     4
1132
1133 /*
1134 ** CAPI3REF: Synchronization Type Flags
1135 **
1136 ** When SQLite invokes the xSync() method of an
1137 ** [sqlite3_io_methods] object it uses a combination of
1138 ** these integer values as the second argument.
1139 **
1140 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1141 ** sync operation only needs to flush data to mass storage.  Inode
1142 ** information need not be flushed. If the lower four bits of the flag
1143 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1144 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1145 ** to use Mac OS X style fullsync instead of fsync().
1146 **
1147 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1148 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1149 ** settings.  The [synchronous pragma] determines when calls to the
1150 ** xSync VFS method occur and applies uniformly across all platforms.
1151 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1152 ** energetic or rigorous or forceful the sync operations are and
1153 ** only make a difference on Mac OSX for the default SQLite code.
1154 ** (Third-party VFS implementations might also make the distinction
1155 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1156 ** operating systems natively supported by SQLite, only Mac OSX
1157 ** cares about the difference.)
1158 */
1159 #define SQLITE_SYNC_NORMAL        0x00002
1160 #define SQLITE_SYNC_FULL          0x00003
1161 #define SQLITE_SYNC_DATAONLY      0x00010
1162
1163 /*
1164 ** CAPI3REF: OS Interface Open File Handle
1165 **
1166 ** An [sqlite3_file] object represents an open file in the 
1167 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1168 ** implementations will
1169 ** want to subclass this object by appending additional fields
1170 ** for their own use.  The pMethods entry is a pointer to an
1171 ** [sqlite3_io_methods] object that defines methods for performing
1172 ** I/O operations on the open file.
1173 */
1174 typedef struct sqlite3_file sqlite3_file;
1175 struct sqlite3_file {
1176   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1177 };
1178
1179 /*
1180 ** CAPI3REF: OS Interface File Virtual Methods Object
1181 **
1182 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1183 ** [sqlite3_file] object (or, more commonly, a subclass of the
1184 ** [sqlite3_file] object) with a pointer to an instance of this object.
1185 ** This object defines the methods used to perform various operations
1186 ** against the open file represented by the [sqlite3_file] object.
1187 **
1188 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
1189 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1190 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1191 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1192 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1193 ** to NULL.
1194 **
1195 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1196 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1197 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1198 ** flag may be ORed in to indicate that only the data of the file
1199 ** and not its inode needs to be synced.
1200 **
1201 ** The integer values to xLock() and xUnlock() are one of
1202 ** <ul>
1203 ** <li> [SQLITE_LOCK_NONE],
1204 ** <li> [SQLITE_LOCK_SHARED],
1205 ** <li> [SQLITE_LOCK_RESERVED],
1206 ** <li> [SQLITE_LOCK_PENDING], or
1207 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1208 ** </ul>
1209 ** xLock() increases the lock. xUnlock() decreases the lock.
1210 ** The xCheckReservedLock() method checks whether any database connection,
1211 ** either in this process or in some other process, is holding a RESERVED,
1212 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1213 ** if such a lock exists and false otherwise.
1214 **
1215 ** The xFileControl() method is a generic interface that allows custom
1216 ** VFS implementations to directly control an open file using the
1217 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1218 ** integer opcode.  The third argument is a generic pointer intended to
1219 ** point to a structure that may contain arguments or space in which to
1220 ** write return values.  Potential uses for xFileControl() might be
1221 ** functions to enable blocking locks with timeouts, to change the
1222 ** locking strategy (for example to use dot-file locks), to inquire
1223 ** about the status of a lock, or to break stale locks.  The SQLite
1224 ** core reserves all opcodes less than 100 for its own use.
1225 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1226 ** Applications that define a custom xFileControl method should use opcodes
1227 ** greater than 100 to avoid conflicts.  VFS implementations should
1228 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1229 ** recognize.
1230 **
1231 ** The xSectorSize() method returns the sector size of the
1232 ** device that underlies the file.  The sector size is the
1233 ** minimum write that can be performed without disturbing
1234 ** other bytes in the file.  The xDeviceCharacteristics()
1235 ** method returns a bit vector describing behaviors of the
1236 ** underlying device:
1237 **
1238 ** <ul>
1239 ** <li> [SQLITE_IOCAP_ATOMIC]
1240 ** <li> [SQLITE_IOCAP_ATOMIC512]
1241 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1242 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1243 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1244 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1245 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1246 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1247 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1248 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1249 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1250 ** </ul>
1251 **
1252 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1253 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1254 ** mean that writes of blocks that are nnn bytes in size and
1255 ** are aligned to an address which is an integer multiple of
1256 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1257 ** that when data is appended to a file, the data is appended
1258 ** first then the size of the file is extended, never the other
1259 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1260 ** information is written to disk in the same order as calls
1261 ** to xWrite().
1262 **
1263 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1264 ** in the unread portions of the buffer with zeros.  A VFS that
1265 ** fails to zero-fill short reads might seem to work.  However,
1266 ** failure to zero-fill short reads will eventually lead to
1267 ** database corruption.
1268 */
1269 typedef struct sqlite3_io_methods sqlite3_io_methods;
1270 struct sqlite3_io_methods {
1271   int iVersion;
1272   int (*xClose)(sqlite3_file*);
1273   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1274   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1275   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1276   int (*xSync)(sqlite3_file*, int flags);
1277   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1278   int (*xLock)(sqlite3_file*, int);
1279   int (*xUnlock)(sqlite3_file*, int);
1280   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1281   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1282   int (*xSectorSize)(sqlite3_file*);
1283   int (*xDeviceCharacteristics)(sqlite3_file*);
1284   /* Methods above are valid for version 1 */
1285   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1286   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1287   void (*xShmBarrier)(sqlite3_file*);
1288   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1289   /* Methods above are valid for version 2 */
1290   /* Additional methods may be added in future releases */
1291 };
1292
1293 /*
1294 ** CAPI3REF: Standard File Control Opcodes
1295 **
1296 ** These integer constants are opcodes for the xFileControl method
1297 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1298 ** interface.
1299 **
1300 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1301 ** opcode causes the xFileControl method to write the current state of
1302 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1303 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1304 ** into an integer that the pArg argument points to. This capability
1305 ** is used during testing and only needs to be supported when SQLITE_TEST
1306 ** is defined.
1307 ** <ul>
1308 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1309 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1310 ** layer a hint of how large the database file will grow to be during the
1311 ** current transaction.  This hint is not guaranteed to be accurate but it
1312 ** is often close.  The underlying VFS might choose to preallocate database
1313 ** file space based on this hint in order to help writes to the database
1314 ** file run faster.
1315 **
1316 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1317 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1318 ** extends and truncates the database file in chunks of a size specified
1319 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1320 ** point to an integer (type int) containing the new chunk-size to use
1321 ** for the nominated database. Allocating database file space in large
1322 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1323 ** improve performance on some systems.
1324 **
1325 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1326 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1327 ** to the [sqlite3_file] object associated with a particular database
1328 ** connection.  See the [sqlite3_file_control()] documentation for
1329 ** additional information.
1330 **
1331 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1332 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1333 ** SQLite and sent to all VFSes in place of a call to the xSync method
1334 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1335 ** Some specialized VFSes need this signal in order to operate correctly
1336 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1337 ** VFSes do not need this signal and should silently ignore this opcode.
1338 ** Applications should not call [sqlite3_file_control()] with this
1339 ** opcode as doing so may disrupt the operation of the specialized VFSes
1340 ** that do require it.  
1341 **
1342 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1343 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1344 ** retry counts and intervals for certain disk I/O operations for the
1345 ** windows [VFS] in order to provide robustness in the presence of
1346 ** anti-virus programs.  By default, the windows VFS will retry file read,
1347 ** file write, and file delete operations up to 10 times, with a delay
1348 ** of 25 milliseconds before the first retry and with the delay increasing
1349 ** by an additional 25 milliseconds with each subsequent retry.  This
1350 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1351 ** to be adjusted.  The values are changed for all database connections
1352 ** within the same process.  The argument is a pointer to an array of two
1353 ** integers where the first integer i the new retry count and the second
1354 ** integer is the delay.  If either integer is negative, then the setting
1355 ** is not changed but instead the prior value of that setting is written
1356 ** into the array entry, allowing the current retry settings to be
1357 ** interrogated.  The zDbName parameter is ignored.
1358 **
1359 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1360 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1361 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1362 ** write ahead log and shared memory files used for transaction control
1363 ** are automatically deleted when the latest connection to the database
1364 ** closes.  Setting persistent WAL mode causes those files to persist after
1365 ** close.  Persisting the files is useful when other processes that do not
1366 ** have write permission on the directory containing the database file want
1367 ** to read the database file, as the WAL and shared memory files must exist
1368 ** in order for the database to be readable.  The fourth parameter to
1369 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1370 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1371 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1372 ** WAL persistence setting.
1373 **
1374 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1375 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1376 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1377 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1378 ** xDeviceCharacteristics methods. The fourth parameter to
1379 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1380 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1381 ** mode.  If the integer is -1, then it is overwritten with the current
1382 ** zero-damage mode setting.
1383 **
1384 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1385 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1386 ** a write transaction to indicate that, unless it is rolled back for some
1387 ** reason, the entire database file will be overwritten by the current 
1388 ** transaction. This is used by VACUUM operations.
1389 **
1390 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1391 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1392 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1393 ** final bottom-level VFS are written into memory obtained from 
1394 ** [sqlite3_malloc()] and the result is stored in the char* variable
1395 ** that the fourth parameter of [sqlite3_file_control()] points to.
1396 ** The caller is responsible for freeing the memory when done.  As with
1397 ** all file-control actions, there is no guarantee that this will actually
1398 ** do anything.  Callers should initialize the char* variable to a NULL
1399 ** pointer in case this file-control is not implemented.  This file-control
1400 ** is intended for diagnostic use only.
1401 **
1402 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1403 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
1404 ** file control is sent to the open [sqlite3_file] object corresponding
1405 ** to the database file to which the pragma statement refers. ^The argument
1406 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1407 ** pointers to strings (char**) in which the second element of the array
1408 ** is the name of the pragma and the third element is the argument to the
1409 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1410 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1411 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1412 ** or the equivalent and that string will become the result of the pragma or
1413 ** the error message if the pragma fails. ^If the
1414 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
1415 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1416 ** file control returns [SQLITE_OK], then the parser assumes that the
1417 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1418 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1419 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1420 ** that the VFS encountered an error while handling the [PRAGMA] and the
1421 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1422 ** file control occurs at the beginning of pragma statement analysis and so
1423 ** it is able to override built-in [PRAGMA] statements.
1424 ** </ul>
1425 */
1426 #define SQLITE_FCNTL_LOCKSTATE               1
1427 #define SQLITE_GET_LOCKPROXYFILE             2
1428 #define SQLITE_SET_LOCKPROXYFILE             3
1429 #define SQLITE_LAST_ERRNO                    4
1430 #define SQLITE_FCNTL_SIZE_HINT               5
1431 #define SQLITE_FCNTL_CHUNK_SIZE              6
1432 #define SQLITE_FCNTL_FILE_POINTER            7
1433 #define SQLITE_FCNTL_SYNC_OMITTED            8
1434 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1435 #define SQLITE_FCNTL_PERSIST_WAL            10
1436 #define SQLITE_FCNTL_OVERWRITE              11
1437 #define SQLITE_FCNTL_VFSNAME                12
1438 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1439 #define SQLITE_FCNTL_PRAGMA                 14
1440
1441 /*
1442 ** CAPI3REF: Mutex Handle
1443 **
1444 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1445 ** abstract type for a mutex object.  The SQLite core never looks
1446 ** at the internal representation of an [sqlite3_mutex].  It only
1447 ** deals with pointers to the [sqlite3_mutex] object.
1448 **
1449 ** Mutexes are created using [sqlite3_mutex_alloc()].
1450 */
1451 typedef struct sqlite3_mutex sqlite3_mutex;
1452
1453 /*
1454 ** CAPI3REF: OS Interface Object
1455 **
1456 ** An instance of the sqlite3_vfs object defines the interface between
1457 ** the SQLite core and the underlying operating system.  The "vfs"
1458 ** in the name of the object stands for "virtual file system".  See
1459 ** the [VFS | VFS documentation] for further information.
1460 **
1461 ** The value of the iVersion field is initially 1 but may be larger in
1462 ** future versions of SQLite.  Additional fields may be appended to this
1463 ** object when the iVersion value is increased.  Note that the structure
1464 ** of the sqlite3_vfs object changes in the transaction between
1465 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1466 ** modified.
1467 **
1468 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1469 ** structure used by this VFS.  mxPathname is the maximum length of
1470 ** a pathname in this VFS.
1471 **
1472 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1473 ** the pNext pointer.  The [sqlite3_vfs_register()]
1474 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1475 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1476 ** searches the list.  Neither the application code nor the VFS
1477 ** implementation should use the pNext pointer.
1478 **
1479 ** The pNext field is the only field in the sqlite3_vfs
1480 ** structure that SQLite will ever modify.  SQLite will only access
1481 ** or modify this field while holding a particular static mutex.
1482 ** The application should never modify anything within the sqlite3_vfs
1483 ** object once the object has been registered.
1484 **
1485 ** The zName field holds the name of the VFS module.  The name must
1486 ** be unique across all VFS modules.
1487 **
1488 ** [[sqlite3_vfs.xOpen]]
1489 ** ^SQLite guarantees that the zFilename parameter to xOpen
1490 ** is either a NULL pointer or string obtained
1491 ** from xFullPathname() with an optional suffix added.
1492 ** ^If a suffix is added to the zFilename parameter, it will
1493 ** consist of a single "-" character followed by no more than
1494 ** 11 alphanumeric and/or "-" characters.
1495 ** ^SQLite further guarantees that
1496 ** the string will be valid and unchanged until xClose() is
1497 ** called. Because of the previous sentence,
1498 ** the [sqlite3_file] can safely store a pointer to the
1499 ** filename if it needs to remember the filename for some reason.
1500 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1501 ** must invent its own temporary name for the file.  ^Whenever the 
1502 ** xFilename parameter is NULL it will also be the case that the
1503 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1504 **
1505 ** The flags argument to xOpen() includes all bits set in
1506 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1507 ** or [sqlite3_open16()] is used, then flags includes at least
1508 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1509 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1510 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1511 **
1512 ** ^(SQLite will also add one of the following flags to the xOpen()
1513 ** call, depending on the object being opened:
1514 **
1515 ** <ul>
1516 ** <li>  [SQLITE_OPEN_MAIN_DB]
1517 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1518 ** <li>  [SQLITE_OPEN_TEMP_DB]
1519 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1520 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1521 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1522 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1523 ** <li>  [SQLITE_OPEN_WAL]
1524 ** </ul>)^
1525 **
1526 ** The file I/O implementation can use the object type flags to
1527 ** change the way it deals with files.  For example, an application
1528 ** that does not care about crash recovery or rollback might make
1529 ** the open of a journal file a no-op.  Writes to this journal would
1530 ** also be no-ops, and any attempt to read the journal would return
1531 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1532 ** file will be doing page-aligned sector reads and writes in a random
1533 ** order and set up its I/O subsystem accordingly.
1534 **
1535 ** SQLite might also add one of the following flags to the xOpen method:
1536 **
1537 ** <ul>
1538 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1539 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1540 ** </ul>
1541 **
1542 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1543 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1544 ** will be set for TEMP databases and their journals, transient
1545 ** databases, and subjournals.
1546 **
1547 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1548 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1549 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1550 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1551 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1552 ** be created, and that it is an error if it already exists.
1553 ** It is <i>not</i> used to indicate the file should be opened 
1554 ** for exclusive access.
1555 **
1556 ** ^At least szOsFile bytes of memory are allocated by SQLite
1557 ** to hold the  [sqlite3_file] structure passed as the third
1558 ** argument to xOpen.  The xOpen method does not have to
1559 ** allocate the structure; it should just fill it in.  Note that
1560 ** the xOpen method must set the sqlite3_file.pMethods to either
1561 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1562 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1563 ** element will be valid after xOpen returns regardless of the success
1564 ** or failure of the xOpen call.
1565 **
1566 ** [[sqlite3_vfs.xAccess]]
1567 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1568 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1569 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1570 ** to test whether a file is at least readable.   The file can be a
1571 ** directory.
1572 **
1573 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1574 ** output buffer xFullPathname.  The exact size of the output buffer
1575 ** is also passed as a parameter to both  methods. If the output buffer
1576 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1577 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1578 ** to prevent this by setting mxPathname to a sufficiently large value.
1579 **
1580 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1581 ** interfaces are not strictly a part of the filesystem, but they are
1582 ** included in the VFS structure for completeness.
1583 ** The xRandomness() function attempts to return nBytes bytes
1584 ** of good-quality randomness into zOut.  The return value is
1585 ** the actual number of bytes of randomness obtained.
1586 ** The xSleep() method causes the calling thread to sleep for at
1587 ** least the number of microseconds given.  ^The xCurrentTime()
1588 ** method returns a Julian Day Number for the current date and time as
1589 ** a floating point value.
1590 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1591 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1592 ** a 24-hour day).  
1593 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1594 ** date and time if that method is available (if iVersion is 2 or 
1595 ** greater and the function pointer is not NULL) and will fall back
1596 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1597 **
1598 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1599 ** are not used by the SQLite core.  These optional interfaces are provided
1600 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1601 ** system calls with functions under its control, a test program can
1602 ** simulate faults and error conditions that would otherwise be difficult
1603 ** or impossible to induce.  The set of system calls that can be overridden
1604 ** varies from one VFS to another, and from one version of the same VFS to the
1605 ** next.  Applications that use these interfaces must be prepared for any
1606 ** or all of these interfaces to be NULL or for their behavior to change
1607 ** from one release to the next.  Applications must not attempt to access
1608 ** any of these methods if the iVersion of the VFS is less than 3.
1609 */
1610 typedef struct sqlite3_vfs sqlite3_vfs;
1611 typedef void (*sqlite3_syscall_ptr)(void);
1612 struct sqlite3_vfs {
1613   int iVersion;            /* Structure version number (currently 3) */
1614   int szOsFile;            /* Size of subclassed sqlite3_file */
1615   int mxPathname;          /* Maximum file pathname length */
1616   sqlite3_vfs *pNext;      /* Next registered VFS */
1617   const char *zName;       /* Name of this virtual file system */
1618   void *pAppData;          /* Pointer to application-specific data */
1619   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1620                int flags, int *pOutFlags);
1621   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1622   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1623   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1624   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1625   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1626   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1627   void (*xDlClose)(sqlite3_vfs*, void*);
1628   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1629   int (*xSleep)(sqlite3_vfs*, int microseconds);
1630   int (*xCurrentTime)(sqlite3_vfs*, double*);
1631   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1632   /*
1633   ** The methods above are in version 1 of the sqlite_vfs object
1634   ** definition.  Those that follow are added in version 2 or later
1635   */
1636   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1637   /*
1638   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1639   ** Those below are for version 3 and greater.
1640   */
1641   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1642   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1643   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1644   /*
1645   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1646   ** New fields may be appended in figure versions.  The iVersion
1647   ** value will increment whenever this happens. 
1648   */
1649 };
1650
1651 /*
1652 ** CAPI3REF: Flags for the xAccess VFS method
1653 **
1654 ** These integer constants can be used as the third parameter to
1655 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1656 ** what kind of permissions the xAccess method is looking for.
1657 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1658 ** simply checks whether the file exists.
1659 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1660 ** checks whether the named directory is both readable and writable
1661 ** (in other words, if files can be added, removed, and renamed within
1662 ** the directory).
1663 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1664 ** [temp_store_directory pragma], though this could change in a future
1665 ** release of SQLite.
1666 ** With SQLITE_ACCESS_READ, the xAccess method
1667 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1668 ** currently unused, though it might be used in a future release of
1669 ** SQLite.
1670 */
1671 #define SQLITE_ACCESS_EXISTS    0
1672 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1673 #define SQLITE_ACCESS_READ      2   /* Unused */
1674
1675 /*
1676 ** CAPI3REF: Flags for the xShmLock VFS method
1677 **
1678 ** These integer constants define the various locking operations
1679 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1680 ** following are the only legal combinations of flags to the
1681 ** xShmLock method:
1682 **
1683 ** <ul>
1684 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1685 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1686 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1687 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1688 ** </ul>
1689 **
1690 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1691 ** was given no the corresponding lock.  
1692 **
1693 ** The xShmLock method can transition between unlocked and SHARED or
1694 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1695 ** and EXCLUSIVE.
1696 */
1697 #define SQLITE_SHM_UNLOCK       1
1698 #define SQLITE_SHM_LOCK         2
1699 #define SQLITE_SHM_SHARED       4
1700 #define SQLITE_SHM_EXCLUSIVE    8
1701
1702 /*
1703 ** CAPI3REF: Maximum xShmLock index
1704 **
1705 ** The xShmLock method on [sqlite3_io_methods] may use values
1706 ** between 0 and this upper bound as its "offset" argument.
1707 ** The SQLite core will never attempt to acquire or release a
1708 ** lock outside of this range
1709 */
1710 #define SQLITE_SHM_NLOCK        8
1711
1712
1713 /*
1714 ** CAPI3REF: Initialize The SQLite Library
1715 **
1716 ** ^The sqlite3_initialize() routine initializes the
1717 ** SQLite library.  ^The sqlite3_shutdown() routine
1718 ** deallocates any resources that were allocated by sqlite3_initialize().
1719 ** These routines are designed to aid in process initialization and
1720 ** shutdown on embedded systems.  Workstation applications using
1721 ** SQLite normally do not need to invoke either of these routines.
1722 **
1723 ** A call to sqlite3_initialize() is an "effective" call if it is
1724 ** the first time sqlite3_initialize() is invoked during the lifetime of
1725 ** the process, or if it is the first time sqlite3_initialize() is invoked
1726 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1727 ** of sqlite3_initialize() does any initialization.  All other calls
1728 ** are harmless no-ops.)^
1729 **
1730 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1731 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1732 ** an effective call to sqlite3_shutdown() does any deinitialization.
1733 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1734 **
1735 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1736 ** is not.  The sqlite3_shutdown() interface must only be called from a
1737 ** single thread.  All open [database connections] must be closed and all
1738 ** other SQLite resources must be deallocated prior to invoking
1739 ** sqlite3_shutdown().
1740 **
1741 ** Among other things, ^sqlite3_initialize() will invoke
1742 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1743 ** will invoke sqlite3_os_end().
1744 **
1745 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1746 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1747 ** the library (perhaps it is unable to allocate a needed resource such
1748 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1749 **
1750 ** ^The sqlite3_initialize() routine is called internally by many other
1751 ** SQLite interfaces so that an application usually does not need to
1752 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1753 ** calls sqlite3_initialize() so the SQLite library will be automatically
1754 ** initialized when [sqlite3_open()] is called if it has not be initialized
1755 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1756 ** compile-time option, then the automatic calls to sqlite3_initialize()
1757 ** are omitted and the application must call sqlite3_initialize() directly
1758 ** prior to using any other SQLite interface.  For maximum portability,
1759 ** it is recommended that applications always invoke sqlite3_initialize()
1760 ** directly prior to using any other SQLite interface.  Future releases
1761 ** of SQLite may require this.  In other words, the behavior exhibited
1762 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1763 ** default behavior in some future release of SQLite.
1764 **
1765 ** The sqlite3_os_init() routine does operating-system specific
1766 ** initialization of the SQLite library.  The sqlite3_os_end()
1767 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1768 ** performed by these routines include allocation or deallocation
1769 ** of static resources, initialization of global variables,
1770 ** setting up a default [sqlite3_vfs] module, or setting up
1771 ** a default configuration using [sqlite3_config()].
1772 **
1773 ** The application should never invoke either sqlite3_os_init()
1774 ** or sqlite3_os_end() directly.  The application should only invoke
1775 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1776 ** interface is called automatically by sqlite3_initialize() and
1777 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1778 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1779 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1780 ** When [custom builds | built for other platforms]
1781 ** (using the [SQLITE_OS_OTHER=1] compile-time
1782 ** option) the application must supply a suitable implementation for
1783 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1784 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1785 ** must return [SQLITE_OK] on success and some other [error code] upon
1786 ** failure.
1787 */
1788 SQLITE_API int sqlite3_initialize(void);
1789 SQLITE_API int sqlite3_shutdown(void);
1790 SQLITE_API int sqlite3_os_init(void);
1791 SQLITE_API int sqlite3_os_end(void);
1792
1793 /*
1794 ** CAPI3REF: Configuring The SQLite Library
1795 **
1796 ** The sqlite3_config() interface is used to make global configuration
1797 ** changes to SQLite in order to tune SQLite to the specific needs of
1798 ** the application.  The default configuration is recommended for most
1799 ** applications and so this routine is usually not necessary.  It is
1800 ** provided to support rare applications with unusual needs.
1801 **
1802 ** The sqlite3_config() interface is not threadsafe.  The application
1803 ** must insure that no other SQLite interfaces are invoked by other
1804 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1805 ** may only be invoked prior to library initialization using
1806 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1807 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1808 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1809 ** Note, however, that ^sqlite3_config() can be called as part of the
1810 ** implementation of an application-defined [sqlite3_os_init()].
1811 **
1812 ** The first argument to sqlite3_config() is an integer
1813 ** [configuration option] that determines
1814 ** what property of SQLite is to be configured.  Subsequent arguments
1815 ** vary depending on the [configuration option]
1816 ** in the first argument.
1817 **
1818 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1819 ** ^If the option is unknown or SQLite is unable to set the option
1820 ** then this routine returns a non-zero [error code].
1821 */
1822 SQLITE_API int sqlite3_config(int, ...);
1823
1824 /*
1825 ** CAPI3REF: Configure database connections
1826 **
1827 ** The sqlite3_db_config() interface is used to make configuration
1828 ** changes to a [database connection].  The interface is similar to
1829 ** [sqlite3_config()] except that the changes apply to a single
1830 ** [database connection] (specified in the first argument).
1831 **
1832 ** The second argument to sqlite3_db_config(D,V,...)  is the
1833 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1834 ** that indicates what aspect of the [database connection] is being configured.
1835 ** Subsequent arguments vary depending on the configuration verb.
1836 **
1837 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1838 ** the call is considered successful.
1839 */
1840 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1841
1842 /*
1843 ** CAPI3REF: Memory Allocation Routines
1844 **
1845 ** An instance of this object defines the interface between SQLite
1846 ** and low-level memory allocation routines.
1847 **
1848 ** This object is used in only one place in the SQLite interface.
1849 ** A pointer to an instance of this object is the argument to
1850 ** [sqlite3_config()] when the configuration option is
1851 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1852 ** By creating an instance of this object
1853 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1854 ** during configuration, an application can specify an alternative
1855 ** memory allocation subsystem for SQLite to use for all of its
1856 ** dynamic memory needs.
1857 **
1858 ** Note that SQLite comes with several [built-in memory allocators]
1859 ** that are perfectly adequate for the overwhelming majority of applications
1860 ** and that this object is only useful to a tiny minority of applications
1861 ** with specialized memory allocation requirements.  This object is
1862 ** also used during testing of SQLite in order to specify an alternative
1863 ** memory allocator that simulates memory out-of-memory conditions in
1864 ** order to verify that SQLite recovers gracefully from such
1865 ** conditions.
1866 **
1867 ** The xMalloc, xRealloc, and xFree methods must work like the
1868 ** malloc(), realloc() and free() functions from the standard C library.
1869 ** ^SQLite guarantees that the second argument to
1870 ** xRealloc is always a value returned by a prior call to xRoundup.
1871 **
1872 ** xSize should return the allocated size of a memory allocation
1873 ** previously obtained from xMalloc or xRealloc.  The allocated size
1874 ** is always at least as big as the requested size but may be larger.
1875 **
1876 ** The xRoundup method returns what would be the allocated size of
1877 ** a memory allocation given a particular requested size.  Most memory
1878 ** allocators round up memory allocations at least to the next multiple
1879 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1880 ** Every memory allocation request coming in through [sqlite3_malloc()]
1881 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1882 ** that causes the corresponding memory allocation to fail.
1883 **
1884 ** The xInit method initializes the memory allocator.  (For example,
1885 ** it might allocate any require mutexes or initialize internal data
1886 ** structures.  The xShutdown method is invoked (indirectly) by
1887 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1888 ** by xInit.  The pAppData pointer is used as the only parameter to
1889 ** xInit and xShutdown.
1890 **
1891 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1892 ** the xInit method, so the xInit method need not be threadsafe.  The
1893 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1894 ** not need to be threadsafe either.  For all other methods, SQLite
1895 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1896 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1897 ** it is by default) and so the methods are automatically serialized.
1898 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1899 ** methods must be threadsafe or else make their own arrangements for
1900 ** serialization.
1901 **
1902 ** SQLite will never invoke xInit() more than once without an intervening
1903 ** call to xShutdown().
1904 */
1905 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1906 struct sqlite3_mem_methods {
1907   void *(*xMalloc)(int);         /* Memory allocation function */
1908   void (*xFree)(void*);          /* Free a prior allocation */
1909   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1910   int (*xSize)(void*);           /* Return the size of an allocation */
1911   int (*xRoundup)(int);          /* Round up request size to allocation size */
1912   int (*xInit)(void*);           /* Initialize the memory allocator */
1913   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1914   void *pAppData;                /* Argument to xInit() and xShutdown() */
1915 };
1916
1917 /*
1918 ** CAPI3REF: Configuration Options
1919 ** KEYWORDS: {configuration option}
1920 **
1921 ** These constants are the available integer configuration options that
1922 ** can be passed as the first argument to the [sqlite3_config()] interface.
1923 **
1924 ** New configuration options may be added in future releases of SQLite.
1925 ** Existing configuration options might be discontinued.  Applications
1926 ** should check the return code from [sqlite3_config()] to make sure that
1927 ** the call worked.  The [sqlite3_config()] interface will return a
1928 ** non-zero [error code] if a discontinued or unsupported configuration option
1929 ** is invoked.
1930 **
1931 ** <dl>
1932 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1933 ** <dd>There are no arguments to this option.  ^This option sets the
1934 ** [threading mode] to Single-thread.  In other words, it disables
1935 ** all mutexing and puts SQLite into a mode where it can only be used
1936 ** by a single thread.   ^If SQLite is compiled with
1937 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1938 ** it is not possible to change the [threading mode] from its default
1939 ** value of Single-thread and so [sqlite3_config()] will return 
1940 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1941 ** configuration option.</dd>
1942 **
1943 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1944 ** <dd>There are no arguments to this option.  ^This option sets the
1945 ** [threading mode] to Multi-thread.  In other words, it disables
1946 ** mutexing on [database connection] and [prepared statement] objects.
1947 ** The application is responsible for serializing access to
1948 ** [database connections] and [prepared statements].  But other mutexes
1949 ** are enabled so that SQLite will be safe to use in a multi-threaded
1950 ** environment as long as no two threads attempt to use the same
1951 ** [database connection] at the same time.  ^If SQLite is compiled with
1952 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1953 ** it is not possible to set the Multi-thread [threading mode] and
1954 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1955 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1956 **
1957 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1958 ** <dd>There are no arguments to this option.  ^This option sets the
1959 ** [threading mode] to Serialized. In other words, this option enables
1960 ** all mutexes including the recursive
1961 ** mutexes on [database connection] and [prepared statement] objects.
1962 ** In this mode (which is the default when SQLite is compiled with
1963 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1964 ** to [database connections] and [prepared statements] so that the
1965 ** application is free to use the same [database connection] or the
1966 ** same [prepared statement] in different threads at the same time.
1967 ** ^If SQLite is compiled with
1968 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1969 ** it is not possible to set the Serialized [threading mode] and
1970 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1971 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1972 **
1973 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1974 ** <dd> ^(This option takes a single argument which is a pointer to an
1975 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1976 ** alternative low-level memory allocation routines to be used in place of
1977 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1978 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1979 ** before the [sqlite3_config()] call returns.</dd>
1980 **
1981 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1982 ** <dd> ^(This option takes a single argument which is a pointer to an
1983 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1984 ** structure is filled with the currently defined memory allocation routines.)^
1985 ** This option can be used to overload the default memory allocation
1986 ** routines with a wrapper that simulations memory allocation failure or
1987 ** tracks memory usage, for example. </dd>
1988 **
1989 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1990 ** <dd> ^This option takes single argument of type int, interpreted as a 
1991 ** boolean, which enables or disables the collection of memory allocation 
1992 ** statistics. ^(When memory allocation statistics are disabled, the 
1993 ** following SQLite interfaces become non-operational:
1994 **   <ul>
1995 **   <li> [sqlite3_memory_used()]
1996 **   <li> [sqlite3_memory_highwater()]
1997 **   <li> [sqlite3_soft_heap_limit64()]
1998 **   <li> [sqlite3_status()]
1999 **   </ul>)^
2000 ** ^Memory allocation statistics are enabled by default unless SQLite is
2001 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2002 ** allocation statistics are disabled by default.
2003 ** </dd>
2004 **
2005 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2006 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2007 ** scratch memory.  There are three arguments:  A pointer an 8-byte
2008 ** aligned memory buffer from which the scratch allocations will be
2009 ** drawn, the size of each scratch allocation (sz),
2010 ** and the maximum number of scratch allocations (N).  The sz
2011 ** argument must be a multiple of 16.
2012 ** The first argument must be a pointer to an 8-byte aligned buffer
2013 ** of at least sz*N bytes of memory.
2014 ** ^SQLite will use no more than two scratch buffers per thread.  So
2015 ** N should be set to twice the expected maximum number of threads.
2016 ** ^SQLite will never require a scratch buffer that is more than 6
2017 ** times the database page size. ^If SQLite needs needs additional
2018 ** scratch memory beyond what is provided by this configuration option, then 
2019 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2020 **
2021 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2022 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2023 ** the database page cache with the default page cache implementation.  
2024 ** This configuration should not be used if an application-define page
2025 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2026 ** There are three arguments to this option: A pointer to 8-byte aligned
2027 ** memory, the size of each page buffer (sz), and the number of pages (N).
2028 ** The sz argument should be the size of the largest database page
2029 ** (a power of two between 512 and 32768) plus a little extra for each
2030 ** page header.  ^The page header size is 20 to 40 bytes depending on
2031 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2032 ** to make sz a little too large.  The first
2033 ** argument should point to an allocation of at least sz*N bytes of memory.
2034 ** ^SQLite will use the memory provided by the first argument to satisfy its
2035 ** memory needs for the first N pages that it adds to cache.  ^If additional
2036 ** page cache memory is needed beyond what is provided by this option, then
2037 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2038 ** The pointer in the first argument must
2039 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2040 ** will be undefined.</dd>
2041 **
2042 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2043 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2044 ** for all of its dynamic memory allocation needs beyond those provided
2045 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2046 ** There are three arguments: An 8-byte aligned pointer to the memory,
2047 ** the number of bytes in the memory buffer, and the minimum allocation size.
2048 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2049 ** to using its default memory allocator (the system malloc() implementation),
2050 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2051 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2052 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2053 ** allocator is engaged to handle all of SQLites memory allocation needs.
2054 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2055 ** boundary or subsequent behavior of SQLite will be undefined.
2056 ** The minimum allocation size is capped at 2**12. Reasonable values
2057 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2058 **
2059 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2060 ** <dd> ^(This option takes a single argument which is a pointer to an
2061 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2062 ** alternative low-level mutex routines to be used in place
2063 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2064 ** content of the [sqlite3_mutex_methods] structure before the call to
2065 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2066 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2067 ** the entire mutexing subsystem is omitted from the build and hence calls to
2068 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2069 ** return [SQLITE_ERROR].</dd>
2070 **
2071 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2072 ** <dd> ^(This option takes a single argument which is a pointer to an
2073 ** instance of the [sqlite3_mutex_methods] structure.  The
2074 ** [sqlite3_mutex_methods]
2075 ** structure is filled with the currently defined mutex routines.)^
2076 ** This option can be used to overload the default mutex allocation
2077 ** routines with a wrapper used to track mutex usage for performance
2078 ** profiling or testing, for example.   ^If SQLite is compiled with
2079 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2080 ** the entire mutexing subsystem is omitted from the build and hence calls to
2081 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2082 ** return [SQLITE_ERROR].</dd>
2083 **
2084 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2085 ** <dd> ^(This option takes two arguments that determine the default
2086 ** memory allocation for the lookaside memory allocator on each
2087 ** [database connection].  The first argument is the
2088 ** size of each lookaside buffer slot and the second is the number of
2089 ** slots allocated to each database connection.)^  ^(This option sets the
2090 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2091 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2092 ** configuration on individual connections.)^ </dd>
2093 **
2094 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2095 ** <dd> ^(This option takes a single argument which is a pointer to
2096 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2097 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2098 ** object and uses it for page cache memory allocations.</dd>
2099 **
2100 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2101 ** <dd> ^(This option takes a single argument which is a pointer to an
2102 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2103 ** page cache implementation into that object.)^ </dd>
2104 **
2105 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2106 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2107 ** function with a call signature of void(*)(void*,int,const char*), 
2108 ** and a pointer to void. ^If the function pointer is not NULL, it is
2109 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2110 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2111 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2112 ** passed through as the first parameter to the application-defined logger
2113 ** function whenever that function is invoked.  ^The second parameter to
2114 ** the logger function is a copy of the first parameter to the corresponding
2115 ** [sqlite3_log()] call and is intended to be a [result code] or an
2116 ** [extended result code].  ^The third parameter passed to the logger is
2117 ** log message after formatting via [sqlite3_snprintf()].
2118 ** The SQLite logging interface is not reentrant; the logger function
2119 ** supplied by the application must not invoke any SQLite interface.
2120 ** In a multi-threaded application, the application-defined logger
2121 ** function must be threadsafe. </dd>
2122 **
2123 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2124 ** <dd> This option takes a single argument of type int. If non-zero, then
2125 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2126 ** is globally disabled. If URI handling is globally enabled, all filenames
2127 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2128 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2129 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2130 ** connection is opened. If it is globally disabled, filenames are
2131 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2132 ** database connection is opened. By default, URI handling is globally
2133 ** disabled. The default value may be changed by compiling with the
2134 ** [SQLITE_USE_URI] symbol defined.
2135 **
2136 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2137 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2138 ** <dd> These options are obsolete and should not be used by new code.
2139 ** They are retained for backwards compatibility but are now no-ops.
2140 ** </dl>
2141 */
2142 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2143 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2144 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2145 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2146 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2147 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2148 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2149 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2150 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2151 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2152 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2153 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2154 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2155 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2156 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2157 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2158 #define SQLITE_CONFIG_URI          17  /* int */
2159 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2160 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2161
2162 /*
2163 ** CAPI3REF: Database Connection Configuration Options
2164 **
2165 ** These constants are the available integer configuration options that
2166 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2167 **
2168 ** New configuration options may be added in future releases of SQLite.
2169 ** Existing configuration options might be discontinued.  Applications
2170 ** should check the return code from [sqlite3_db_config()] to make sure that
2171 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2172 ** non-zero [error code] if a discontinued or unsupported configuration option
2173 ** is invoked.
2174 **
2175 ** <dl>
2176 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2177 ** <dd> ^This option takes three additional arguments that determine the 
2178 ** [lookaside memory allocator] configuration for the [database connection].
2179 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2180 ** pointer to a memory buffer to use for lookaside memory.
2181 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2182 ** may be NULL in which case SQLite will allocate the
2183 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2184 ** size of each lookaside buffer slot.  ^The third argument is the number of
2185 ** slots.  The size of the buffer in the first argument must be greater than
2186 ** or equal to the product of the second and third arguments.  The buffer
2187 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2188 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2189 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2190 ** configuration for a database connection can only be changed when that
2191 ** connection is not currently using lookaside memory, or in other words
2192 ** when the "current value" returned by
2193 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2194 ** Any attempt to change the lookaside memory configuration when lookaside
2195 ** memory is in use leaves the configuration unchanged and returns 
2196 ** [SQLITE_BUSY].)^</dd>
2197 **
2198 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2199 ** <dd> ^This option is used to enable or disable the enforcement of
2200 ** [foreign key constraints].  There should be two additional arguments.
2201 ** The first argument is an integer which is 0 to disable FK enforcement,
2202 ** positive to enable FK enforcement or negative to leave FK enforcement
2203 ** unchanged.  The second parameter is a pointer to an integer into which
2204 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2205 ** following this call.  The second parameter may be a NULL pointer, in
2206 ** which case the FK enforcement setting is not reported back. </dd>
2207 **
2208 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2209 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2210 ** There should be two additional arguments.
2211 ** The first argument is an integer which is 0 to disable triggers,
2212 ** positive to enable triggers or negative to leave the setting unchanged.
2213 ** The second parameter is a pointer to an integer into which
2214 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2215 ** following this call.  The second parameter may be a NULL pointer, in
2216 ** which case the trigger setting is not reported back. </dd>
2217 **
2218 ** </dl>
2219 */
2220 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2221 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2222 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2223
2224
2225 /*
2226 ** CAPI3REF: Enable Or Disable Extended Result Codes
2227 **
2228 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2229 ** [extended result codes] feature of SQLite. ^The extended result
2230 ** codes are disabled by default for historical compatibility.
2231 */
2232 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2233
2234 /*
2235 ** CAPI3REF: Last Insert Rowid
2236 **
2237 ** ^Each entry in an SQLite table has a unique 64-bit signed
2238 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2239 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2240 ** names are not also used by explicitly declared columns. ^If
2241 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2242 ** is another alias for the rowid.
2243 **
2244 ** ^This routine returns the [rowid] of the most recent
2245 ** successful [INSERT] into the database from the [database connection]
2246 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2247 ** records the last insert rowid of both ordinary tables and [virtual tables].
2248 ** ^If no successful [INSERT]s
2249 ** have ever occurred on that database connection, zero is returned.
2250 **
2251 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2252 ** method, then this routine will return the [rowid] of the inserted
2253 ** row as long as the trigger or virtual table method is running.
2254 ** But once the trigger or virtual table method ends, the value returned 
2255 ** by this routine reverts to what it was before the trigger or virtual
2256 ** table method began.)^
2257 **
2258 ** ^An [INSERT] that fails due to a constraint violation is not a
2259 ** successful [INSERT] and does not change the value returned by this
2260 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2261 ** and INSERT OR ABORT make no changes to the return value of this
2262 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2263 ** encounters a constraint violation, it does not fail.  The
2264 ** INSERT continues to completion after deleting rows that caused
2265 ** the constraint problem so INSERT OR REPLACE will always change
2266 ** the return value of this interface.)^
2267 **
2268 ** ^For the purposes of this routine, an [INSERT] is considered to
2269 ** be successful even if it is subsequently rolled back.
2270 **
2271 ** This function is accessible to SQL statements via the
2272 ** [last_insert_rowid() SQL function].
2273 **
2274 ** If a separate thread performs a new [INSERT] on the same
2275 ** database connection while the [sqlite3_last_insert_rowid()]
2276 ** function is running and thus changes the last insert [rowid],
2277 ** then the value returned by [sqlite3_last_insert_rowid()] is
2278 ** unpredictable and might not equal either the old or the new
2279 ** last insert [rowid].
2280 */
2281 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2282
2283 /*
2284 ** CAPI3REF: Count The Number Of Rows Modified
2285 **
2286 ** ^This function returns the number of database rows that were changed
2287 ** or inserted or deleted by the most recently completed SQL statement
2288 ** on the [database connection] specified by the first parameter.
2289 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2290 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2291 ** triggers or [foreign key actions] are not counted.)^ Use the
2292 ** [sqlite3_total_changes()] function to find the total number of changes
2293 ** including changes caused by triggers and foreign key actions.
2294 **
2295 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2296 ** are not counted.  Only real table changes are counted.
2297 **
2298 ** ^(A "row change" is a change to a single row of a single table
2299 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2300 ** are changed as side effects of [REPLACE] constraint resolution,
2301 ** rollback, ABORT processing, [DROP TABLE], or by any other
2302 ** mechanisms do not count as direct row changes.)^
2303 **
2304 ** A "trigger context" is a scope of execution that begins and
2305 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2306 ** Most SQL statements are
2307 ** evaluated outside of any trigger.  This is the "top level"
2308 ** trigger context.  If a trigger fires from the top level, a
2309 ** new trigger context is entered for the duration of that one
2310 ** trigger.  Subtriggers create subcontexts for their duration.
2311 **
2312 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2313 ** not create a new trigger context.
2314 **
2315 ** ^This function returns the number of direct row changes in the
2316 ** most recent INSERT, UPDATE, or DELETE statement within the same
2317 ** trigger context.
2318 **
2319 ** ^Thus, when called from the top level, this function returns the
2320 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2321 ** that also occurred at the top level.  ^(Within the body of a trigger,
2322 ** the sqlite3_changes() interface can be called to find the number of
2323 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2324 ** statement within the body of the same trigger.
2325 ** However, the number returned does not include changes
2326 ** caused by subtriggers since those have their own context.)^
2327 **
2328 ** See also the [sqlite3_total_changes()] interface, the
2329 ** [count_changes pragma], and the [changes() SQL function].
2330 **
2331 ** If a separate thread makes changes on the same database connection
2332 ** while [sqlite3_changes()] is running then the value returned
2333 ** is unpredictable and not meaningful.
2334 */
2335 SQLITE_API int sqlite3_changes(sqlite3*);
2336
2337 /*
2338 ** CAPI3REF: Total Number Of Rows Modified
2339 **
2340 ** ^This function returns the number of row changes caused by [INSERT],
2341 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2342 ** ^(The count returned by sqlite3_total_changes() includes all changes
2343 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2344 ** [foreign key actions]. However,
2345 ** the count does not include changes used to implement [REPLACE] constraints,
2346 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2347 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2348 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2349 ** are counted.)^
2350 ** ^The sqlite3_total_changes() function counts the changes as soon as
2351 ** the statement that makes them is completed (when the statement handle
2352 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2353 **
2354 ** See also the [sqlite3_changes()] interface, the
2355 ** [count_changes pragma], and the [total_changes() SQL function].
2356 **
2357 ** If a separate thread makes changes on the same database connection
2358 ** while [sqlite3_total_changes()] is running then the value
2359 ** returned is unpredictable and not meaningful.
2360 */
2361 SQLITE_API int sqlite3_total_changes(sqlite3*);
2362
2363 /*
2364 ** CAPI3REF: Interrupt A Long-Running Query
2365 **
2366 ** ^This function causes any pending database operation to abort and
2367 ** return at its earliest opportunity. This routine is typically
2368 ** called in response to a user action such as pressing "Cancel"
2369 ** or Ctrl-C where the user wants a long query operation to halt
2370 ** immediately.
2371 **
2372 ** ^It is safe to call this routine from a thread different from the
2373 ** thread that is currently running the database operation.  But it
2374 ** is not safe to call this routine with a [database connection] that
2375 ** is closed or might close before sqlite3_interrupt() returns.
2376 **
2377 ** ^If an SQL operation is very nearly finished at the time when
2378 ** sqlite3_interrupt() is called, then it might not have an opportunity
2379 ** to be interrupted and might continue to completion.
2380 **
2381 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2382 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2383 ** that is inside an explicit transaction, then the entire transaction
2384 ** will be rolled back automatically.
2385 **
2386 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2387 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2388 ** that are started after the sqlite3_interrupt() call and before the 
2389 ** running statements reaches zero are interrupted as if they had been
2390 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2391 ** that are started after the running statement count reaches zero are
2392 ** not effected by the sqlite3_interrupt().
2393 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2394 ** SQL statements is a no-op and has no effect on SQL statements
2395 ** that are started after the sqlite3_interrupt() call returns.
2396 **
2397 ** If the database connection closes while [sqlite3_interrupt()]
2398 ** is running then bad things will likely happen.
2399 */
2400 SQLITE_API void sqlite3_interrupt(sqlite3*);
2401
2402 /*
2403 ** CAPI3REF: Determine If An SQL Statement Is Complete
2404 **
2405 ** These routines are useful during command-line input to determine if the
2406 ** currently entered text seems to form a complete SQL statement or
2407 ** if additional input is needed before sending the text into
2408 ** SQLite for parsing.  ^These routines return 1 if the input string
2409 ** appears to be a complete SQL statement.  ^A statement is judged to be
2410 ** complete if it ends with a semicolon token and is not a prefix of a
2411 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2412 ** string literals or quoted identifier names or comments are not
2413 ** independent tokens (they are part of the token in which they are
2414 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2415 ** and comments that follow the final semicolon are ignored.
2416 **
2417 ** ^These routines return 0 if the statement is incomplete.  ^If a
2418 ** memory allocation fails, then SQLITE_NOMEM is returned.
2419 **
2420 ** ^These routines do not parse the SQL statements thus
2421 ** will not detect syntactically incorrect SQL.
2422 **
2423 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2424 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2425 ** automatically by sqlite3_complete16().  If that initialization fails,
2426 ** then the return value from sqlite3_complete16() will be non-zero
2427 ** regardless of whether or not the input SQL is complete.)^
2428 **
2429 ** The input to [sqlite3_complete()] must be a zero-terminated
2430 ** UTF-8 string.
2431 **
2432 ** The input to [sqlite3_complete16()] must be a zero-terminated
2433 ** UTF-16 string in native byte order.
2434 */
2435 SQLITE_API int sqlite3_complete(const char *sql);
2436 SQLITE_API int sqlite3_complete16(const void *sql);
2437
2438 /*
2439 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2440 **
2441 ** ^This routine sets a callback function that might be invoked whenever
2442 ** an attempt is made to open a database table that another thread
2443 ** or process has locked.
2444 **
2445 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2446 ** is returned immediately upon encountering the lock.  ^If the busy callback
2447 ** is not NULL, then the callback might be invoked with two arguments.
2448 **
2449 ** ^The first argument to the busy handler is a copy of the void* pointer which
2450 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2451 ** the busy handler callback is the number of times that the busy handler has
2452 ** been invoked for this locking event.  ^If the
2453 ** busy callback returns 0, then no additional attempts are made to
2454 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2455 ** ^If the callback returns non-zero, then another attempt
2456 ** is made to open the database for reading and the cycle repeats.
2457 **
2458 ** The presence of a busy handler does not guarantee that it will be invoked
2459 ** when there is lock contention. ^If SQLite determines that invoking the busy
2460 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2461 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2462 ** Consider a scenario where one process is holding a read lock that
2463 ** it is trying to promote to a reserved lock and
2464 ** a second process is holding a reserved lock that it is trying
2465 ** to promote to an exclusive lock.  The first process cannot proceed
2466 ** because it is blocked by the second and the second process cannot
2467 ** proceed because it is blocked by the first.  If both processes
2468 ** invoke the busy handlers, neither will make any progress.  Therefore,
2469 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2470 ** will induce the first process to release its read lock and allow
2471 ** the second process to proceed.
2472 **
2473 ** ^The default busy callback is NULL.
2474 **
2475 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2476 ** when SQLite is in the middle of a large transaction where all the
2477 ** changes will not fit into the in-memory cache.  SQLite will
2478 ** already hold a RESERVED lock on the database file, but it needs
2479 ** to promote this lock to EXCLUSIVE so that it can spill cache
2480 ** pages into the database file without harm to concurrent
2481 ** readers.  ^If it is unable to promote the lock, then the in-memory
2482 ** cache will be left in an inconsistent state and so the error
2483 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2484 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2485 ** forces an automatic rollback of the changes.  See the
2486 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2487 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2488 ** this is important.
2489 **
2490 ** ^(There can only be a single busy handler defined for each
2491 ** [database connection].  Setting a new busy handler clears any
2492 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2493 ** will also set or clear the busy handler.
2494 **
2495 ** The busy callback should not take any actions which modify the
2496 ** database connection that invoked the busy handler.  Any such actions
2497 ** result in undefined behavior.
2498 ** 
2499 ** A busy handler must not close the database connection
2500 ** or [prepared statement] that invoked the busy handler.
2501 */
2502 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2503
2504 /*
2505 ** CAPI3REF: Set A Busy Timeout
2506 **
2507 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2508 ** for a specified amount of time when a table is locked.  ^The handler
2509 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2510 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2511 ** the handler returns 0 which causes [sqlite3_step()] to return
2512 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2513 **
2514 ** ^Calling this routine with an argument less than or equal to zero
2515 ** turns off all busy handlers.
2516 **
2517 ** ^(There can only be a single busy handler for a particular
2518 ** [database connection] any any given moment.  If another busy handler
2519 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2520 ** this routine, that other busy handler is cleared.)^
2521 */
2522 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2523
2524 /*
2525 ** CAPI3REF: Convenience Routines For Running Queries
2526 **
2527 ** This is a legacy interface that is preserved for backwards compatibility.
2528 ** Use of this interface is not recommended.
2529 **
2530 ** Definition: A <b>result table</b> is memory data structure created by the
2531 ** [sqlite3_get_table()] interface.  A result table records the
2532 ** complete query results from one or more queries.
2533 **
2534 ** The table conceptually has a number of rows and columns.  But
2535 ** these numbers are not part of the result table itself.  These
2536 ** numbers are obtained separately.  Let N be the number of rows
2537 ** and M be the number of columns.
2538 **
2539 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2540 ** There are (N+1)*M elements in the array.  The first M pointers point
2541 ** to zero-terminated strings that  contain the names of the columns.
2542 ** The remaining entries all point to query results.  NULL values result
2543 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2544 ** string representation as returned by [sqlite3_column_text()].
2545 **
2546 ** A result table might consist of one or more memory allocations.
2547 ** It is not safe to pass a result table directly to [sqlite3_free()].
2548 ** A result table should be deallocated using [sqlite3_free_table()].
2549 **
2550 ** ^(As an example of the result table format, suppose a query result
2551 ** is as follows:
2552 **
2553 ** <blockquote><pre>
2554 **        Name        | Age
2555 **        -----------------------
2556 **        Alice       | 43
2557 **        Bob         | 28
2558 **        Cindy       | 21
2559 ** </pre></blockquote>
2560 **
2561 ** There are two column (M==2) and three rows (N==3).  Thus the
2562 ** result table has 8 entries.  Suppose the result table is stored
2563 ** in an array names azResult.  Then azResult holds this content:
2564 **
2565 ** <blockquote><pre>
2566 **        azResult&#91;0] = "Name";
2567 **        azResult&#91;1] = "Age";
2568 **        azResult&#91;2] = "Alice";
2569 **        azResult&#91;3] = "43";
2570 **        azResult&#91;4] = "Bob";
2571 **        azResult&#91;5] = "28";
2572 **        azResult&#91;6] = "Cindy";
2573 **        azResult&#91;7] = "21";
2574 ** </pre></blockquote>)^
2575 **
2576 ** ^The sqlite3_get_table() function evaluates one or more
2577 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2578 ** string of its 2nd parameter and returns a result table to the
2579 ** pointer given in its 3rd parameter.
2580 **
2581 ** After the application has finished with the result from sqlite3_get_table(),
2582 ** it must pass the result table pointer to sqlite3_free_table() in order to
2583 ** release the memory that was malloced.  Because of the way the
2584 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2585 ** function must not try to call [sqlite3_free()] directly.  Only
2586 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2587 **
2588 ** The sqlite3_get_table() interface is implemented as a wrapper around
2589 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2590 ** to any internal data structures of SQLite.  It uses only the public
2591 ** interface defined here.  As a consequence, errors that occur in the
2592 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2593 ** reflected in subsequent calls to [sqlite3_errcode()] or
2594 ** [sqlite3_errmsg()].
2595 */
2596 SQLITE_API int sqlite3_get_table(
2597   sqlite3 *db,          /* An open database */
2598   const char *zSql,     /* SQL to be evaluated */
2599   char ***pazResult,    /* Results of the query */
2600   int *pnRow,           /* Number of result rows written here */
2601   int *pnColumn,        /* Number of result columns written here */
2602   char **pzErrmsg       /* Error msg written here */
2603 );
2604 SQLITE_API void sqlite3_free_table(char **result);
2605
2606 /*
2607 ** CAPI3REF: Formatted String Printing Functions
2608 **
2609 ** These routines are work-alikes of the "printf()" family of functions
2610 ** from the standard C library.
2611 **
2612 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2613 ** results into memory obtained from [sqlite3_malloc()].
2614 ** The strings returned by these two routines should be
2615 ** released by [sqlite3_free()].  ^Both routines return a
2616 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2617 ** memory to hold the resulting string.
2618 **
2619 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2620 ** the standard C library.  The result is written into the
2621 ** buffer supplied as the second parameter whose size is given by
2622 ** the first parameter. Note that the order of the
2623 ** first two parameters is reversed from snprintf().)^  This is an
2624 ** historical accident that cannot be fixed without breaking
2625 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2626 ** returns a pointer to its buffer instead of the number of
2627 ** characters actually written into the buffer.)^  We admit that
2628 ** the number of characters written would be a more useful return
2629 ** value but we cannot change the implementation of sqlite3_snprintf()
2630 ** now without breaking compatibility.
2631 **
2632 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2633 ** guarantees that the buffer is always zero-terminated.  ^The first
2634 ** parameter "n" is the total size of the buffer, including space for
2635 ** the zero terminator.  So the longest string that can be completely
2636 ** written will be n-1 characters.
2637 **
2638 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2639 **
2640 ** These routines all implement some additional formatting
2641 ** options that are useful for constructing SQL statements.
2642 ** All of the usual printf() formatting options apply.  In addition, there
2643 ** is are "%q", "%Q", and "%z" options.
2644 **
2645 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2646 ** string from the argument list.  But %q also doubles every '\'' character.
2647 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2648 ** character it escapes that character and allows it to be inserted into
2649 ** the string.
2650 **
2651 ** For example, assume the string variable zText contains text as follows:
2652 **
2653 ** <blockquote><pre>
2654 **  char *zText = "It's a happy day!";
2655 ** </pre></blockquote>
2656 **
2657 ** One can use this text in an SQL statement as follows:
2658 **
2659 ** <blockquote><pre>
2660 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2661 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2662 **  sqlite3_free(zSQL);
2663 ** </pre></blockquote>
2664 **
2665 ** Because the %q format string is used, the '\'' character in zText
2666 ** is escaped and the SQL generated is as follows:
2667 **
2668 ** <blockquote><pre>
2669 **  INSERT INTO table1 VALUES('It''s a happy day!')
2670 ** </pre></blockquote>
2671 **
2672 ** This is correct.  Had we used %s instead of %q, the generated SQL
2673 ** would have looked like this:
2674 **
2675 ** <blockquote><pre>
2676 **  INSERT INTO table1 VALUES('It's a happy day!');
2677 ** </pre></blockquote>
2678 **
2679 ** This second example is an SQL syntax error.  As a general rule you should
2680 ** always use %q instead of %s when inserting text into a string literal.
2681 **
2682 ** ^(The %Q option works like %q except it also adds single quotes around
2683 ** the outside of the total string.  Additionally, if the parameter in the
2684 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2685 ** single quotes).)^  So, for example, one could say:
2686 **
2687 ** <blockquote><pre>
2688 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2689 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2690 **  sqlite3_free(zSQL);
2691 ** </pre></blockquote>
2692 **
2693 ** The code above will render a correct SQL statement in the zSQL
2694 ** variable even if the zText variable is a NULL pointer.
2695 **
2696 ** ^(The "%z" formatting option works like "%s" but with the
2697 ** addition that after the string has been read and copied into
2698 ** the result, [sqlite3_free()] is called on the input string.)^
2699 */
2700 SQLITE_API char *sqlite3_mprintf(const char*,...);
2701 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2702 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2703 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2704
2705 /*
2706 ** CAPI3REF: Memory Allocation Subsystem
2707 **
2708 ** The SQLite core uses these three routines for all of its own
2709 ** internal memory allocation needs. "Core" in the previous sentence
2710 ** does not include operating-system specific VFS implementation.  The
2711 ** Windows VFS uses native malloc() and free() for some operations.
2712 **
2713 ** ^The sqlite3_malloc() routine returns a pointer to a block
2714 ** of memory at least N bytes in length, where N is the parameter.
2715 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2716 ** memory, it returns a NULL pointer.  ^If the parameter N to
2717 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2718 ** a NULL pointer.
2719 **
2720 ** ^Calling sqlite3_free() with a pointer previously returned
2721 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2722 ** that it might be reused.  ^The sqlite3_free() routine is
2723 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2724 ** to sqlite3_free() is harmless.  After being freed, memory
2725 ** should neither be read nor written.  Even reading previously freed
2726 ** memory might result in a segmentation fault or other severe error.
2727 ** Memory corruption, a segmentation fault, or other severe error
2728 ** might result if sqlite3_free() is called with a non-NULL pointer that
2729 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2730 **
2731 ** ^(The sqlite3_realloc() interface attempts to resize a
2732 ** prior memory allocation to be at least N bytes, where N is the
2733 ** second parameter.  The memory allocation to be resized is the first
2734 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2735 ** is a NULL pointer then its behavior is identical to calling
2736 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2737 ** ^If the second parameter to sqlite3_realloc() is zero or
2738 ** negative then the behavior is exactly the same as calling
2739 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2740 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2741 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2742 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2743 ** of the prior allocation are copied into the beginning of buffer returned
2744 ** by sqlite3_realloc() and the prior allocation is freed.
2745 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2746 ** is not freed.
2747 **
2748 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2749 ** is always aligned to at least an 8 byte boundary, or to a
2750 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2751 ** option is used.
2752 **
2753 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2754 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2755 ** implementation of these routines to be omitted.  That capability
2756 ** is no longer provided.  Only built-in memory allocators can be used.
2757 **
2758 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2759 ** the system malloc() and free() directly when converting
2760 ** filenames between the UTF-8 encoding used by SQLite
2761 ** and whatever filename encoding is used by the particular Windows
2762 ** installation.  Memory allocation errors were detected, but
2763 ** they were reported back as [SQLITE_CANTOPEN] or
2764 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2765 **
2766 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2767 ** must be either NULL or else pointers obtained from a prior
2768 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2769 ** not yet been released.
2770 **
2771 ** The application must not read or write any part of
2772 ** a block of memory after it has been released using
2773 ** [sqlite3_free()] or [sqlite3_realloc()].
2774 */
2775 SQLITE_API void *sqlite3_malloc(int);
2776 SQLITE_API void *sqlite3_realloc(void*, int);
2777 SQLITE_API void sqlite3_free(void*);
2778
2779 /*
2780 ** CAPI3REF: Memory Allocator Statistics
2781 **
2782 ** SQLite provides these two interfaces for reporting on the status
2783 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2784 ** routines, which form the built-in memory allocation subsystem.
2785 **
2786 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2787 ** of memory currently outstanding (malloced but not freed).
2788 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2789 ** value of [sqlite3_memory_used()] since the high-water mark
2790 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2791 ** [sqlite3_memory_highwater()] include any overhead
2792 ** added by SQLite in its implementation of [sqlite3_malloc()],
2793 ** but not overhead added by the any underlying system library
2794 ** routines that [sqlite3_malloc()] may call.
2795 **
2796 ** ^The memory high-water mark is reset to the current value of
2797 ** [sqlite3_memory_used()] if and only if the parameter to
2798 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2799 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2800 ** prior to the reset.
2801 */
2802 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2803 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2804
2805 /*
2806 ** CAPI3REF: Pseudo-Random Number Generator
2807 **
2808 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2809 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2810 ** already uses the largest possible [ROWID].  The PRNG is also used for
2811 ** the build-in random() and randomblob() SQL functions.  This interface allows
2812 ** applications to access the same PRNG for other purposes.
2813 **
2814 ** ^A call to this routine stores N bytes of randomness into buffer P.
2815 **
2816 ** ^The first time this routine is invoked (either internally or by
2817 ** the application) the PRNG is seeded using randomness obtained
2818 ** from the xRandomness method of the default [sqlite3_vfs] object.
2819 ** ^On all subsequent invocations, the pseudo-randomness is generated
2820 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2821 ** method.
2822 */
2823 SQLITE_API void sqlite3_randomness(int N, void *P);
2824
2825 /*
2826 ** CAPI3REF: Compile-Time Authorization Callbacks
2827 **
2828 ** ^This routine registers an authorizer callback with a particular
2829 ** [database connection], supplied in the first argument.
2830 ** ^The authorizer callback is invoked as SQL statements are being compiled
2831 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2832 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2833 ** points during the compilation process, as logic is being created
2834 ** to perform various actions, the authorizer callback is invoked to
2835 ** see if those actions are allowed.  ^The authorizer callback should
2836 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2837 ** specific action but allow the SQL statement to continue to be
2838 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2839 ** rejected with an error.  ^If the authorizer callback returns
2840 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2841 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2842 ** the authorizer will fail with an error message.
2843 **
2844 ** When the callback returns [SQLITE_OK], that means the operation
2845 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2846 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2847 ** authorizer will fail with an error message explaining that
2848 ** access is denied. 
2849 **
2850 ** ^The first parameter to the authorizer callback is a copy of the third
2851 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2852 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2853 ** the particular action to be authorized. ^The third through sixth parameters
2854 ** to the callback are zero-terminated strings that contain additional
2855 ** details about the action to be authorized.
2856 **
2857 ** ^If the action code is [SQLITE_READ]
2858 ** and the callback returns [SQLITE_IGNORE] then the
2859 ** [prepared statement] statement is constructed to substitute
2860 ** a NULL value in place of the table column that would have
2861 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2862 ** return can be used to deny an untrusted user access to individual
2863 ** columns of a table.
2864 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2865 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2866 ** [truncate optimization] is disabled and all rows are deleted individually.
2867 **
2868 ** An authorizer is used when [sqlite3_prepare | preparing]
2869 ** SQL statements from an untrusted source, to ensure that the SQL statements
2870 ** do not try to access data they are not allowed to see, or that they do not
2871 ** try to execute malicious statements that damage the database.  For
2872 ** example, an application may allow a user to enter arbitrary
2873 ** SQL queries for evaluation by a database.  But the application does
2874 ** not want the user to be able to make arbitrary changes to the
2875 ** database.  An authorizer could then be put in place while the
2876 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2877 ** disallows everything except [SELECT] statements.
2878 **
2879 ** Applications that need to process SQL from untrusted sources
2880 ** might also consider lowering resource limits using [sqlite3_limit()]
2881 ** and limiting database size using the [max_page_count] [PRAGMA]
2882 ** in addition to using an authorizer.
2883 **
2884 ** ^(Only a single authorizer can be in place on a database connection
2885 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2886 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2887 ** The authorizer is disabled by default.
2888 **
2889 ** The authorizer callback must not do anything that will modify
2890 ** the database connection that invoked the authorizer callback.
2891 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2892 ** database connections for the meaning of "modify" in this paragraph.
2893 **
2894 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2895 ** statement might be re-prepared during [sqlite3_step()] due to a 
2896 ** schema change.  Hence, the application should ensure that the
2897 ** correct authorizer callback remains in place during the [sqlite3_step()].
2898 **
2899 ** ^Note that the authorizer callback is invoked only during
2900 ** [sqlite3_prepare()] or its variants.  Authorization is not
2901 ** performed during statement evaluation in [sqlite3_step()], unless
2902 ** as stated in the previous paragraph, sqlite3_step() invokes
2903 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2904 */
2905 SQLITE_API int sqlite3_set_authorizer(
2906   sqlite3*,
2907   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2908   void *pUserData
2909 );
2910
2911 /*
2912 ** CAPI3REF: Authorizer Return Codes
2913 **
2914 ** The [sqlite3_set_authorizer | authorizer callback function] must
2915 ** return either [SQLITE_OK] or one of these two constants in order
2916 ** to signal SQLite whether or not the action is permitted.  See the
2917 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2918 ** information.
2919 **
2920 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2921 ** from the [sqlite3_vtab_on_conflict()] interface.
2922 */
2923 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2924 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2925
2926 /*
2927 ** CAPI3REF: Authorizer Action Codes
2928 **
2929 ** The [sqlite3_set_authorizer()] interface registers a callback function
2930 ** that is invoked to authorize certain SQL statement actions.  The
2931 ** second parameter to the callback is an integer code that specifies
2932 ** what action is being authorized.  These are the integer action codes that
2933 ** the authorizer callback may be passed.
2934 **
2935 ** These action code values signify what kind of operation is to be
2936 ** authorized.  The 3rd and 4th parameters to the authorization
2937 ** callback function will be parameters or NULL depending on which of these
2938 ** codes is used as the second parameter.  ^(The 5th parameter to the
2939 ** authorizer callback is the name of the database ("main", "temp",
2940 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2941 ** is the name of the inner-most trigger or view that is responsible for
2942 ** the access attempt or NULL if this access attempt is directly from
2943 ** top-level SQL code.
2944 */
2945 /******************************************* 3rd ************ 4th ***********/
2946 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2947 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2948 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2949 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2950 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2951 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2952 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2953 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2954 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2955 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2956 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2957 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2958 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2959 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2960 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2961 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2962 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2963 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2964 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2965 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2966 #define SQLITE_SELECT               21   /* NULL            NULL            */
2967 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2968 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2969 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2970 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2971 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2972 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2973 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2974 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2975 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2976 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2977 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2978 #define SQLITE_COPY                  0   /* No longer used */
2979
2980 /*
2981 ** CAPI3REF: Tracing And Profiling Functions
2982 **
2983 ** These routines register callback functions that can be used for
2984 ** tracing and profiling the execution of SQL statements.
2985 **
2986 ** ^The callback function registered by sqlite3_trace() is invoked at
2987 ** various times when an SQL statement is being run by [sqlite3_step()].
2988 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2989 ** SQL statement text as the statement first begins executing.
2990 ** ^(Additional sqlite3_trace() callbacks might occur
2991 ** as each triggered subprogram is entered.  The callbacks for triggers
2992 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2993 **
2994 ** ^The callback function registered by sqlite3_profile() is invoked
2995 ** as each SQL statement finishes.  ^The profile callback contains
2996 ** the original statement text and an estimate of wall-clock time
2997 ** of how long that statement took to run.  ^The profile callback
2998 ** time is in units of nanoseconds, however the current implementation
2999 ** is only capable of millisecond resolution so the six least significant
3000 ** digits in the time are meaningless.  Future versions of SQLite
3001 ** might provide greater resolution on the profiler callback.  The
3002 ** sqlite3_profile() function is considered experimental and is
3003 ** subject to change in future versions of SQLite.
3004 */
3005 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3006 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3007    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3008
3009 /*
3010 ** CAPI3REF: Query Progress Callbacks
3011 **
3012 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3013 ** function X to be invoked periodically during long running calls to
3014 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3015 ** database connection D.  An example use for this
3016 ** interface is to keep a GUI updated during a large query.
3017 **
3018 ** ^The parameter P is passed through as the only parameter to the 
3019 ** callback function X.  ^The parameter N is the number of 
3020 ** [virtual machine instructions] that are evaluated between successive
3021 ** invocations of the callback X.
3022 **
3023 ** ^Only a single progress handler may be defined at one time per
3024 ** [database connection]; setting a new progress handler cancels the
3025 ** old one.  ^Setting parameter X to NULL disables the progress handler.
3026 ** ^The progress handler is also disabled by setting N to a value less
3027 ** than 1.
3028 **
3029 ** ^If the progress callback returns non-zero, the operation is
3030 ** interrupted.  This feature can be used to implement a
3031 ** "Cancel" button on a GUI progress dialog box.
3032 **
3033 ** The progress handler callback must not do anything that will modify
3034 ** the database connection that invoked the progress handler.
3035 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3036 ** database connections for the meaning of "modify" in this paragraph.
3037 **
3038 */
3039 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3040
3041 /*
3042 ** CAPI3REF: Opening A New Database Connection
3043 **
3044 ** ^These routines open an SQLite database file as specified by the 
3045 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3046 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3047 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3048 ** returned in *ppDb, even if an error occurs.  The only exception is that
3049 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3050 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3051 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3052 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3053 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3054 ** an English language description of the error following a failure of any
3055 ** of the sqlite3_open() routines.
3056 **
3057 ** ^The default encoding for the database will be UTF-8 if
3058 ** sqlite3_open() or sqlite3_open_v2() is called and
3059 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3060 **
3061 ** Whether or not an error occurs when it is opened, resources
3062 ** associated with the [database connection] handle should be released by
3063 ** passing it to [sqlite3_close()] when it is no longer required.
3064 **
3065 ** The sqlite3_open_v2() interface works like sqlite3_open()
3066 ** except that it accepts two additional parameters for additional control
3067 ** over the new database connection.  ^(The flags parameter to
3068 ** sqlite3_open_v2() can take one of
3069 ** the following three values, optionally combined with the 
3070 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3071 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3072 **
3073 ** <dl>
3074 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3075 ** <dd>The database is opened in read-only mode.  If the database does not
3076 ** already exist, an error is returned.</dd>)^
3077 **
3078 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3079 ** <dd>The database is opened for reading and writing if possible, or reading
3080 ** only if the file is write protected by the operating system.  In either
3081 ** case the database must already exist, otherwise an error is returned.</dd>)^
3082 **
3083 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3084 ** <dd>The database is opened for reading and writing, and is created if
3085 ** it does not already exist. This is the behavior that is always used for
3086 ** sqlite3_open() and sqlite3_open16().</dd>)^
3087 ** </dl>
3088 **
3089 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3090 ** combinations shown above optionally combined with other
3091 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3092 ** then the behavior is undefined.
3093 **
3094 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3095 ** opens in the multi-thread [threading mode] as long as the single-thread
3096 ** mode has not been set at compile-time or start-time.  ^If the
3097 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3098 ** in the serialized [threading mode] unless single-thread was
3099 ** previously selected at compile-time or start-time.
3100 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3101 ** eligible to use [shared cache mode], regardless of whether or not shared
3102 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3103 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3104 ** participate in [shared cache mode] even if it is enabled.
3105 **
3106 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3107 ** [sqlite3_vfs] object that defines the operating system interface that
3108 ** the new database connection should use.  ^If the fourth parameter is
3109 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3110 **
3111 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3112 ** is created for the connection.  ^This in-memory database will vanish when
3113 ** the database connection is closed.  Future versions of SQLite might
3114 ** make use of additional special filenames that begin with the ":" character.
3115 ** It is recommended that when a database filename actually does begin with
3116 ** a ":" character you should prefix the filename with a pathname such as
3117 ** "./" to avoid ambiguity.
3118 **
3119 ** ^If the filename is an empty string, then a private, temporary
3120 ** on-disk database will be created.  ^This private database will be
3121 ** automatically deleted as soon as the database connection is closed.
3122 **
3123 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3124 **
3125 ** ^If [URI filename] interpretation is enabled, and the filename argument
3126 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3127 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3128 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3129 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3130 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3131 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3132 ** by default, but future releases of SQLite might enable URI filename
3133 ** interpretation by default.  See "[URI filenames]" for additional
3134 ** information.
3135 **
3136 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3137 ** authority, then it must be either an empty string or the string 
3138 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3139 ** error is returned to the caller. ^The fragment component of a URI, if 
3140 ** present, is ignored.
3141 **
3142 ** ^SQLite uses the path component of the URI as the name of the disk file
3143 ** which contains the database. ^If the path begins with a '/' character, 
3144 ** then it is interpreted as an absolute path. ^If the path does not begin 
3145 ** with a '/' (meaning that the authority section is omitted from the URI)
3146 ** then the path is interpreted as a relative path. 
3147 ** ^On windows, the first component of an absolute path 
3148 ** is a drive specification (e.g. "C:").
3149 **
3150 ** [[core URI query parameters]]
3151 ** The query component of a URI may contain parameters that are interpreted
3152 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3153 ** SQLite interprets the following three query parameters:
3154 **
3155 ** <ul>
3156 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3157 **     a VFS object that provides the operating system interface that should
3158 **     be used to access the database file on disk. ^If this option is set to
3159 **     an empty string the default VFS object is used. ^Specifying an unknown
3160 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3161 **     present, then the VFS specified by the option takes precedence over
3162 **     the value passed as the fourth parameter to sqlite3_open_v2().
3163 **
3164 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3165 **     "rwc", or "memory". Attempting to set it to any other value is
3166 **     an error)^. 
3167 **     ^If "ro" is specified, then the database is opened for read-only 
3168 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3169 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to 
3170 **     "rw", then the database is opened for read-write (but not create) 
3171 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3172 **     been set. ^Value "rwc" is equivalent to setting both 
3173 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3174 **     set to "memory" then a pure [in-memory database] that never reads
3175 **     or writes from disk is used. ^It is an error to specify a value for
3176 **     the mode parameter that is less restrictive than that specified by
3177 **     the flags passed in the third parameter to sqlite3_open_v2().
3178 **
3179 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3180 **     "private". ^Setting it to "shared" is equivalent to setting the
3181 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3182 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3183 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3184 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3185 **     a URI filename, its value overrides any behaviour requested by setting
3186 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3187 ** </ul>
3188 **
3189 ** ^Specifying an unknown parameter in the query component of a URI is not an
3190 ** error.  Future versions of SQLite might understand additional query
3191 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3192 ** additional information.
3193 **
3194 ** [[URI filename examples]] <h3>URI filename examples</h3>
3195 **
3196 ** <table border="1" align=center cellpadding=5>
3197 ** <tr><th> URI filenames <th> Results
3198 ** <tr><td> file:data.db <td> 
3199 **          Open the file "data.db" in the current directory.
3200 ** <tr><td> file:/home/fred/data.db<br>
3201 **          file:///home/fred/data.db <br> 
3202 **          file://localhost/home/fred/data.db <br> <td> 
3203 **          Open the database file "/home/fred/data.db".
3204 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3205 **          An error. "darkstar" is not a recognized authority.
3206 ** <tr><td style="white-space:nowrap"> 
3207 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3208 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3209 **          C:. Note that the %20 escaping in this example is not strictly 
3210 **          necessary - space characters can be used literally
3211 **          in URI filenames.
3212 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3213 **          Open file "data.db" in the current directory for read-only access.
3214 **          Regardless of whether or not shared-cache mode is enabled by
3215 **          default, use a private cache.
3216 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3217 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3218 ** <tr><td> file:data.db?mode=readonly <td> 
3219 **          An error. "readonly" is not a valid option for the "mode" parameter.
3220 ** </table>
3221 **
3222 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3223 ** query components of a URI. A hexadecimal escape sequence consists of a
3224 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3225 ** specifying an octet value. ^Before the path or query components of a
3226 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3227 ** hexadecimal escape sequences replaced by a single byte containing the
3228 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3229 ** the results are undefined.
3230 **
3231 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3232 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3233 ** codepage is currently defined.  Filenames containing international
3234 ** characters must be converted to UTF-8 prior to passing them into
3235 ** sqlite3_open() or sqlite3_open_v2().
3236 **
3237 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3238 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3239 ** features that require the use of temporary files may fail.
3240 **
3241 ** See also: [sqlite3_temp_directory]
3242 */
3243 SQLITE_API int sqlite3_open(
3244   const char *filename,   /* Database filename (UTF-8) */
3245   sqlite3 **ppDb          /* OUT: SQLite db handle */
3246 );
3247 SQLITE_API int sqlite3_open16(
3248   const void *filename,   /* Database filename (UTF-16) */
3249   sqlite3 **ppDb          /* OUT: SQLite db handle */
3250 );
3251 SQLITE_API int sqlite3_open_v2(
3252   const char *filename,   /* Database filename (UTF-8) */
3253   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3254   int flags,              /* Flags */
3255   const char *zVfs        /* Name of VFS module to use */
3256 );
3257
3258 /*
3259 ** CAPI3REF: Obtain Values For URI Parameters
3260 **
3261 ** These are utility routines, useful to VFS implementations, that check
3262 ** to see if a database file was a URI that contained a specific query 
3263 ** parameter, and if so obtains the value of that query parameter.
3264 **
3265 ** If F is the database filename pointer passed into the xOpen() method of 
3266 ** a VFS implementation when the flags parameter to xOpen() has one or 
3267 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3268 ** P is the name of the query parameter, then
3269 ** sqlite3_uri_parameter(F,P) returns the value of the P
3270 ** parameter if it exists or a NULL pointer if P does not appear as a 
3271 ** query parameter on F.  If P is a query parameter of F
3272 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3273 ** a pointer to an empty string.
3274 **
3275 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3276 ** parameter and returns true (1) or false (0) according to the value
3277 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3278 ** value of query parameter P is one of "yes", "true", or "on" in any
3279 ** case or if the value begins with a non-zero number.  The 
3280 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3281 ** query parameter P is one of "no", "false", or "off" in any case or
3282 ** if the value begins with a numeric zero.  If P is not a query
3283 ** parameter on F or if the value of P is does not match any of the
3284 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3285 **
3286 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3287 ** 64-bit signed integer and returns that integer, or D if P does not
3288 ** exist.  If the value of P is something other than an integer, then
3289 ** zero is returned.
3290 ** 
3291 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3292 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3293 ** is not a database file pathname pointer that SQLite passed into the xOpen
3294 ** VFS method, then the behavior of this routine is undefined and probably
3295 ** undesirable.
3296 */
3297 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3298 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3299 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3300
3301
3302 /*
3303 ** CAPI3REF: Error Codes And Messages
3304 **
3305 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3306 ** [extended result code] for the most recent failed sqlite3_* API call
3307 ** associated with a [database connection]. If a prior API call failed
3308 ** but the most recent API call succeeded, the return value from
3309 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3310 ** interface is the same except that it always returns the 
3311 ** [extended result code] even when extended result codes are
3312 ** disabled.
3313 **
3314 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3315 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3316 ** ^(Memory to hold the error message string is managed internally.
3317 ** The application does not need to worry about freeing the result.
3318 ** However, the error string might be overwritten or deallocated by
3319 ** subsequent calls to other SQLite interface functions.)^
3320 **
3321 ** When the serialized [threading mode] is in use, it might be the
3322 ** case that a second error occurs on a separate thread in between
3323 ** the time of the first error and the call to these interfaces.
3324 ** When that happens, the second error will be reported since these
3325 ** interfaces always report the most recent result.  To avoid
3326 ** this, each thread can obtain exclusive use of the [database connection] D
3327 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3328 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3329 ** all calls to the interfaces listed here are completed.
3330 **
3331 ** If an interface fails with SQLITE_MISUSE, that means the interface
3332 ** was invoked incorrectly by the application.  In that case, the
3333 ** error code and message may or may not be set.
3334 */
3335 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3336 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3337 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3338 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3339
3340 /*
3341 ** CAPI3REF: SQL Statement Object
3342 ** KEYWORDS: {prepared statement} {prepared statements}
3343 **
3344 ** An instance of this object represents a single SQL statement.
3345 ** This object is variously known as a "prepared statement" or a
3346 ** "compiled SQL statement" or simply as a "statement".
3347 **
3348 ** The life of a statement object goes something like this:
3349 **
3350 ** <ol>
3351 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3352 **      function.
3353 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3354 **      interfaces.
3355 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3356 ** <li> Reset the statement using [sqlite3_reset()] then go back
3357 **      to step 2.  Do this zero or more times.
3358 ** <li> Destroy the object using [sqlite3_finalize()].
3359 ** </ol>
3360 **
3361 ** Refer to documentation on individual methods above for additional
3362 ** information.
3363 */
3364 typedef struct sqlite3_stmt sqlite3_stmt;
3365
3366 /*
3367 ** CAPI3REF: Run-time Limits
3368 **
3369 ** ^(This interface allows the size of various constructs to be limited
3370 ** on a connection by connection basis.  The first parameter is the
3371 ** [database connection] whose limit is to be set or queried.  The
3372 ** second parameter is one of the [limit categories] that define a
3373 ** class of constructs to be size limited.  The third parameter is the
3374 ** new limit for that construct.)^
3375 **
3376 ** ^If the new limit is a negative number, the limit is unchanged.
3377 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3378 ** [limits | hard upper bound]
3379 ** set at compile-time by a C preprocessor macro called
3380 ** [limits | SQLITE_MAX_<i>NAME</i>].
3381 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3382 ** ^Attempts to increase a limit above its hard upper bound are
3383 ** silently truncated to the hard upper bound.
3384 **
3385 ** ^Regardless of whether or not the limit was changed, the 
3386 ** [sqlite3_limit()] interface returns the prior value of the limit.
3387 ** ^Hence, to find the current value of a limit without changing it,
3388 ** simply invoke this interface with the third parameter set to -1.
3389 **
3390 ** Run-time limits are intended for use in applications that manage
3391 ** both their own internal database and also databases that are controlled
3392 ** by untrusted external sources.  An example application might be a
3393 ** web browser that has its own databases for storing history and
3394 ** separate databases controlled by JavaScript applications downloaded
3395 ** off the Internet.  The internal databases can be given the
3396 ** large, default limits.  Databases managed by external sources can
3397 ** be given much smaller limits designed to prevent a denial of service
3398 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3399 ** interface to further control untrusted SQL.  The size of the database
3400 ** created by an untrusted script can be contained using the
3401 ** [max_page_count] [PRAGMA].
3402 **
3403 ** New run-time limit categories may be added in future releases.
3404 */
3405 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3406
3407 /*
3408 ** CAPI3REF: Run-Time Limit Categories
3409 ** KEYWORDS: {limit category} {*limit categories}
3410 **
3411 ** These constants define various performance limits
3412 ** that can be lowered at run-time using [sqlite3_limit()].
3413 ** The synopsis of the meanings of the various limits is shown below.
3414 ** Additional information is available at [limits | Limits in SQLite].
3415 **
3416 ** <dl>
3417 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3418 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3419 **
3420 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3421 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3422 **
3423 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3424 ** <dd>The maximum number of columns in a table definition or in the
3425 ** result set of a [SELECT] or the maximum number of columns in an index
3426 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3427 **
3428 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3429 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3430 **
3431 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3432 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3433 **
3434 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3435 ** <dd>The maximum number of instructions in a virtual machine program
3436 ** used to implement an SQL statement.  This limit is not currently
3437 ** enforced, though that might be added in some future release of
3438 ** SQLite.</dd>)^
3439 **
3440 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3441 ** <dd>The maximum number of arguments on a function.</dd>)^
3442 **
3443 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3444 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3445 **
3446 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3447 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3448 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3449 ** [GLOB] operators.</dd>)^
3450 **
3451 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3452 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3453 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3454 **
3455 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3456 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3457 ** </dl>
3458 */
3459 #define SQLITE_LIMIT_LENGTH                    0
3460 #define SQLITE_LIMIT_SQL_LENGTH                1
3461 #define SQLITE_LIMIT_COLUMN                    2
3462 #define SQLITE_LIMIT_EXPR_DEPTH                3
3463 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3464 #define SQLITE_LIMIT_VDBE_OP                   5
3465 #define SQLITE_LIMIT_FUNCTION_ARG              6
3466 #define SQLITE_LIMIT_ATTACHED                  7
3467 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3468 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3469 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3470
3471 /*
3472 ** CAPI3REF: Compiling An SQL Statement
3473 ** KEYWORDS: {SQL statement compiler}
3474 **
3475 ** To execute an SQL query, it must first be compiled into a byte-code
3476 ** program using one of these routines.
3477 **
3478 ** The first argument, "db", is a [database connection] obtained from a
3479 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3480 ** [sqlite3_open16()].  The database connection must not have been closed.
3481 **
3482 ** The second argument, "zSql", is the statement to be compiled, encoded
3483 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3484 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3485 ** use UTF-16.
3486 **
3487 ** ^If the nByte argument is less than zero, then zSql is read up to the
3488 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3489 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3490 ** zSql string ends at either the first '\000' or '\u0000' character or
3491 ** the nByte-th byte, whichever comes first. If the caller knows
3492 ** that the supplied string is nul-terminated, then there is a small
3493 ** performance advantage to be gained by passing an nByte parameter that
3494 ** is equal to the number of bytes in the input string <i>including</i>
3495 ** the nul-terminator bytes as this saves SQLite from having to
3496 ** make a copy of the input string.
3497 **
3498 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3499 ** past the end of the first SQL statement in zSql.  These routines only
3500 ** compile the first statement in zSql, so *pzTail is left pointing to
3501 ** what remains uncompiled.
3502 **
3503 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3504 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3505 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3506 ** string or a comment) then *ppStmt is set to NULL.
3507 ** The calling procedure is responsible for deleting the compiled
3508 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3509 ** ppStmt may not be NULL.
3510 **
3511 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3512 ** otherwise an [error code] is returned.
3513 **
3514 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3515 ** recommended for all new programs. The two older interfaces are retained
3516 ** for backwards compatibility, but their use is discouraged.
3517 ** ^In the "v2" interfaces, the prepared statement
3518 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3519 ** original SQL text. This causes the [sqlite3_step()] interface to
3520 ** behave differently in three ways:
3521 **
3522 ** <ol>
3523 ** <li>
3524 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3525 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3526 ** statement and try to run it again.
3527 ** </li>
3528 **
3529 ** <li>
3530 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3531 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3532 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3533 ** and the application would have to make a second call to [sqlite3_reset()]
3534 ** in order to find the underlying cause of the problem. With the "v2" prepare
3535 ** interfaces, the underlying reason for the error is returned immediately.
3536 ** </li>
3537 **
3538 ** <li>
3539 ** ^If the specific value bound to [parameter | host parameter] in the 
3540 ** WHERE clause might influence the choice of query plan for a statement,
3541 ** then the statement will be automatically recompiled, as if there had been 
3542 ** a schema change, on the first  [sqlite3_step()] call following any change
3543 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3544 ** ^The specific value of WHERE-clause [parameter] might influence the 
3545 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3546 ** or [GLOB] operator or if the parameter is compared to an indexed column
3547 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3548 ** the 
3549 ** </li>
3550 ** </ol>
3551 */
3552 SQLITE_API int sqlite3_prepare(
3553   sqlite3 *db,            /* Database handle */
3554   const char *zSql,       /* SQL statement, UTF-8 encoded */
3555   int nByte,              /* Maximum length of zSql in bytes. */
3556   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3557   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3558 );
3559 SQLITE_API int sqlite3_prepare_v2(
3560   sqlite3 *db,            /* Database handle */
3561   const char *zSql,       /* SQL statement, UTF-8 encoded */
3562   int nByte,              /* Maximum length of zSql in bytes. */
3563   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3564   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3565 );
3566 SQLITE_API int sqlite3_prepare16(
3567   sqlite3 *db,            /* Database handle */
3568   const void *zSql,       /* SQL statement, UTF-16 encoded */
3569   int nByte,              /* Maximum length of zSql in bytes. */
3570   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3571   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3572 );
3573 SQLITE_API int sqlite3_prepare16_v2(
3574   sqlite3 *db,            /* Database handle */
3575   const void *zSql,       /* SQL statement, UTF-16 encoded */
3576   int nByte,              /* Maximum length of zSql in bytes. */
3577   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3578   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3579 );
3580
3581 /*
3582 ** CAPI3REF: Retrieving Statement SQL
3583 **
3584 ** ^This interface can be used to retrieve a saved copy of the original
3585 ** SQL text used to create a [prepared statement] if that statement was
3586 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3587 */
3588 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3589
3590 /*
3591 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3592 **
3593 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3594 ** and only if the [prepared statement] X makes no direct changes to
3595 ** the content of the database file.
3596 **
3597 ** Note that [application-defined SQL functions] or
3598 ** [virtual tables] might change the database indirectly as a side effect.  
3599 ** ^(For example, if an application defines a function "eval()" that 
3600 ** calls [sqlite3_exec()], then the following SQL statement would
3601 ** change the database file through side-effects:
3602 **
3603 ** <blockquote><pre>
3604 **    SELECT eval('DELETE FROM t1') FROM t2;
3605 ** </pre></blockquote>
3606 **
3607 ** But because the [SELECT] statement does not change the database file
3608 ** directly, sqlite3_stmt_readonly() would still return true.)^
3609 **
3610 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3611 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3612 ** since the statements themselves do not actually modify the database but
3613 ** rather they control the timing of when other statements modify the 
3614 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3615 ** sqlite3_stmt_readonly() to return true since, while those statements
3616 ** change the configuration of a database connection, they do not make 
3617 ** changes to the content of the database files on disk.
3618 */
3619 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3620
3621 /*
3622 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3623 **
3624 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3625 ** [prepared statement] S has been stepped at least once using 
3626 ** [sqlite3_step(S)] but has not run to completion and/or has not 
3627 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3628 ** interface returns false if S is a NULL pointer.  If S is not a 
3629 ** NULL pointer and is not a pointer to a valid [prepared statement]
3630 ** object, then the behavior is undefined and probably undesirable.
3631 **
3632 ** This interface can be used in combination [sqlite3_next_stmt()]
3633 ** to locate all prepared statements associated with a database 
3634 ** connection that are in need of being reset.  This can be used,
3635 ** for example, in diagnostic routines to search for prepared 
3636 ** statements that are holding a transaction open.
3637 */
3638 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3639
3640 /*
3641 ** CAPI3REF: Dynamically Typed Value Object
3642 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3643 **
3644 ** SQLite uses the sqlite3_value object to represent all values
3645 ** that can be stored in a database table. SQLite uses dynamic typing
3646 ** for the values it stores.  ^Values stored in sqlite3_value objects
3647 ** can be integers, floating point values, strings, BLOBs, or NULL.
3648 **
3649 ** An sqlite3_value object may be either "protected" or "unprotected".
3650 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3651 ** will accept either a protected or an unprotected sqlite3_value.
3652 ** Every interface that accepts sqlite3_value arguments specifies
3653 ** whether or not it requires a protected sqlite3_value.
3654 **
3655 ** The terms "protected" and "unprotected" refer to whether or not
3656 ** a mutex is held.  An internal mutex is held for a protected
3657 ** sqlite3_value object but no mutex is held for an unprotected
3658 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3659 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3660 ** or if SQLite is run in one of reduced mutex modes 
3661 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3662 ** then there is no distinction between protected and unprotected
3663 ** sqlite3_value objects and they can be used interchangeably.  However,
3664 ** for maximum code portability it is recommended that applications
3665 ** still make the distinction between protected and unprotected
3666 ** sqlite3_value objects even when not strictly required.
3667 **
3668 ** ^The sqlite3_value objects that are passed as parameters into the
3669 ** implementation of [application-defined SQL functions] are protected.
3670 ** ^The sqlite3_value object returned by
3671 ** [sqlite3_column_value()] is unprotected.
3672 ** Unprotected sqlite3_value objects may only be used with
3673 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3674 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3675 ** interfaces require protected sqlite3_value objects.
3676 */
3677 typedef struct Mem sqlite3_value;
3678
3679 /*
3680 ** CAPI3REF: SQL Function Context Object
3681 **
3682 ** The context in which an SQL function executes is stored in an
3683 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3684 ** is always first parameter to [application-defined SQL functions].
3685 ** The application-defined SQL function implementation will pass this
3686 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3687 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3688 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3689 ** and/or [sqlite3_set_auxdata()].
3690 */
3691 typedef struct sqlite3_context sqlite3_context;
3692
3693 /*
3694 ** CAPI3REF: Binding Values To Prepared Statements
3695 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3696 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3697 **
3698 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3699 ** literals may be replaced by a [parameter] that matches one of following
3700 ** templates:
3701 **
3702 ** <ul>
3703 ** <li>  ?
3704 ** <li>  ?NNN
3705 ** <li>  :VVV
3706 ** <li>  @VVV
3707 ** <li>  $VVV
3708 ** </ul>
3709 **
3710 ** In the templates above, NNN represents an integer literal,
3711 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3712 ** parameters (also called "host parameter names" or "SQL parameters")
3713 ** can be set using the sqlite3_bind_*() routines defined here.
3714 **
3715 ** ^The first argument to the sqlite3_bind_*() routines is always
3716 ** a pointer to the [sqlite3_stmt] object returned from
3717 ** [sqlite3_prepare_v2()] or its variants.
3718 **
3719 ** ^The second argument is the index of the SQL parameter to be set.
3720 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3721 ** SQL parameter is used more than once, second and subsequent
3722 ** occurrences have the same index as the first occurrence.
3723 ** ^The index for named parameters can be looked up using the
3724 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3725 ** for "?NNN" parameters is the value of NNN.
3726 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3727 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3728 **
3729 ** ^The third argument is the value to bind to the parameter.
3730 **
3731 ** ^(In those routines that have a fourth argument, its value is the
3732 ** number of bytes in the parameter.  To be clear: the value is the
3733 ** number of <u>bytes</u> in the value, not the number of characters.)^
3734 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3735 ** is negative, then the length of the string is
3736 ** the number of bytes up to the first zero terminator.
3737 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3738 ** the behavior is undefined.
3739 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3740 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3741 ** where the NUL terminator would occur assuming the string were NUL
3742 ** terminated.  If any NUL characters occur at byte offsets less than 
3743 ** the value of the fourth parameter then the resulting string value will
3744 ** contain embedded NULs.  The result of expressions involving strings
3745 ** with embedded NULs is undefined.
3746 **
3747 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3748 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3749 ** string after SQLite has finished with it.  ^The destructor is called
3750 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3751 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3752 ** ^If the fifth argument is
3753 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3754 ** information is in static, unmanaged space and does not need to be freed.
3755 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3756 ** SQLite makes its own private copy of the data immediately, before
3757 ** the sqlite3_bind_*() routine returns.
3758 **
3759 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3760 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3761 ** (just an integer to hold its size) while it is being processed.
3762 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3763 ** content is later written using
3764 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3765 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3766 **
3767 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3768 ** for the [prepared statement] or with a prepared statement for which
3769 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3770 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3771 ** routine is passed a [prepared statement] that has been finalized, the
3772 ** result is undefined and probably harmful.
3773 **
3774 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3775 ** ^Unbound parameters are interpreted as NULL.
3776 **
3777 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3778 ** [error code] if anything goes wrong.
3779 ** ^[SQLITE_RANGE] is returned if the parameter
3780 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3781 **
3782 ** See also: [sqlite3_bind_parameter_count()],
3783 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3784 */
3785 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3786 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3787 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3788 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3789 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3790 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3791 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3792 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3793 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3794
3795 /*
3796 ** CAPI3REF: Number Of SQL Parameters
3797 **
3798 ** ^This routine can be used to find the number of [SQL parameters]
3799 ** in a [prepared statement].  SQL parameters are tokens of the
3800 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3801 ** placeholders for values that are [sqlite3_bind_blob | bound]
3802 ** to the parameters at a later time.
3803 **
3804 ** ^(This routine actually returns the index of the largest (rightmost)
3805 ** parameter. For all forms except ?NNN, this will correspond to the
3806 ** number of unique parameters.  If parameters of the ?NNN form are used,
3807 ** there may be gaps in the list.)^
3808 **
3809 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3810 ** [sqlite3_bind_parameter_name()], and
3811 ** [sqlite3_bind_parameter_index()].
3812 */
3813 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3814
3815 /*
3816 ** CAPI3REF: Name Of A Host Parameter
3817 **
3818 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3819 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3820 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3821 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3822 ** respectively.
3823 ** In other words, the initial ":" or "$" or "@" or "?"
3824 ** is included as part of the name.)^
3825 ** ^Parameters of the form "?" without a following integer have no name
3826 ** and are referred to as "nameless" or "anonymous parameters".
3827 **
3828 ** ^The first host parameter has an index of 1, not 0.
3829 **
3830 ** ^If the value N is out of range or if the N-th parameter is
3831 ** nameless, then NULL is returned.  ^The returned string is
3832 ** always in UTF-8 encoding even if the named parameter was
3833 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3834 ** [sqlite3_prepare16_v2()].
3835 **
3836 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3837 ** [sqlite3_bind_parameter_count()], and
3838 ** [sqlite3_bind_parameter_index()].
3839 */
3840 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3841
3842 /*
3843 ** CAPI3REF: Index Of A Parameter With A Given Name
3844 **
3845 ** ^Return the index of an SQL parameter given its name.  ^The
3846 ** index value returned is suitable for use as the second
3847 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3848 ** is returned if no matching parameter is found.  ^The parameter
3849 ** name must be given in UTF-8 even if the original statement
3850 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3851 **
3852 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3853 ** [sqlite3_bind_parameter_count()], and
3854 ** [sqlite3_bind_parameter_index()].
3855 */
3856 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3857
3858 /*
3859 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3860 **
3861 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3862 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3863 ** ^Use this routine to reset all host parameters to NULL.
3864 */
3865 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3866
3867 /*
3868 ** CAPI3REF: Number Of Columns In A Result Set
3869 **
3870 ** ^Return the number of columns in the result set returned by the
3871 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3872 ** statement that does not return data (for example an [UPDATE]).
3873 **
3874 ** See also: [sqlite3_data_count()]
3875 */
3876 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3877
3878 /*
3879 ** CAPI3REF: Column Names In A Result Set
3880 **
3881 ** ^These routines return the name assigned to a particular column
3882 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3883 ** interface returns a pointer to a zero-terminated UTF-8 string
3884 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3885 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3886 ** that implements the [SELECT] statement. ^The second parameter is the
3887 ** column number.  ^The leftmost column is number 0.
3888 **
3889 ** ^The returned string pointer is valid until either the [prepared statement]
3890 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3891 ** reprepared by the first call to [sqlite3_step()] for a particular run
3892 ** or until the next call to
3893 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3894 **
3895 ** ^If sqlite3_malloc() fails during the processing of either routine
3896 ** (for example during a conversion from UTF-8 to UTF-16) then a
3897 ** NULL pointer is returned.
3898 **
3899 ** ^The name of a result column is the value of the "AS" clause for
3900 ** that column, if there is an AS clause.  If there is no AS clause
3901 ** then the name of the column is unspecified and may change from
3902 ** one release of SQLite to the next.
3903 */
3904 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3905 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3906
3907 /*
3908 ** CAPI3REF: Source Of Data In A Query Result
3909 **
3910 ** ^These routines provide a means to determine the database, table, and
3911 ** table column that is the origin of a particular result column in
3912 ** [SELECT] statement.
3913 ** ^The name of the database or table or column can be returned as
3914 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3915 ** the database name, the _table_ routines return the table name, and
3916 ** the origin_ routines return the column name.
3917 ** ^The returned string is valid until the [prepared statement] is destroyed
3918 ** using [sqlite3_finalize()] or until the statement is automatically
3919 ** reprepared by the first call to [sqlite3_step()] for a particular run
3920 ** or until the same information is requested
3921 ** again in a different encoding.
3922 **
3923 ** ^The names returned are the original un-aliased names of the
3924 ** database, table, and column.
3925 **
3926 ** ^The first argument to these interfaces is a [prepared statement].
3927 ** ^These functions return information about the Nth result column returned by
3928 ** the statement, where N is the second function argument.
3929 ** ^The left-most column is column 0 for these routines.
3930 **
3931 ** ^If the Nth column returned by the statement is an expression or
3932 ** subquery and is not a column value, then all of these functions return
3933 ** NULL.  ^These routine might also return NULL if a memory allocation error
3934 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3935 ** or column that query result column was extracted from.
3936 **
3937 ** ^As with all other SQLite APIs, those whose names end with "16" return
3938 ** UTF-16 encoded strings and the other functions return UTF-8.
3939 **
3940 ** ^These APIs are only available if the library was compiled with the
3941 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3942 **
3943 ** If two or more threads call one or more of these routines against the same
3944 ** prepared statement and column at the same time then the results are
3945 ** undefined.
3946 **
3947 ** If two or more threads call one or more
3948 ** [sqlite3_column_database_name | column metadata interfaces]
3949 ** for the same [prepared statement] and result column
3950 ** at the same time then the results are undefined.
3951 */
3952 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3953 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3954 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3955 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3956 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3957 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3958
3959 /*
3960 ** CAPI3REF: Declared Datatype Of A Query Result
3961 **
3962 ** ^(The first parameter is a [prepared statement].
3963 ** If this statement is a [SELECT] statement and the Nth column of the
3964 ** returned result set of that [SELECT] is a table column (not an
3965 ** expression or subquery) then the declared type of the table
3966 ** column is returned.)^  ^If the Nth column of the result set is an
3967 ** expression or subquery, then a NULL pointer is returned.
3968 ** ^The returned string is always UTF-8 encoded.
3969 **
3970 ** ^(For example, given the database schema:
3971 **
3972 ** CREATE TABLE t1(c1 VARIANT);
3973 **
3974 ** and the following statement to be compiled:
3975 **
3976 ** SELECT c1 + 1, c1 FROM t1;
3977 **
3978 ** this routine would return the string "VARIANT" for the second result
3979 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3980 **
3981 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3982 ** is declared to contain a particular type does not mean that the
3983 ** data stored in that column is of the declared type.  SQLite is
3984 ** strongly typed, but the typing is dynamic not static.  ^Type
3985 ** is associated with individual values, not with the containers
3986 ** used to hold those values.
3987 */
3988 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3989 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3990
3991 /*
3992 ** CAPI3REF: Evaluate An SQL Statement
3993 **
3994 ** After a [prepared statement] has been prepared using either
3995 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3996 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3997 ** must be called one or more times to evaluate the statement.
3998 **
3999 ** The details of the behavior of the sqlite3_step() interface depend
4000 ** on whether the statement was prepared using the newer "v2" interface
4001 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4002 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4003 ** new "v2" interface is recommended for new applications but the legacy
4004 ** interface will continue to be supported.
4005 **
4006 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4007 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4008 ** ^With the "v2" interface, any of the other [result codes] or
4009 ** [extended result codes] might be returned as well.
4010 **
4011 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4012 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4013 ** or occurs outside of an explicit transaction, then you can retry the
4014 ** statement.  If the statement is not a [COMMIT] and occurs within an
4015 ** explicit transaction then you should rollback the transaction before
4016 ** continuing.
4017 **
4018 ** ^[SQLITE_DONE] means that the statement has finished executing
4019 ** successfully.  sqlite3_step() should not be called again on this virtual
4020 ** machine without first calling [sqlite3_reset()] to reset the virtual
4021 ** machine back to its initial state.
4022 **
4023 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4024 ** is returned each time a new row of data is ready for processing by the
4025 ** caller. The values may be accessed using the [column access functions].
4026 ** sqlite3_step() is called again to retrieve the next row of data.
4027 **
4028 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4029 ** violation) has occurred.  sqlite3_step() should not be called again on
4030 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4031 ** ^With the legacy interface, a more specific error code (for example,
4032 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4033 ** can be obtained by calling [sqlite3_reset()] on the
4034 ** [prepared statement].  ^In the "v2" interface,
4035 ** the more specific error code is returned directly by sqlite3_step().
4036 **
4037 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4038 ** Perhaps it was called on a [prepared statement] that has
4039 ** already been [sqlite3_finalize | finalized] or on one that had
4040 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4041 ** be the case that the same database connection is being used by two or
4042 ** more threads at the same moment in time.
4043 **
4044 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4045 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4046 ** other than [SQLITE_ROW] before any subsequent invocation of
4047 ** sqlite3_step().  Failure to reset the prepared statement using 
4048 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4049 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4050 ** calling [sqlite3_reset()] automatically in this circumstance rather
4051 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4052 ** break because any application that ever receives an SQLITE_MISUSE error
4053 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4054 ** can be used to restore the legacy behavior.
4055 **
4056 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4057 ** API always returns a generic error code, [SQLITE_ERROR], following any
4058 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4059 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4060 ** specific [error codes] that better describes the error.
4061 ** We admit that this is a goofy design.  The problem has been fixed
4062 ** with the "v2" interface.  If you prepare all of your SQL statements
4063 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4064 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4065 ** then the more specific [error codes] are returned directly
4066 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4067 */
4068 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4069
4070 /*
4071 ** CAPI3REF: Number of columns in a result set
4072 **
4073 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4074 ** current row of the result set of [prepared statement] P.
4075 ** ^If prepared statement P does not have results ready to return
4076 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4077 ** interfaces) then sqlite3_data_count(P) returns 0.
4078 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4079 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4080 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4081 ** will return non-zero if previous call to [sqlite3_step](P) returned
4082 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4083 ** where it always returns zero since each step of that multi-step
4084 ** pragma returns 0 columns of data.
4085 **
4086 ** See also: [sqlite3_column_count()]
4087 */
4088 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4089
4090 /*
4091 ** CAPI3REF: Fundamental Datatypes
4092 ** KEYWORDS: SQLITE_TEXT
4093 **
4094 ** ^(Every value in SQLite has one of five fundamental datatypes:
4095 **
4096 ** <ul>
4097 ** <li> 64-bit signed integer
4098 ** <li> 64-bit IEEE floating point number
4099 ** <li> string
4100 ** <li> BLOB
4101 ** <li> NULL
4102 ** </ul>)^
4103 **
4104 ** These constants are codes for each of those types.
4105 **
4106 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4107 ** for a completely different meaning.  Software that links against both
4108 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4109 ** SQLITE_TEXT.
4110 */
4111 #define SQLITE_INTEGER  1
4112 #define SQLITE_FLOAT    2
4113 #define SQLITE_BLOB     4
4114 #define SQLITE_NULL     5
4115 #ifdef SQLITE_TEXT
4116 # undef SQLITE_TEXT
4117 #else
4118 # define SQLITE_TEXT     3
4119 #endif
4120 #define SQLITE3_TEXT     3
4121
4122 /*
4123 ** CAPI3REF: Result Values From A Query
4124 ** KEYWORDS: {column access functions}
4125 **
4126 ** These routines form the "result set" interface.
4127 **
4128 ** ^These routines return information about a single column of the current
4129 ** result row of a query.  ^In every case the first argument is a pointer
4130 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4131 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4132 ** and the second argument is the index of the column for which information
4133 ** should be returned. ^The leftmost column of the result set has the index 0.
4134 ** ^The number of columns in the result can be determined using
4135 ** [sqlite3_column_count()].
4136 **
4137 ** If the SQL statement does not currently point to a valid row, or if the
4138 ** column index is out of range, the result is undefined.
4139 ** These routines may only be called when the most recent call to
4140 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4141 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4142 ** If any of these routines are called after [sqlite3_reset()] or
4143 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4144 ** something other than [SQLITE_ROW], the results are undefined.
4145 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4146 ** are called from a different thread while any of these routines
4147 ** are pending, then the results are undefined.
4148 **
4149 ** ^The sqlite3_column_type() routine returns the
4150 ** [SQLITE_INTEGER | datatype code] for the initial data type
4151 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4152 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4153 ** returned by sqlite3_column_type() is only meaningful if no type
4154 ** conversions have occurred as described below.  After a type conversion,
4155 ** the value returned by sqlite3_column_type() is undefined.  Future
4156 ** versions of SQLite may change the behavior of sqlite3_column_type()
4157 ** following a type conversion.
4158 **
4159 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4160 ** routine returns the number of bytes in that BLOB or string.
4161 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4162 ** the string to UTF-8 and then returns the number of bytes.
4163 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4164 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4165 ** the number of bytes in that string.
4166 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4167 **
4168 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4169 ** routine returns the number of bytes in that BLOB or string.
4170 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4171 ** the string to UTF-16 and then returns the number of bytes.
4172 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4173 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4174 ** the number of bytes in that string.
4175 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4176 **
4177 ** ^The values returned by [sqlite3_column_bytes()] and 
4178 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4179 ** of the string.  ^For clarity: the values returned by
4180 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4181 ** bytes in the string, not the number of characters.
4182 **
4183 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4184 ** even empty strings, are always zero-terminated.  ^The return
4185 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4186 **
4187 ** ^The object returned by [sqlite3_column_value()] is an
4188 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4189 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4190 ** If the [unprotected sqlite3_value] object returned by
4191 ** [sqlite3_column_value()] is used in any other way, including calls
4192 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4193 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4194 **
4195 ** These routines attempt to convert the value where appropriate.  ^For
4196 ** example, if the internal representation is FLOAT and a text result
4197 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4198 ** conversion automatically.  ^(The following table details the conversions
4199 ** that are applied:
4200 **
4201 ** <blockquote>
4202 ** <table border="1">
4203 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4204 **
4205 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4206 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4207 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4208 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4209 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4210 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4211 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4212 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4213 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4214 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4215 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4216 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4217 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4218 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4219 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4220 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4221 ** </table>
4222 ** </blockquote>)^
4223 **
4224 ** The table above makes reference to standard C library functions atoi()
4225 ** and atof().  SQLite does not really use these functions.  It has its
4226 ** own equivalent internal routines.  The atoi() and atof() names are
4227 ** used in the table for brevity and because they are familiar to most
4228 ** C programmers.
4229 **
4230 ** Note that when type conversions occur, pointers returned by prior
4231 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4232 ** sqlite3_column_text16() may be invalidated.
4233 ** Type conversions and pointer invalidations might occur
4234 ** in the following cases:
4235 **
4236 ** <ul>
4237 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4238 **      sqlite3_column_text16() is called.  A zero-terminator might
4239 **      need to be added to the string.</li>
4240 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4241 **      sqlite3_column_text16() is called.  The content must be converted
4242 **      to UTF-16.</li>
4243 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4244 **      sqlite3_column_text() is called.  The content must be converted
4245 **      to UTF-8.</li>
4246 ** </ul>
4247 **
4248 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4249 ** not invalidate a prior pointer, though of course the content of the buffer
4250 ** that the prior pointer references will have been modified.  Other kinds
4251 ** of conversion are done in place when it is possible, but sometimes they
4252 ** are not possible and in those cases prior pointers are invalidated.
4253 **
4254 ** The safest and easiest to remember policy is to invoke these routines
4255 ** in one of the following ways:
4256 **
4257 ** <ul>
4258 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4259 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4260 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4261 ** </ul>
4262 **
4263 ** In other words, you should call sqlite3_column_text(),
4264 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4265 ** into the desired format, then invoke sqlite3_column_bytes() or
4266 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4267 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4268 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4269 ** with calls to sqlite3_column_bytes().
4270 **
4271 ** ^The pointers returned are valid until a type conversion occurs as
4272 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4273 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4274 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4275 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4276 ** [sqlite3_free()].
4277 **
4278 ** ^(If a memory allocation error occurs during the evaluation of any
4279 ** of these routines, a default value is returned.  The default value
4280 ** is either the integer 0, the floating point number 0.0, or a NULL
4281 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4282 ** [SQLITE_NOMEM].)^
4283 */
4284 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4285 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4286 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4287 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4288 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4289 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4290 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4291 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4292 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4293 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4294
4295 /*
4296 ** CAPI3REF: Destroy A Prepared Statement Object
4297 **
4298 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4299 ** ^If the most recent evaluation of the statement encountered no errors
4300 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4301 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4302 ** sqlite3_finalize(S) returns the appropriate [error code] or
4303 ** [extended error code].
4304 **
4305 ** ^The sqlite3_finalize(S) routine can be called at any point during
4306 ** the life cycle of [prepared statement] S:
4307 ** before statement S is ever evaluated, after
4308 ** one or more calls to [sqlite3_reset()], or after any call
4309 ** to [sqlite3_step()] regardless of whether or not the statement has
4310 ** completed execution.
4311 **
4312 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4313 **
4314 ** The application must finalize every [prepared statement] in order to avoid
4315 ** resource leaks.  It is a grievous error for the application to try to use
4316 ** a prepared statement after it has been finalized.  Any use of a prepared
4317 ** statement after it has been finalized can result in undefined and
4318 ** undesirable behavior such as segfaults and heap corruption.
4319 */
4320 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4321
4322 /*
4323 ** CAPI3REF: Reset A Prepared Statement Object
4324 **
4325 ** The sqlite3_reset() function is called to reset a [prepared statement]
4326 ** object back to its initial state, ready to be re-executed.
4327 ** ^Any SQL statement variables that had values bound to them using
4328 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4329 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4330 **
4331 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4332 ** back to the beginning of its program.
4333 **
4334 ** ^If the most recent call to [sqlite3_step(S)] for the
4335 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4336 ** or if [sqlite3_step(S)] has never before been called on S,
4337 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4338 **
4339 ** ^If the most recent call to [sqlite3_step(S)] for the
4340 ** [prepared statement] S indicated an error, then
4341 ** [sqlite3_reset(S)] returns an appropriate [error code].
4342 **
4343 ** ^The [sqlite3_reset(S)] interface does not change the values
4344 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4345 */
4346 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4347
4348 /*
4349 ** CAPI3REF: Create Or Redefine SQL Functions
4350 ** KEYWORDS: {function creation routines}
4351 ** KEYWORDS: {application-defined SQL function}
4352 ** KEYWORDS: {application-defined SQL functions}
4353 **
4354 ** ^These functions (collectively known as "function creation routines")
4355 ** are used to add SQL functions or aggregates or to redefine the behavior
4356 ** of existing SQL functions or aggregates.  The only differences between
4357 ** these routines are the text encoding expected for
4358 ** the second parameter (the name of the function being created)
4359 ** and the presence or absence of a destructor callback for
4360 ** the application data pointer.
4361 **
4362 ** ^The first parameter is the [database connection] to which the SQL
4363 ** function is to be added.  ^If an application uses more than one database
4364 ** connection then application-defined SQL functions must be added
4365 ** to each database connection separately.
4366 **
4367 ** ^The second parameter is the name of the SQL function to be created or
4368 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4369 ** representation, exclusive of the zero-terminator.  ^Note that the name
4370 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4371 ** ^Any attempt to create a function with a longer name
4372 ** will result in [SQLITE_MISUSE] being returned.
4373 **
4374 ** ^The third parameter (nArg)
4375 ** is the number of arguments that the SQL function or
4376 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4377 ** aggregate may take any number of arguments between 0 and the limit
4378 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4379 ** parameter is less than -1 or greater than 127 then the behavior is
4380 ** undefined.
4381 **
4382 ** ^The fourth parameter, eTextRep, specifies what
4383 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4384 ** its parameters.  Every SQL function implementation must be able to work
4385 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4386 ** more efficient with one encoding than another.  ^An application may
4387 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4388 ** times with the same function but with different values of eTextRep.
4389 ** ^When multiple implementations of the same function are available, SQLite
4390 ** will pick the one that involves the least amount of data conversion.
4391 ** If there is only a single implementation which does not care what text
4392 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4393 **
4394 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4395 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4396 **
4397 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4398 ** pointers to C-language functions that implement the SQL function or
4399 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4400 ** callback only; NULL pointers must be passed as the xStep and xFinal
4401 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4402 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4403 ** SQL function or aggregate, pass NULL pointers for all three function
4404 ** callbacks.
4405 **
4406 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4407 ** then it is destructor for the application data pointer. 
4408 ** The destructor is invoked when the function is deleted, either by being
4409 ** overloaded or when the database connection closes.)^
4410 ** ^The destructor is also invoked if the call to
4411 ** sqlite3_create_function_v2() fails.
4412 ** ^When the destructor callback of the tenth parameter is invoked, it
4413 ** is passed a single argument which is a copy of the application data 
4414 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4415 **
4416 ** ^It is permitted to register multiple implementations of the same
4417 ** functions with the same name but with either differing numbers of
4418 ** arguments or differing preferred text encodings.  ^SQLite will use
4419 ** the implementation that most closely matches the way in which the
4420 ** SQL function is used.  ^A function implementation with a non-negative
4421 ** nArg parameter is a better match than a function implementation with
4422 ** a negative nArg.  ^A function where the preferred text encoding
4423 ** matches the database encoding is a better
4424 ** match than a function where the encoding is different.  
4425 ** ^A function where the encoding difference is between UTF16le and UTF16be
4426 ** is a closer match than a function where the encoding difference is
4427 ** between UTF8 and UTF16.
4428 **
4429 ** ^Built-in functions may be overloaded by new application-defined functions.
4430 **
4431 ** ^An application-defined function is permitted to call other
4432 ** SQLite interfaces.  However, such calls must not
4433 ** close the database connection nor finalize or reset the prepared
4434 ** statement in which the function is running.
4435 */
4436 SQLITE_API int sqlite3_create_function(
4437   sqlite3 *db,
4438   const char *zFunctionName,
4439   int nArg,
4440   int eTextRep,
4441   void *pApp,
4442   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4443   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4444   void (*xFinal)(sqlite3_context*)
4445 );
4446 SQLITE_API int sqlite3_create_function16(
4447   sqlite3 *db,
4448   const void *zFunctionName,
4449   int nArg,
4450   int eTextRep,
4451   void *pApp,
4452   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4453   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4454   void (*xFinal)(sqlite3_context*)
4455 );
4456 SQLITE_API int sqlite3_create_function_v2(
4457   sqlite3 *db,
4458   const char *zFunctionName,
4459   int nArg,
4460   int eTextRep,
4461   void *pApp,
4462   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4463   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4464   void (*xFinal)(sqlite3_context*),
4465   void(*xDestroy)(void*)
4466 );
4467
4468 /*
4469 ** CAPI3REF: Text Encodings
4470 **
4471 ** These constant define integer codes that represent the various
4472 ** text encodings supported by SQLite.
4473 */
4474 #define SQLITE_UTF8           1
4475 #define SQLITE_UTF16LE        2
4476 #define SQLITE_UTF16BE        3
4477 #define SQLITE_UTF16          4    /* Use native byte order */
4478 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4479 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4480
4481 /*
4482 ** CAPI3REF: Deprecated Functions
4483 ** DEPRECATED
4484 **
4485 ** These functions are [deprecated].  In order to maintain
4486 ** backwards compatibility with older code, these functions continue 
4487 ** to be supported.  However, new applications should avoid
4488 ** the use of these functions.  To help encourage people to avoid
4489 ** using these functions, we are not going to tell you what they do.
4490 */
4491 #ifndef SQLITE_OMIT_DEPRECATED
4492 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4493 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4494 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4495 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4496 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4497 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4498 #endif
4499
4500 /*
4501 ** CAPI3REF: Obtaining SQL Function Parameter Values
4502 **
4503 ** The C-language implementation of SQL functions and aggregates uses
4504 ** this set of interface routines to access the parameter values on
4505 ** the function or aggregate.
4506 **
4507 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4508 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4509 ** define callbacks that implement the SQL functions and aggregates.
4510 ** The 3rd parameter to these callbacks is an array of pointers to
4511 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4512 ** each parameter to the SQL function.  These routines are used to
4513 ** extract values from the [sqlite3_value] objects.
4514 **
4515 ** These routines work only with [protected sqlite3_value] objects.
4516 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4517 ** object results in undefined behavior.
4518 **
4519 ** ^These routines work just like the corresponding [column access functions]
4520 ** except that  these routines take a single [protected sqlite3_value] object
4521 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4522 **
4523 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4524 ** in the native byte-order of the host machine.  ^The
4525 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4526 ** extract UTF-16 strings as big-endian and little-endian respectively.
4527 **
4528 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4529 ** numeric affinity to the value.  This means that an attempt is
4530 ** made to convert the value to an integer or floating point.  If
4531 ** such a conversion is possible without loss of information (in other
4532 ** words, if the value is a string that looks like a number)
4533 ** then the conversion is performed.  Otherwise no conversion occurs.
4534 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4535 **
4536 ** Please pay particular attention to the fact that the pointer returned
4537 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4538 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4539 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4540 ** or [sqlite3_value_text16()].
4541 **
4542 ** These routines must be called from the same thread as
4543 ** the SQL function that supplied the [sqlite3_value*] parameters.
4544 */
4545 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4546 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4547 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4548 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4549 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4550 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4551 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4552 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4553 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4554 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4555 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4556 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4557
4558 /*
4559 ** CAPI3REF: Obtain Aggregate Function Context
4560 **
4561 ** Implementations of aggregate SQL functions use this
4562 ** routine to allocate memory for storing their state.
4563 **
4564 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4565 ** for a particular aggregate function, SQLite
4566 ** allocates N of memory, zeroes out that memory, and returns a pointer
4567 ** to the new memory. ^On second and subsequent calls to
4568 ** sqlite3_aggregate_context() for the same aggregate function instance,
4569 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4570 ** called once for each invocation of the xStep callback and then one
4571 ** last time when the xFinal callback is invoked.  ^(When no rows match
4572 ** an aggregate query, the xStep() callback of the aggregate function
4573 ** implementation is never called and xFinal() is called exactly once.
4574 ** In those cases, sqlite3_aggregate_context() might be called for the
4575 ** first time from within xFinal().)^
4576 **
4577 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4578 ** less than or equal to zero or if a memory allocate error occurs.
4579 **
4580 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4581 ** determined by the N parameter on first successful call.  Changing the
4582 ** value of N in subsequent call to sqlite3_aggregate_context() within
4583 ** the same aggregate function instance will not resize the memory
4584 ** allocation.)^
4585 **
4586 ** ^SQLite automatically frees the memory allocated by 
4587 ** sqlite3_aggregate_context() when the aggregate query concludes.
4588 **
4589 ** The first parameter must be a copy of the
4590 ** [sqlite3_context | SQL function context] that is the first parameter
4591 ** to the xStep or xFinal callback routine that implements the aggregate
4592 ** function.
4593 **
4594 ** This routine must be called from the same thread in which
4595 ** the aggregate SQL function is running.
4596 */
4597 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4598
4599 /*
4600 ** CAPI3REF: User Data For Functions
4601 **
4602 ** ^The sqlite3_user_data() interface returns a copy of
4603 ** the pointer that was the pUserData parameter (the 5th parameter)
4604 ** of the [sqlite3_create_function()]
4605 ** and [sqlite3_create_function16()] routines that originally
4606 ** registered the application defined function.
4607 **
4608 ** This routine must be called from the same thread in which
4609 ** the application-defined function is running.
4610 */
4611 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4612
4613 /*
4614 ** CAPI3REF: Database Connection For Functions
4615 **
4616 ** ^The sqlite3_context_db_handle() interface returns a copy of
4617 ** the pointer to the [database connection] (the 1st parameter)
4618 ** of the [sqlite3_create_function()]
4619 ** and [sqlite3_create_function16()] routines that originally
4620 ** registered the application defined function.
4621 */
4622 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4623
4624 /*
4625 ** CAPI3REF: Function Auxiliary Data
4626 **
4627 ** The following two functions may be used by scalar SQL functions to
4628 ** associate metadata with argument values. If the same value is passed to
4629 ** multiple invocations of the same SQL function during query execution, under
4630 ** some circumstances the associated metadata may be preserved. This may
4631 ** be used, for example, to add a regular-expression matching scalar
4632 ** function. The compiled version of the regular expression is stored as
4633 ** metadata associated with the SQL value passed as the regular expression
4634 ** pattern.  The compiled regular expression can be reused on multiple
4635 ** invocations of the same function so that the original pattern string
4636 ** does not need to be recompiled on each invocation.
4637 **
4638 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4639 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4640 ** value to the application-defined function. ^If no metadata has been ever
4641 ** been set for the Nth argument of the function, or if the corresponding
4642 ** function parameter has changed since the meta-data was set,
4643 ** then sqlite3_get_auxdata() returns a NULL pointer.
4644 **
4645 ** ^The sqlite3_set_auxdata() interface saves the metadata
4646 ** pointed to by its 3rd parameter as the metadata for the N-th
4647 ** argument of the application-defined function.  Subsequent
4648 ** calls to sqlite3_get_auxdata() might return this data, if it has
4649 ** not been destroyed.
4650 ** ^If it is not NULL, SQLite will invoke the destructor
4651 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4652 ** the metadata when the corresponding function parameter changes
4653 ** or when the SQL statement completes, whichever comes first.
4654 **
4655 ** SQLite is free to call the destructor and drop metadata on any
4656 ** parameter of any function at any time.  ^The only guarantee is that
4657 ** the destructor will be called before the metadata is dropped.
4658 **
4659 ** ^(In practice, metadata is preserved between function calls for
4660 ** expressions that are constant at compile time. This includes literal
4661 ** values and [parameters].)^
4662 **
4663 ** These routines must be called from the same thread in which
4664 ** the SQL function is running.
4665 */
4666 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4667 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4668
4669
4670 /*
4671 ** CAPI3REF: Constants Defining Special Destructor Behavior
4672 **
4673 ** These are special values for the destructor that is passed in as the
4674 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4675 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4676 ** and will never change.  It does not need to be destroyed.  ^The
4677 ** SQLITE_TRANSIENT value means that the content will likely change in
4678 ** the near future and that SQLite should make its own private copy of
4679 ** the content before returning.
4680 **
4681 ** The typedef is necessary to work around problems in certain
4682 ** C++ compilers.  See ticket #2191.
4683 */
4684 typedef void (*sqlite3_destructor_type)(void*);
4685 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4686 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4687
4688 /*
4689 ** CAPI3REF: Setting The Result Of An SQL Function
4690 **
4691 ** These routines are used by the xFunc or xFinal callbacks that
4692 ** implement SQL functions and aggregates.  See
4693 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4694 ** for additional information.
4695 **
4696 ** These functions work very much like the [parameter binding] family of
4697 ** functions used to bind values to host parameters in prepared statements.
4698 ** Refer to the [SQL parameter] documentation for additional information.
4699 **
4700 ** ^The sqlite3_result_blob() interface sets the result from
4701 ** an application-defined function to be the BLOB whose content is pointed
4702 ** to by the second parameter and which is N bytes long where N is the
4703 ** third parameter.
4704 **
4705 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4706 ** the application-defined function to be a BLOB containing all zero
4707 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4708 **
4709 ** ^The sqlite3_result_double() interface sets the result from
4710 ** an application-defined function to be a floating point value specified
4711 ** by its 2nd argument.
4712 **
4713 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4714 ** cause the implemented SQL function to throw an exception.
4715 ** ^SQLite uses the string pointed to by the
4716 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4717 ** as the text of an error message.  ^SQLite interprets the error
4718 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4719 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4720 ** byte order.  ^If the third parameter to sqlite3_result_error()
4721 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4722 ** message all text up through the first zero character.
4723 ** ^If the third parameter to sqlite3_result_error() or
4724 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4725 ** bytes (not characters) from the 2nd parameter as the error message.
4726 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4727 ** routines make a private copy of the error message text before
4728 ** they return.  Hence, the calling function can deallocate or
4729 ** modify the text after they return without harm.
4730 ** ^The sqlite3_result_error_code() function changes the error code
4731 ** returned by SQLite as a result of an error in a function.  ^By default,
4732 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4733 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4734 **
4735 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4736 ** error indicating that a string or BLOB is too long to represent.
4737 **
4738 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4739 ** error indicating that a memory allocation failed.
4740 **
4741 ** ^The sqlite3_result_int() interface sets the return value
4742 ** of the application-defined function to be the 32-bit signed integer
4743 ** value given in the 2nd argument.
4744 ** ^The sqlite3_result_int64() interface sets the return value
4745 ** of the application-defined function to be the 64-bit signed integer
4746 ** value given in the 2nd argument.
4747 **
4748 ** ^The sqlite3_result_null() interface sets the return value
4749 ** of the application-defined function to be NULL.
4750 **
4751 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4752 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4753 ** set the return value of the application-defined function to be
4754 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4755 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4756 ** ^SQLite takes the text result from the application from
4757 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4758 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4759 ** is negative, then SQLite takes result text from the 2nd parameter
4760 ** through the first zero character.
4761 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4762 ** is non-negative, then as many bytes (not characters) of the text
4763 ** pointed to by the 2nd parameter are taken as the application-defined
4764 ** function result.  If the 3rd parameter is non-negative, then it
4765 ** must be the byte offset into the string where the NUL terminator would
4766 ** appear if the string where NUL terminated.  If any NUL characters occur
4767 ** in the string at a byte offset that is less than the value of the 3rd
4768 ** parameter, then the resulting string will contain embedded NULs and the
4769 ** result of expressions operating on strings with embedded NULs is undefined.
4770 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4771 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4772 ** function as the destructor on the text or BLOB result when it has
4773 ** finished using that result.
4774 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4775 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4776 ** assumes that the text or BLOB result is in constant space and does not
4777 ** copy the content of the parameter nor call a destructor on the content
4778 ** when it has finished using that result.
4779 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4780 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4781 ** then SQLite makes a copy of the result into space obtained from
4782 ** from [sqlite3_malloc()] before it returns.
4783 **
4784 ** ^The sqlite3_result_value() interface sets the result of
4785 ** the application-defined function to be a copy the
4786 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4787 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4788 ** so that the [sqlite3_value] specified in the parameter may change or
4789 ** be deallocated after sqlite3_result_value() returns without harm.
4790 ** ^A [protected sqlite3_value] object may always be used where an
4791 ** [unprotected sqlite3_value] object is required, so either
4792 ** kind of [sqlite3_value] object can be used with this interface.
4793 **
4794 ** If these routines are called from within the different thread
4795 ** than the one containing the application-defined function that received
4796 ** the [sqlite3_context] pointer, the results are undefined.
4797 */
4798 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4799 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4800 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4801 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4802 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4803 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4804 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4805 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4806 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4807 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4808 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4809 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4810 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4811 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4812 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4813 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4814
4815 /*
4816 ** CAPI3REF: Define New Collating Sequences
4817 **
4818 ** ^These functions add, remove, or modify a [collation] associated
4819 ** with the [database connection] specified as the first argument.
4820 **
4821 ** ^The name of the collation is a UTF-8 string
4822 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4823 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4824 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4825 ** considered to be the same name.
4826 **
4827 ** ^(The third argument (eTextRep) must be one of the constants:
4828 ** <ul>
4829 ** <li> [SQLITE_UTF8],
4830 ** <li> [SQLITE_UTF16LE],
4831 ** <li> [SQLITE_UTF16BE],
4832 ** <li> [SQLITE_UTF16], or
4833 ** <li> [SQLITE_UTF16_ALIGNED].
4834 ** </ul>)^
4835 ** ^The eTextRep argument determines the encoding of strings passed
4836 ** to the collating function callback, xCallback.
4837 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4838 ** force strings to be UTF16 with native byte order.
4839 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4840 ** on an even byte address.
4841 **
4842 ** ^The fourth argument, pArg, is an application data pointer that is passed
4843 ** through as the first argument to the collating function callback.
4844 **
4845 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4846 ** ^Multiple collating functions can be registered using the same name but
4847 ** with different eTextRep parameters and SQLite will use whichever
4848 ** function requires the least amount of data transformation.
4849 ** ^If the xCallback argument is NULL then the collating function is
4850 ** deleted.  ^When all collating functions having the same name are deleted,
4851 ** that collation is no longer usable.
4852 **
4853 ** ^The collating function callback is invoked with a copy of the pArg 
4854 ** application data pointer and with two strings in the encoding specified
4855 ** by the eTextRep argument.  The collating function must return an
4856 ** integer that is negative, zero, or positive
4857 ** if the first string is less than, equal to, or greater than the second,
4858 ** respectively.  A collating function must always return the same answer
4859 ** given the same inputs.  If two or more collating functions are registered
4860 ** to the same collation name (using different eTextRep values) then all
4861 ** must give an equivalent answer when invoked with equivalent strings.
4862 ** The collating function must obey the following properties for all
4863 ** strings A, B, and C:
4864 **
4865 ** <ol>
4866 ** <li> If A==B then B==A.
4867 ** <li> If A==B and B==C then A==C.
4868 ** <li> If A&lt;B THEN B&gt;A.
4869 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4870 ** </ol>
4871 **
4872 ** If a collating function fails any of the above constraints and that
4873 ** collating function is  registered and used, then the behavior of SQLite
4874 ** is undefined.
4875 **
4876 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4877 ** with the addition that the xDestroy callback is invoked on pArg when
4878 ** the collating function is deleted.
4879 ** ^Collating functions are deleted when they are overridden by later
4880 ** calls to the collation creation functions or when the
4881 ** [database connection] is closed using [sqlite3_close()].
4882 **
4883 ** ^The xDestroy callback is <u>not</u> called if the 
4884 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4885 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4886 ** check the return code and dispose of the application data pointer
4887 ** themselves rather than expecting SQLite to deal with it for them.
4888 ** This is different from every other SQLite interface.  The inconsistency 
4889 ** is unfortunate but cannot be changed without breaking backwards 
4890 ** compatibility.
4891 **
4892 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4893 */
4894 SQLITE_API int sqlite3_create_collation(
4895   sqlite3*, 
4896   const char *zName, 
4897   int eTextRep, 
4898   void *pArg,
4899   int(*xCompare)(void*,int,const void*,int,const void*)
4900 );
4901 SQLITE_API int sqlite3_create_collation_v2(
4902   sqlite3*, 
4903   const char *zName, 
4904   int eTextRep, 
4905   void *pArg,
4906   int(*xCompare)(void*,int,const void*,int,const void*),
4907   void(*xDestroy)(void*)
4908 );
4909 SQLITE_API int sqlite3_create_collation16(
4910   sqlite3*, 
4911   const void *zName,
4912   int eTextRep, 
4913   void *pArg,
4914   int(*xCompare)(void*,int,const void*,int,const void*)
4915 );
4916
4917 /*
4918 ** CAPI3REF: Collation Needed Callbacks
4919 **
4920 ** ^To avoid having to register all collation sequences before a database
4921 ** can be used, a single callback function may be registered with the
4922 ** [database connection] to be invoked whenever an undefined collation
4923 ** sequence is required.
4924 **
4925 ** ^If the function is registered using the sqlite3_collation_needed() API,
4926 ** then it is passed the names of undefined collation sequences as strings
4927 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4928 ** the names are passed as UTF-16 in machine native byte order.
4929 ** ^A call to either function replaces the existing collation-needed callback.
4930 **
4931 ** ^(When the callback is invoked, the first argument passed is a copy
4932 ** of the second argument to sqlite3_collation_needed() or
4933 ** sqlite3_collation_needed16().  The second argument is the database
4934 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4935 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4936 ** sequence function required.  The fourth parameter is the name of the
4937 ** required collation sequence.)^
4938 **
4939 ** The callback function should register the desired collation using
4940 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4941 ** [sqlite3_create_collation_v2()].
4942 */
4943 SQLITE_API int sqlite3_collation_needed(
4944   sqlite3*, 
4945   void*, 
4946   void(*)(void*,sqlite3*,int eTextRep,const char*)
4947 );
4948 SQLITE_API int sqlite3_collation_needed16(
4949   sqlite3*, 
4950   void*,
4951   void(*)(void*,sqlite3*,int eTextRep,const void*)
4952 );
4953
4954 #ifdef SQLITE_HAS_CODEC
4955 /*
4956 ** Specify the key for an encrypted database.  This routine should be
4957 ** called right after sqlite3_open().
4958 **
4959 ** The code to implement this API is not available in the public release
4960 ** of SQLite.
4961 */
4962 SQLITE_API int sqlite3_key(
4963   sqlite3 *db,                   /* Database to be rekeyed */
4964   const void *pKey, int nKey     /* The key */
4965 );
4966
4967 /*
4968 ** Change the key on an open database.  If the current database is not
4969 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4970 ** database is decrypted.
4971 **
4972 ** The code to implement this API is not available in the public release
4973 ** of SQLite.
4974 */
4975 SQLITE_API int sqlite3_rekey(
4976   sqlite3 *db,                   /* Database to be rekeyed */
4977   const void *pKey, int nKey     /* The new key */
4978 );
4979
4980 /*
4981 ** Specify the activation key for a SEE database.  Unless 
4982 ** activated, none of the SEE routines will work.
4983 */
4984 SQLITE_API void sqlite3_activate_see(
4985   const char *zPassPhrase        /* Activation phrase */
4986 );
4987 #endif
4988
4989 #ifdef SQLITE_ENABLE_CEROD
4990 /*
4991 ** Specify the activation key for a CEROD database.  Unless 
4992 ** activated, none of the CEROD routines will work.
4993 */
4994 SQLITE_API void sqlite3_activate_cerod(
4995   const char *zPassPhrase        /* Activation phrase */
4996 );
4997 #endif
4998
4999 /*
5000 ** CAPI3REF: Suspend Execution For A Short Time
5001 **
5002 ** The sqlite3_sleep() function causes the current thread to suspend execution
5003 ** for at least a number of milliseconds specified in its parameter.
5004 **
5005 ** If the operating system does not support sleep requests with
5006 ** millisecond time resolution, then the time will be rounded up to
5007 ** the nearest second. The number of milliseconds of sleep actually
5008 ** requested from the operating system is returned.
5009 **
5010 ** ^SQLite implements this interface by calling the xSleep()
5011 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5012 ** of the default VFS is not implemented correctly, or not implemented at
5013 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5014 ** in the previous paragraphs.
5015 */
5016 SQLITE_API int sqlite3_sleep(int);
5017
5018 /*
5019 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5020 **
5021 ** ^(If this global variable is made to point to a string which is
5022 ** the name of a folder (a.k.a. directory), then all temporary files
5023 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5024 ** will be placed in that directory.)^  ^If this variable
5025 ** is a NULL pointer, then SQLite performs a search for an appropriate
5026 ** temporary file directory.
5027 **
5028 ** It is not safe to read or modify this variable in more than one
5029 ** thread at a time.  It is not safe to read or modify this variable
5030 ** if a [database connection] is being used at the same time in a separate
5031 ** thread.
5032 ** It is intended that this variable be set once
5033 ** as part of process initialization and before any SQLite interface
5034 ** routines have been called and that this variable remain unchanged
5035 ** thereafter.
5036 **
5037 ** ^The [temp_store_directory pragma] may modify this variable and cause
5038 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5039 ** the [temp_store_directory pragma] always assumes that any string
5040 ** that this variable points to is held in memory obtained from 
5041 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5042 ** using [sqlite3_free].
5043 ** Hence, if this variable is modified directly, either it should be
5044 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5045 ** or else the use of the [temp_store_directory pragma] should be avoided.
5046 **
5047 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5048 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5049 ** features that require the use of temporary files may fail.  Here is an
5050 ** example of how to do this using C++ with the Windows Runtime:
5051 **
5052 ** <blockquote><pre>
5053 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5054 ** &nbsp;     TemporaryFolder->Path->Data();
5055 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5056 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5057 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5058 ** &nbsp;     NULL, NULL);
5059 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5060 ** </pre></blockquote>
5061 */
5062 SQLITE_API char *sqlite3_temp_directory;
5063
5064 /*
5065 ** CAPI3REF: Name Of The Folder Holding Database Files
5066 **
5067 ** ^(If this global variable is made to point to a string which is
5068 ** the name of a folder (a.k.a. directory), then all database files
5069 ** specified with a relative pathname and created or accessed by
5070 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5071 ** to be relative to that directory.)^ ^If this variable is a NULL
5072 ** pointer, then SQLite assumes that all database files specified
5073 ** with a relative pathname are relative to the current directory
5074 ** for the process.  Only the windows VFS makes use of this global
5075 ** variable; it is ignored by the unix VFS.
5076 **
5077 ** Changing the value of this variable while a database connection is
5078 ** open can result in a corrupt database.
5079 **
5080 ** It is not safe to read or modify this variable in more than one
5081 ** thread at a time.  It is not safe to read or modify this variable
5082 ** if a [database connection] is being used at the same time in a separate
5083 ** thread.
5084 ** It is intended that this variable be set once
5085 ** as part of process initialization and before any SQLite interface
5086 ** routines have been called and that this variable remain unchanged
5087 ** thereafter.
5088 **
5089 ** ^The [data_store_directory pragma] may modify this variable and cause
5090 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5091 ** the [data_store_directory pragma] always assumes that any string
5092 ** that this variable points to is held in memory obtained from 
5093 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5094 ** using [sqlite3_free].
5095 ** Hence, if this variable is modified directly, either it should be
5096 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5097 ** or else the use of the [data_store_directory pragma] should be avoided.
5098 */
5099 SQLITE_API char *sqlite3_data_directory;
5100
5101 /*
5102 ** CAPI3REF: Test For Auto-Commit Mode
5103 ** KEYWORDS: {autocommit mode}
5104 **
5105 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5106 ** zero if the given database connection is or is not in autocommit mode,
5107 ** respectively.  ^Autocommit mode is on by default.
5108 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5109 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5110 **
5111 ** If certain kinds of errors occur on a statement within a multi-statement
5112 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5113 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5114 ** transaction might be rolled back automatically.  The only way to
5115 ** find out whether SQLite automatically rolled back the transaction after
5116 ** an error is to use this function.
5117 **
5118 ** If another thread changes the autocommit status of the database
5119 ** connection while this routine is running, then the return value
5120 ** is undefined.
5121 */
5122 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5123
5124 /*
5125 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5126 **
5127 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5128 ** to which a [prepared statement] belongs.  ^The [database connection]
5129 ** returned by sqlite3_db_handle is the same [database connection]
5130 ** that was the first argument
5131 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5132 ** create the statement in the first place.
5133 */
5134 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5135
5136 /*
5137 ** CAPI3REF: Return The Filename For A Database Connection
5138 **
5139 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5140 ** associated with database N of connection D.  ^The main database file
5141 ** has the name "main".  If there is no attached database N on the database
5142 ** connection D, or if database N is a temporary or in-memory database, then
5143 ** a NULL pointer is returned.
5144 **
5145 ** ^The filename returned by this function is the output of the
5146 ** xFullPathname method of the [VFS].  ^In other words, the filename
5147 ** will be an absolute pathname, even if the filename used
5148 ** to open the database originally was a URI or relative pathname.
5149 */
5150 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5151
5152 /*
5153 ** CAPI3REF: Determine if a database is read-only
5154 **
5155 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5156 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5157 ** the name of a database on connection D.
5158 */
5159 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5160
5161 /*
5162 ** CAPI3REF: Find the next prepared statement
5163 **
5164 ** ^This interface returns a pointer to the next [prepared statement] after
5165 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5166 ** then this interface returns a pointer to the first prepared statement
5167 ** associated with the database connection pDb.  ^If no prepared statement
5168 ** satisfies the conditions of this routine, it returns NULL.
5169 **
5170 ** The [database connection] pointer D in a call to
5171 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5172 ** connection and in particular must not be a NULL pointer.
5173 */
5174 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5175
5176 /*
5177 ** CAPI3REF: Commit And Rollback Notification Callbacks
5178 **
5179 ** ^The sqlite3_commit_hook() interface registers a callback
5180 ** function to be invoked whenever a transaction is [COMMIT | committed].
5181 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5182 ** for the same database connection is overridden.
5183 ** ^The sqlite3_rollback_hook() interface registers a callback
5184 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5185 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5186 ** for the same database connection is overridden.
5187 ** ^The pArg argument is passed through to the callback.
5188 ** ^If the callback on a commit hook function returns non-zero,
5189 ** then the commit is converted into a rollback.
5190 **
5191 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5192 ** return the P argument from the previous call of the same function
5193 ** on the same [database connection] D, or NULL for
5194 ** the first call for each function on D.
5195 **
5196 ** The commit and rollback hook callbacks are not reentrant.
5197 ** The callback implementation must not do anything that will modify
5198 ** the database connection that invoked the callback.  Any actions
5199 ** to modify the database connection must be deferred until after the
5200 ** completion of the [sqlite3_step()] call that triggered the commit
5201 ** or rollback hook in the first place.
5202 ** Note that running any other SQL statements, including SELECT statements,
5203 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5204 ** the database connections for the meaning of "modify" in this paragraph.
5205 **
5206 ** ^Registering a NULL function disables the callback.
5207 **
5208 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5209 ** operation is allowed to continue normally.  ^If the commit hook
5210 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5211 ** ^The rollback hook is invoked on a rollback that results from a commit
5212 ** hook returning non-zero, just as it would be with any other rollback.
5213 **
5214 ** ^For the purposes of this API, a transaction is said to have been
5215 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5216 ** an error or constraint causes an implicit rollback to occur.
5217 ** ^The rollback callback is not invoked if a transaction is
5218 ** automatically rolled back because the database connection is closed.
5219 **
5220 ** See also the [sqlite3_update_hook()] interface.
5221 */
5222 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5223 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5224
5225 /*
5226 ** CAPI3REF: Data Change Notification Callbacks
5227 **
5228 ** ^The sqlite3_update_hook() interface registers a callback function
5229 ** with the [database connection] identified by the first argument
5230 ** to be invoked whenever a row is updated, inserted or deleted.
5231 ** ^Any callback set by a previous call to this function
5232 ** for the same database connection is overridden.
5233 **
5234 ** ^The second argument is a pointer to the function to invoke when a
5235 ** row is updated, inserted or deleted.
5236 ** ^The first argument to the callback is a copy of the third argument
5237 ** to sqlite3_update_hook().
5238 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5239 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5240 ** to be invoked.
5241 ** ^The third and fourth arguments to the callback contain pointers to the
5242 ** database and table name containing the affected row.
5243 ** ^The final callback parameter is the [rowid] of the row.
5244 ** ^In the case of an update, this is the [rowid] after the update takes place.
5245 **
5246 ** ^(The update hook is not invoked when internal system tables are
5247 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5248 **
5249 ** ^In the current implementation, the update hook
5250 ** is not invoked when duplication rows are deleted because of an
5251 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5252 ** invoked when rows are deleted using the [truncate optimization].
5253 ** The exceptions defined in this paragraph might change in a future
5254 ** release of SQLite.
5255 **
5256 ** The update hook implementation must not do anything that will modify
5257 ** the database connection that invoked the update hook.  Any actions
5258 ** to modify the database connection must be deferred until after the
5259 ** completion of the [sqlite3_step()] call that triggered the update hook.
5260 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5261 ** database connections for the meaning of "modify" in this paragraph.
5262 **
5263 ** ^The sqlite3_update_hook(D,C,P) function
5264 ** returns the P argument from the previous call
5265 ** on the same [database connection] D, or NULL for
5266 ** the first call on D.
5267 **
5268 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5269 ** interfaces.
5270 */
5271 SQLITE_API void *sqlite3_update_hook(
5272   sqlite3*, 
5273   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5274   void*
5275 );
5276
5277 /*
5278 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5279 **
5280 ** ^(This routine enables or disables the sharing of the database cache
5281 ** and schema data structures between [database connection | connections]
5282 ** to the same database. Sharing is enabled if the argument is true
5283 ** and disabled if the argument is false.)^
5284 **
5285 ** ^Cache sharing is enabled and disabled for an entire process.
5286 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5287 ** sharing was enabled or disabled for each thread separately.
5288 **
5289 ** ^(The cache sharing mode set by this interface effects all subsequent
5290 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5291 ** Existing database connections continue use the sharing mode
5292 ** that was in effect at the time they were opened.)^
5293 **
5294 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5295 ** successfully.  An [error code] is returned otherwise.)^
5296 **
5297 ** ^Shared cache is disabled by default. But this might change in
5298 ** future releases of SQLite.  Applications that care about shared
5299 ** cache setting should set it explicitly.
5300 **
5301 ** See Also:  [SQLite Shared-Cache Mode]
5302 */
5303 SQLITE_API int sqlite3_enable_shared_cache(int);
5304
5305 /*
5306 ** CAPI3REF: Attempt To Free Heap Memory
5307 **
5308 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5309 ** of heap memory by deallocating non-essential memory allocations
5310 ** held by the database library.   Memory used to cache database
5311 ** pages to improve performance is an example of non-essential memory.
5312 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5313 ** which might be more or less than the amount requested.
5314 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5315 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5316 **
5317 ** See also: [sqlite3_db_release_memory()]
5318 */
5319 SQLITE_API int sqlite3_release_memory(int);
5320
5321 /*
5322 ** CAPI3REF: Free Memory Used By A Database Connection
5323 **
5324 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5325 ** memory as possible from database connection D. Unlike the
5326 ** [sqlite3_release_memory()] interface, this interface is effect even
5327 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5328 ** omitted.
5329 **
5330 ** See also: [sqlite3_release_memory()]
5331 */
5332 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5333
5334 /*
5335 ** CAPI3REF: Impose A Limit On Heap Size
5336 **
5337 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5338 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5339 ** ^SQLite strives to keep heap memory utilization below the soft heap
5340 ** limit by reducing the number of pages held in the page cache
5341 ** as heap memory usages approaches the limit.
5342 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5343 ** below the limit, it will exceed the limit rather than generate
5344 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5345 ** is advisory only.
5346 **
5347 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5348 ** the soft heap limit prior to the call, or negative in the case of an
5349 ** error.  ^If the argument N is negative
5350 ** then no change is made to the soft heap limit.  Hence, the current
5351 ** size of the soft heap limit can be determined by invoking
5352 ** sqlite3_soft_heap_limit64() with a negative argument.
5353 **
5354 ** ^If the argument N is zero then the soft heap limit is disabled.
5355 **
5356 ** ^(The soft heap limit is not enforced in the current implementation
5357 ** if one or more of following conditions are true:
5358 **
5359 ** <ul>
5360 ** <li> The soft heap limit is set to zero.
5361 ** <li> Memory accounting is disabled using a combination of the
5362 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5363 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5364 ** <li> An alternative page cache implementation is specified using
5365 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5366 ** <li> The page cache allocates from its own memory pool supplied
5367 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5368 **      from the heap.
5369 ** </ul>)^
5370 **
5371 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5372 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5373 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5374 ** the soft heap limit is enforced on every memory allocation.  Without
5375 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5376 ** when memory is allocated by the page cache.  Testing suggests that because
5377 ** the page cache is the predominate memory user in SQLite, most
5378 ** applications will achieve adequate soft heap limit enforcement without
5379 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5380 **
5381 ** The circumstances under which SQLite will enforce the soft heap limit may
5382 ** changes in future releases of SQLite.
5383 */
5384 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5385
5386 /*
5387 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5388 ** DEPRECATED
5389 **
5390 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5391 ** interface.  This routine is provided for historical compatibility
5392 ** only.  All new applications should use the
5393 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5394 */
5395 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5396
5397
5398 /*
5399 ** CAPI3REF: Extract Metadata About A Column Of A Table
5400 **
5401 ** ^This routine returns metadata about a specific column of a specific
5402 ** database table accessible using the [database connection] handle
5403 ** passed as the first function argument.
5404 **
5405 ** ^The column is identified by the second, third and fourth parameters to
5406 ** this function. ^The second parameter is either the name of the database
5407 ** (i.e. "main", "temp", or an attached database) containing the specified
5408 ** table or NULL. ^If it is NULL, then all attached databases are searched
5409 ** for the table using the same algorithm used by the database engine to
5410 ** resolve unqualified table references.
5411 **
5412 ** ^The third and fourth parameters to this function are the table and column
5413 ** name of the desired column, respectively. Neither of these parameters
5414 ** may be NULL.
5415 **
5416 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5417 ** and subsequent parameters to this function. ^Any of these arguments may be
5418 ** NULL, in which case the corresponding element of metadata is omitted.
5419 **
5420 ** ^(<blockquote>
5421 ** <table border="1">
5422 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5423 **
5424 ** <tr><td> 5th <td> const char* <td> Data type
5425 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5426 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5427 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5428 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5429 ** </table>
5430 ** </blockquote>)^
5431 **
5432 ** ^The memory pointed to by the character pointers returned for the
5433 ** declaration type and collation sequence is valid only until the next
5434 ** call to any SQLite API function.
5435 **
5436 ** ^If the specified table is actually a view, an [error code] is returned.
5437 **
5438 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5439 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5440 ** parameters are set for the explicitly declared column. ^(If there is no
5441 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5442 ** parameters are set as follows:
5443 **
5444 ** <pre>
5445 **     data type: "INTEGER"
5446 **     collation sequence: "BINARY"
5447 **     not null: 0
5448 **     primary key: 1
5449 **     auto increment: 0
5450 ** </pre>)^
5451 **
5452 ** ^(This function may load one or more schemas from database files. If an
5453 ** error occurs during this process, or if the requested table or column
5454 ** cannot be found, an [error code] is returned and an error message left
5455 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5456 **
5457 ** ^This API is only available if the library was compiled with the
5458 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5459 */
5460 SQLITE_API int sqlite3_table_column_metadata(
5461   sqlite3 *db,                /* Connection handle */
5462   const char *zDbName,        /* Database name or NULL */
5463   const char *zTableName,     /* Table name */
5464   const char *zColumnName,    /* Column name */
5465   char const **pzDataType,    /* OUTPUT: Declared data type */
5466   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5467   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5468   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5469   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5470 );
5471
5472 /*
5473 ** CAPI3REF: Load An Extension
5474 **
5475 ** ^This interface loads an SQLite extension library from the named file.
5476 **
5477 ** ^The sqlite3_load_extension() interface attempts to load an
5478 ** SQLite extension library contained in the file zFile.
5479 **
5480 ** ^The entry point is zProc.
5481 ** ^zProc may be 0, in which case the name of the entry point
5482 ** defaults to "sqlite3_extension_init".
5483 ** ^The sqlite3_load_extension() interface returns
5484 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5485 ** ^If an error occurs and pzErrMsg is not 0, then the
5486 ** [sqlite3_load_extension()] interface shall attempt to
5487 ** fill *pzErrMsg with error message text stored in memory
5488 ** obtained from [sqlite3_malloc()]. The calling function
5489 ** should free this memory by calling [sqlite3_free()].
5490 **
5491 ** ^Extension loading must be enabled using
5492 ** [sqlite3_enable_load_extension()] prior to calling this API,
5493 ** otherwise an error will be returned.
5494 **
5495 ** See also the [load_extension() SQL function].
5496 */
5497 SQLITE_API int sqlite3_load_extension(
5498   sqlite3 *db,          /* Load the extension into this database connection */
5499   const char *zFile,    /* Name of the shared library containing extension */
5500   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5501   char **pzErrMsg       /* Put error message here if not 0 */
5502 );
5503
5504 /*
5505 ** CAPI3REF: Enable Or Disable Extension Loading
5506 **
5507 ** ^So as not to open security holes in older applications that are
5508 ** unprepared to deal with extension loading, and as a means of disabling
5509 ** extension loading while evaluating user-entered SQL, the following API
5510 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5511 **
5512 ** ^Extension loading is off by default. See ticket #1863.
5513 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5514 ** to turn extension loading on and call it with onoff==0 to turn
5515 ** it back off again.
5516 */
5517 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5518
5519 /*
5520 ** CAPI3REF: Automatically Load Statically Linked Extensions
5521 **
5522 ** ^This interface causes the xEntryPoint() function to be invoked for
5523 ** each new [database connection] that is created.  The idea here is that
5524 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5525 ** that is to be automatically loaded into all new database connections.
5526 **
5527 ** ^(Even though the function prototype shows that xEntryPoint() takes
5528 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5529 ** arguments and expects and integer result as if the signature of the
5530 ** entry point where as follows:
5531 **
5532 ** <blockquote><pre>
5533 ** &nbsp;  int xEntryPoint(
5534 ** &nbsp;    sqlite3 *db,
5535 ** &nbsp;    const char **pzErrMsg,
5536 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5537 ** &nbsp;  );
5538 ** </pre></blockquote>)^
5539 **
5540 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5541 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5542 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5543 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5544 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5545 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5546 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5547 **
5548 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5549 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5550 ** will be called more than once for each database connection that is opened.
5551 **
5552 ** See also: [sqlite3_reset_auto_extension()].
5553 */
5554 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5555
5556 /*
5557 ** CAPI3REF: Reset Automatic Extension Loading
5558 **
5559 ** ^This interface disables all automatic extensions previously
5560 ** registered using [sqlite3_auto_extension()].
5561 */
5562 SQLITE_API void sqlite3_reset_auto_extension(void);
5563
5564 /*
5565 ** The interface to the virtual-table mechanism is currently considered
5566 ** to be experimental.  The interface might change in incompatible ways.
5567 ** If this is a problem for you, do not use the interface at this time.
5568 **
5569 ** When the virtual-table mechanism stabilizes, we will declare the
5570 ** interface fixed, support it indefinitely, and remove this comment.
5571 */
5572
5573 /*
5574 ** Structures used by the virtual table interface
5575 */
5576 typedef struct sqlite3_vtab sqlite3_vtab;
5577 typedef struct sqlite3_index_info sqlite3_index_info;
5578 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5579 typedef struct sqlite3_module sqlite3_module;
5580
5581 /*
5582 ** CAPI3REF: Virtual Table Object
5583 ** KEYWORDS: sqlite3_module {virtual table module}
5584 **
5585 ** This structure, sometimes called a "virtual table module", 
5586 ** defines the implementation of a [virtual tables].  
5587 ** This structure consists mostly of methods for the module.
5588 **
5589 ** ^A virtual table module is created by filling in a persistent
5590 ** instance of this structure and passing a pointer to that instance
5591 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5592 ** ^The registration remains valid until it is replaced by a different
5593 ** module or until the [database connection] closes.  The content
5594 ** of this structure must not change while it is registered with
5595 ** any database connection.
5596 */
5597 struct sqlite3_module {
5598   int iVersion;
5599   int (*xCreate)(sqlite3*, void *pAux,
5600                int argc, const char *const*argv,
5601                sqlite3_vtab **ppVTab, char**);
5602   int (*xConnect)(sqlite3*, void *pAux,
5603                int argc, const char *const*argv,
5604                sqlite3_vtab **ppVTab, char**);
5605   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5606   int (*xDisconnect)(sqlite3_vtab *pVTab);
5607   int (*xDestroy)(sqlite3_vtab *pVTab);
5608   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5609   int (*xClose)(sqlite3_vtab_cursor*);
5610   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5611                 int argc, sqlite3_value **argv);
5612   int (*xNext)(sqlite3_vtab_cursor*);
5613   int (*xEof)(sqlite3_vtab_cursor*);
5614   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5615   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5616   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5617   int (*xBegin)(sqlite3_vtab *pVTab);
5618   int (*xSync)(sqlite3_vtab *pVTab);
5619   int (*xCommit)(sqlite3_vtab *pVTab);
5620   int (*xRollback)(sqlite3_vtab *pVTab);
5621   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5622                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5623                        void **ppArg);
5624   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5625   /* The methods above are in version 1 of the sqlite_module object. Those 
5626   ** below are for version 2 and greater. */
5627   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5628   int (*xRelease)(sqlite3_vtab *pVTab, int);
5629   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5630 };
5631
5632 /*
5633 ** CAPI3REF: Virtual Table Indexing Information
5634 ** KEYWORDS: sqlite3_index_info
5635 **
5636 ** The sqlite3_index_info structure and its substructures is used as part
5637 ** of the [virtual table] interface to
5638 ** pass information into and receive the reply from the [xBestIndex]
5639 ** method of a [virtual table module].  The fields under **Inputs** are the
5640 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5641 ** results into the **Outputs** fields.
5642 **
5643 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5644 **
5645 ** <blockquote>column OP expr</blockquote>
5646 **
5647 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5648 ** stored in aConstraint[].op using one of the
5649 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5650 ** ^(The index of the column is stored in
5651 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5652 ** expr on the right-hand side can be evaluated (and thus the constraint
5653 ** is usable) and false if it cannot.)^
5654 **
5655 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5656 ** and makes other simplifications to the WHERE clause in an attempt to
5657 ** get as many WHERE clause terms into the form shown above as possible.
5658 ** ^The aConstraint[] array only reports WHERE clause terms that are
5659 ** relevant to the particular virtual table being queried.
5660 **
5661 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5662 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5663 **
5664 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5665 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5666 ** the right-hand side of the corresponding aConstraint[] is evaluated
5667 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5668 ** is true, then the constraint is assumed to be fully handled by the
5669 ** virtual table and is not checked again by SQLite.)^
5670 **
5671 ** ^The idxNum and idxPtr values are recorded and passed into the
5672 ** [xFilter] method.
5673 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5674 ** needToFreeIdxPtr is true.
5675 **
5676 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5677 ** the correct order to satisfy the ORDER BY clause so that no separate
5678 ** sorting step is required.
5679 **
5680 ** ^The estimatedCost value is an estimate of the cost of doing the
5681 ** particular lookup.  A full scan of a table with N entries should have
5682 ** a cost of N.  A binary search of a table of N entries should have a
5683 ** cost of approximately log(N).
5684 */
5685 struct sqlite3_index_info {
5686   /* Inputs */
5687   int nConstraint;           /* Number of entries in aConstraint */
5688   struct sqlite3_index_constraint {
5689      int iColumn;              /* Column on left-hand side of constraint */
5690      unsigned char op;         /* Constraint operator */
5691      unsigned char usable;     /* True if this constraint is usable */
5692      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5693   } *aConstraint;            /* Table of WHERE clause constraints */
5694   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5695   struct sqlite3_index_orderby {
5696      int iColumn;              /* Column number */
5697      unsigned char desc;       /* True for DESC.  False for ASC. */
5698   } *aOrderBy;               /* The ORDER BY clause */
5699   /* Outputs */
5700   struct sqlite3_index_constraint_usage {
5701     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5702     unsigned char omit;      /* Do not code a test for this constraint */
5703   } *aConstraintUsage;
5704   int idxNum;                /* Number used to identify the index */
5705   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5706   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5707   int orderByConsumed;       /* True if output is already ordered */
5708   double estimatedCost;      /* Estimated cost of using this index */
5709 };
5710
5711 /*
5712 ** CAPI3REF: Virtual Table Constraint Operator Codes
5713 **
5714 ** These macros defined the allowed values for the
5715 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5716 ** an operator that is part of a constraint term in the wHERE clause of
5717 ** a query that uses a [virtual table].
5718 */
5719 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5720 #define SQLITE_INDEX_CONSTRAINT_GT    4
5721 #define SQLITE_INDEX_CONSTRAINT_LE    8
5722 #define SQLITE_INDEX_CONSTRAINT_LT    16
5723 #define SQLITE_INDEX_CONSTRAINT_GE    32
5724 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5725
5726 /*
5727 ** CAPI3REF: Register A Virtual Table Implementation
5728 **
5729 ** ^These routines are used to register a new [virtual table module] name.
5730 ** ^Module names must be registered before
5731 ** creating a new [virtual table] using the module and before using a
5732 ** preexisting [virtual table] for the module.
5733 **
5734 ** ^The module name is registered on the [database connection] specified
5735 ** by the first parameter.  ^The name of the module is given by the 
5736 ** second parameter.  ^The third parameter is a pointer to
5737 ** the implementation of the [virtual table module].   ^The fourth
5738 ** parameter is an arbitrary client data pointer that is passed through
5739 ** into the [xCreate] and [xConnect] methods of the virtual table module
5740 ** when a new virtual table is be being created or reinitialized.
5741 **
5742 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5743 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5744 ** invoke the destructor function (if it is not NULL) when SQLite
5745 ** no longer needs the pClientData pointer.  ^The destructor will also
5746 ** be invoked if the call to sqlite3_create_module_v2() fails.
5747 ** ^The sqlite3_create_module()
5748 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5749 ** destructor.
5750 */
5751 SQLITE_API int sqlite3_create_module(
5752   sqlite3 *db,               /* SQLite connection to register module with */
5753   const char *zName,         /* Name of the module */
5754   const sqlite3_module *p,   /* Methods for the module */
5755   void *pClientData          /* Client data for xCreate/xConnect */
5756 );
5757 SQLITE_API int sqlite3_create_module_v2(
5758   sqlite3 *db,               /* SQLite connection to register module with */
5759   const char *zName,         /* Name of the module */
5760   const sqlite3_module *p,   /* Methods for the module */
5761   void *pClientData,         /* Client data for xCreate/xConnect */
5762   void(*xDestroy)(void*)     /* Module destructor function */
5763 );
5764
5765 /*
5766 ** CAPI3REF: Virtual Table Instance Object
5767 ** KEYWORDS: sqlite3_vtab
5768 **
5769 ** Every [virtual table module] implementation uses a subclass
5770 ** of this object to describe a particular instance
5771 ** of the [virtual table].  Each subclass will
5772 ** be tailored to the specific needs of the module implementation.
5773 ** The purpose of this superclass is to define certain fields that are
5774 ** common to all module implementations.
5775 **
5776 ** ^Virtual tables methods can set an error message by assigning a
5777 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5778 ** take care that any prior string is freed by a call to [sqlite3_free()]
5779 ** prior to assigning a new string to zErrMsg.  ^After the error message
5780 ** is delivered up to the client application, the string will be automatically
5781 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5782 */
5783 struct sqlite3_vtab {
5784   const sqlite3_module *pModule;  /* The module for this virtual table */
5785   int nRef;                       /* NO LONGER USED */
5786   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5787   /* Virtual table implementations will typically add additional fields */
5788 };
5789
5790 /*
5791 ** CAPI3REF: Virtual Table Cursor Object
5792 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5793 **
5794 ** Every [virtual table module] implementation uses a subclass of the
5795 ** following structure to describe cursors that point into the
5796 ** [virtual table] and are used
5797 ** to loop through the virtual table.  Cursors are created using the
5798 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5799 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5800 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5801 ** of the module.  Each module implementation will define
5802 ** the content of a cursor structure to suit its own needs.
5803 **
5804 ** This superclass exists in order to define fields of the cursor that
5805 ** are common to all implementations.
5806 */
5807 struct sqlite3_vtab_cursor {
5808   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5809   /* Virtual table implementations will typically add additional fields */
5810 };
5811
5812 /*
5813 ** CAPI3REF: Declare The Schema Of A Virtual Table
5814 **
5815 ** ^The [xCreate] and [xConnect] methods of a
5816 ** [virtual table module] call this interface
5817 ** to declare the format (the names and datatypes of the columns) of
5818 ** the virtual tables they implement.
5819 */
5820 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5821
5822 /*
5823 ** CAPI3REF: Overload A Function For A Virtual Table
5824 **
5825 ** ^(Virtual tables can provide alternative implementations of functions
5826 ** using the [xFindFunction] method of the [virtual table module].  
5827 ** But global versions of those functions
5828 ** must exist in order to be overloaded.)^
5829 **
5830 ** ^(This API makes sure a global version of a function with a particular
5831 ** name and number of parameters exists.  If no such function exists
5832 ** before this API is called, a new function is created.)^  ^The implementation
5833 ** of the new function always causes an exception to be thrown.  So
5834 ** the new function is not good for anything by itself.  Its only
5835 ** purpose is to be a placeholder function that can be overloaded
5836 ** by a [virtual table].
5837 */
5838 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5839
5840 /*
5841 ** The interface to the virtual-table mechanism defined above (back up
5842 ** to a comment remarkably similar to this one) is currently considered
5843 ** to be experimental.  The interface might change in incompatible ways.
5844 ** If this is a problem for you, do not use the interface at this time.
5845 **
5846 ** When the virtual-table mechanism stabilizes, we will declare the
5847 ** interface fixed, support it indefinitely, and remove this comment.
5848 */
5849
5850 /*
5851 ** CAPI3REF: A Handle To An Open BLOB
5852 ** KEYWORDS: {BLOB handle} {BLOB handles}
5853 **
5854 ** An instance of this object represents an open BLOB on which
5855 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5856 ** ^Objects of this type are created by [sqlite3_blob_open()]
5857 ** and destroyed by [sqlite3_blob_close()].
5858 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5859 ** can be used to read or write small subsections of the BLOB.
5860 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5861 */
5862 typedef struct sqlite3_blob sqlite3_blob;
5863
5864 /*
5865 ** CAPI3REF: Open A BLOB For Incremental I/O
5866 **
5867 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5868 ** in row iRow, column zColumn, table zTable in database zDb;
5869 ** in other words, the same BLOB that would be selected by:
5870 **
5871 ** <pre>
5872 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5873 ** </pre>)^
5874 **
5875 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5876 ** and write access. ^If it is zero, the BLOB is opened for read access.
5877 ** ^It is not possible to open a column that is part of an index or primary 
5878 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5879 ** not possible to open a column that is part of a [child key] for writing.
5880 **
5881 ** ^Note that the database name is not the filename that contains
5882 ** the database but rather the symbolic name of the database that
5883 ** appears after the AS keyword when the database is connected using [ATTACH].
5884 ** ^For the main database file, the database name is "main".
5885 ** ^For TEMP tables, the database name is "temp".
5886 **
5887 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5888 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5889 ** to be a null pointer.)^
5890 ** ^This function sets the [database connection] error code and message
5891 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5892 ** functions. ^Note that the *ppBlob variable is always initialized in a
5893 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5894 ** regardless of the success or failure of this routine.
5895 **
5896 ** ^(If the row that a BLOB handle points to is modified by an
5897 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5898 ** then the BLOB handle is marked as "expired".
5899 ** This is true if any column of the row is changed, even a column
5900 ** other than the one the BLOB handle is open on.)^
5901 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5902 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5903 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5904 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5905 ** commit if the transaction continues to completion.)^
5906 **
5907 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5908 ** the opened blob.  ^The size of a blob may not be changed by this
5909 ** interface.  Use the [UPDATE] SQL command to change the size of a
5910 ** blob.
5911 **
5912 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5913 ** and the built-in [zeroblob] SQL function can be used, if desired,
5914 ** to create an empty, zero-filled blob in which to read or write using
5915 ** this interface.
5916 **
5917 ** To avoid a resource leak, every open [BLOB handle] should eventually
5918 ** be released by a call to [sqlite3_blob_close()].
5919 */
5920 SQLITE_API int sqlite3_blob_open(
5921   sqlite3*,
5922   const char *zDb,
5923   const char *zTable,
5924   const char *zColumn,
5925   sqlite3_int64 iRow,
5926   int flags,
5927   sqlite3_blob **ppBlob
5928 );
5929
5930 /*
5931 ** CAPI3REF: Move a BLOB Handle to a New Row
5932 **
5933 ** ^This function is used to move an existing blob handle so that it points
5934 ** to a different row of the same database table. ^The new row is identified
5935 ** by the rowid value passed as the second argument. Only the row can be
5936 ** changed. ^The database, table and column on which the blob handle is open
5937 ** remain the same. Moving an existing blob handle to a new row can be
5938 ** faster than closing the existing handle and opening a new one.
5939 **
5940 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5941 ** it must exist and there must be either a blob or text value stored in
5942 ** the nominated column.)^ ^If the new row is not present in the table, or if
5943 ** it does not contain a blob or text value, or if another error occurs, an
5944 ** SQLite error code is returned and the blob handle is considered aborted.
5945 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5946 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5947 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5948 ** always returns zero.
5949 **
5950 ** ^This function sets the database handle error code and message.
5951 */
5952 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5953
5954 /*
5955 ** CAPI3REF: Close A BLOB Handle
5956 **
5957 ** ^Closes an open [BLOB handle].
5958 **
5959 ** ^Closing a BLOB shall cause the current transaction to commit
5960 ** if there are no other BLOBs, no pending prepared statements, and the
5961 ** database connection is in [autocommit mode].
5962 ** ^If any writes were made to the BLOB, they might be held in cache
5963 ** until the close operation if they will fit.
5964 **
5965 ** ^(Closing the BLOB often forces the changes
5966 ** out to disk and so if any I/O errors occur, they will likely occur
5967 ** at the time when the BLOB is closed.  Any errors that occur during
5968 ** closing are reported as a non-zero return value.)^
5969 **
5970 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5971 ** an error code, the BLOB is still closed.)^
5972 **
5973 ** ^Calling this routine with a null pointer (such as would be returned
5974 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5975 */
5976 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5977
5978 /*
5979 ** CAPI3REF: Return The Size Of An Open BLOB
5980 **
5981 ** ^Returns the size in bytes of the BLOB accessible via the 
5982 ** successfully opened [BLOB handle] in its only argument.  ^The
5983 ** incremental blob I/O routines can only read or overwriting existing
5984 ** blob content; they cannot change the size of a blob.
5985 **
5986 ** This routine only works on a [BLOB handle] which has been created
5987 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5988 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5989 ** to this routine results in undefined and probably undesirable behavior.
5990 */
5991 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5992
5993 /*
5994 ** CAPI3REF: Read Data From A BLOB Incrementally
5995 **
5996 ** ^(This function is used to read data from an open [BLOB handle] into a
5997 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5998 ** from the open BLOB, starting at offset iOffset.)^
5999 **
6000 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6001 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6002 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6003 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6004 ** can be determined using the [sqlite3_blob_bytes()] interface.
6005 **
6006 ** ^An attempt to read from an expired [BLOB handle] fails with an
6007 ** error code of [SQLITE_ABORT].
6008 **
6009 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6010 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6011 **
6012 ** This routine only works on a [BLOB handle] which has been created
6013 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6014 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6015 ** to this routine results in undefined and probably undesirable behavior.
6016 **
6017 ** See also: [sqlite3_blob_write()].
6018 */
6019 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6020
6021 /*
6022 ** CAPI3REF: Write Data Into A BLOB Incrementally
6023 **
6024 ** ^This function is used to write data into an open [BLOB handle] from a
6025 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6026 ** into the open BLOB, starting at offset iOffset.
6027 **
6028 ** ^If the [BLOB handle] passed as the first argument was not opened for
6029 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6030 ** this function returns [SQLITE_READONLY].
6031 **
6032 ** ^This function may only modify the contents of the BLOB; it is
6033 ** not possible to increase the size of a BLOB using this API.
6034 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6035 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6036 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6037 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6038 ** can be determined using the [sqlite3_blob_bytes()] interface.
6039 **
6040 ** ^An attempt to write to an expired [BLOB handle] fails with an
6041 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6042 ** before the [BLOB handle] expired are not rolled back by the
6043 ** expiration of the handle, though of course those changes might
6044 ** have been overwritten by the statement that expired the BLOB handle
6045 ** or by other independent statements.
6046 **
6047 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6048 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6049 **
6050 ** This routine only works on a [BLOB handle] which has been created
6051 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6052 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6053 ** to this routine results in undefined and probably undesirable behavior.
6054 **
6055 ** See also: [sqlite3_blob_read()].
6056 */
6057 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6058
6059 /*
6060 ** CAPI3REF: Virtual File System Objects
6061 **
6062 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6063 ** that SQLite uses to interact
6064 ** with the underlying operating system.  Most SQLite builds come with a
6065 ** single default VFS that is appropriate for the host computer.
6066 ** New VFSes can be registered and existing VFSes can be unregistered.
6067 ** The following interfaces are provided.
6068 **
6069 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6070 ** ^Names are case sensitive.
6071 ** ^Names are zero-terminated UTF-8 strings.
6072 ** ^If there is no match, a NULL pointer is returned.
6073 ** ^If zVfsName is NULL then the default VFS is returned.
6074 **
6075 ** ^New VFSes are registered with sqlite3_vfs_register().
6076 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6077 ** ^The same VFS can be registered multiple times without injury.
6078 ** ^To make an existing VFS into the default VFS, register it again
6079 ** with the makeDflt flag set.  If two different VFSes with the
6080 ** same name are registered, the behavior is undefined.  If a
6081 ** VFS is registered with a name that is NULL or an empty string,
6082 ** then the behavior is undefined.
6083 **
6084 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6085 ** ^(If the default VFS is unregistered, another VFS is chosen as
6086 ** the default.  The choice for the new VFS is arbitrary.)^
6087 */
6088 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6089 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6090 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6091
6092 /*
6093 ** CAPI3REF: Mutexes
6094 **
6095 ** The SQLite core uses these routines for thread
6096 ** synchronization. Though they are intended for internal
6097 ** use by SQLite, code that links against SQLite is
6098 ** permitted to use any of these routines.
6099 **
6100 ** The SQLite source code contains multiple implementations
6101 ** of these mutex routines.  An appropriate implementation
6102 ** is selected automatically at compile-time.  ^(The following
6103 ** implementations are available in the SQLite core:
6104 **
6105 ** <ul>
6106 ** <li>   SQLITE_MUTEX_PTHREADS
6107 ** <li>   SQLITE_MUTEX_W32
6108 ** <li>   SQLITE_MUTEX_NOOP
6109 ** </ul>)^
6110 **
6111 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6112 ** that does no real locking and is appropriate for use in
6113 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6114 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6115 ** and Windows.
6116 **
6117 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6118 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6119 ** implementation is included with the library. In this case the
6120 ** application must supply a custom mutex implementation using the
6121 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6122 ** before calling sqlite3_initialize() or any other public sqlite3_
6123 ** function that calls sqlite3_initialize().)^
6124 **
6125 ** ^The sqlite3_mutex_alloc() routine allocates a new
6126 ** mutex and returns a pointer to it. ^If it returns NULL
6127 ** that means that a mutex could not be allocated.  ^SQLite
6128 ** will unwind its stack and return an error.  ^(The argument
6129 ** to sqlite3_mutex_alloc() is one of these integer constants:
6130 **
6131 ** <ul>
6132 ** <li>  SQLITE_MUTEX_FAST
6133 ** <li>  SQLITE_MUTEX_RECURSIVE
6134 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6135 ** <li>  SQLITE_MUTEX_STATIC_MEM
6136 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6137 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6138 ** <li>  SQLITE_MUTEX_STATIC_LRU
6139 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6140 ** </ul>)^
6141 **
6142 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6143 ** cause sqlite3_mutex_alloc() to create
6144 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6145 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6146 ** The mutex implementation does not need to make a distinction
6147 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6148 ** not want to.  ^SQLite will only request a recursive mutex in
6149 ** cases where it really needs one.  ^If a faster non-recursive mutex
6150 ** implementation is available on the host platform, the mutex subsystem
6151 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6152 **
6153 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6154 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6155 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6156 ** used by the current version of SQLite.  Future versions of SQLite
6157 ** may add additional static mutexes.  Static mutexes are for internal
6158 ** use by SQLite only.  Applications that use SQLite mutexes should
6159 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6160 ** SQLITE_MUTEX_RECURSIVE.
6161 **
6162 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6163 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6164 ** returns a different mutex on every call.  ^But for the static
6165 ** mutex types, the same mutex is returned on every call that has
6166 ** the same type number.
6167 **
6168 ** ^The sqlite3_mutex_free() routine deallocates a previously
6169 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6170 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6171 ** use when they are deallocated.  Attempting to deallocate a static
6172 ** mutex results in undefined behavior.  ^SQLite never deallocates
6173 ** a static mutex.
6174 **
6175 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6176 ** to enter a mutex.  ^If another thread is already within the mutex,
6177 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6178 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6179 ** upon successful entry.  ^(Mutexes created using
6180 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6181 ** In such cases the,
6182 ** mutex must be exited an equal number of times before another thread
6183 ** can enter.)^  ^(If the same thread tries to enter any other
6184 ** kind of mutex more than once, the behavior is undefined.
6185 ** SQLite will never exhibit
6186 ** such behavior in its own use of mutexes.)^
6187 **
6188 ** ^(Some systems (for example, Windows 95) do not support the operation
6189 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6190 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6191 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6192 **
6193 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6194 ** previously entered by the same thread.   ^(The behavior
6195 ** is undefined if the mutex is not currently entered by the
6196 ** calling thread or is not currently allocated.  SQLite will
6197 ** never do either.)^
6198 **
6199 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6200 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6201 ** behave as no-ops.
6202 **
6203 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6204 */
6205 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6206 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6207 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6208 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6209 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6210
6211 /*
6212 ** CAPI3REF: Mutex Methods Object
6213 **
6214 ** An instance of this structure defines the low-level routines
6215 ** used to allocate and use mutexes.
6216 **
6217 ** Usually, the default mutex implementations provided by SQLite are
6218 ** sufficient, however the user has the option of substituting a custom
6219 ** implementation for specialized deployments or systems for which SQLite
6220 ** does not provide a suitable implementation. In this case, the user
6221 ** creates and populates an instance of this structure to pass
6222 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6223 ** Additionally, an instance of this structure can be used as an
6224 ** output variable when querying the system for the current mutex
6225 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6226 **
6227 ** ^The xMutexInit method defined by this structure is invoked as
6228 ** part of system initialization by the sqlite3_initialize() function.
6229 ** ^The xMutexInit routine is called by SQLite exactly once for each
6230 ** effective call to [sqlite3_initialize()].
6231 **
6232 ** ^The xMutexEnd method defined by this structure is invoked as
6233 ** part of system shutdown by the sqlite3_shutdown() function. The
6234 ** implementation of this method is expected to release all outstanding
6235 ** resources obtained by the mutex methods implementation, especially
6236 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6237 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6238 **
6239 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6240 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6241 ** xMutexNotheld) implement the following interfaces (respectively):
6242 **
6243 ** <ul>
6244 **   <li>  [sqlite3_mutex_alloc()] </li>
6245 **   <li>  [sqlite3_mutex_free()] </li>
6246 **   <li>  [sqlite3_mutex_enter()] </li>
6247 **   <li>  [sqlite3_mutex_try()] </li>
6248 **   <li>  [sqlite3_mutex_leave()] </li>
6249 **   <li>  [sqlite3_mutex_held()] </li>
6250 **   <li>  [sqlite3_mutex_notheld()] </li>
6251 ** </ul>)^
6252 **
6253 ** The only difference is that the public sqlite3_XXX functions enumerated
6254 ** above silently ignore any invocations that pass a NULL pointer instead
6255 ** of a valid mutex handle. The implementations of the methods defined
6256 ** by this structure are not required to handle this case, the results
6257 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6258 ** (i.e. it is acceptable to provide an implementation that segfaults if
6259 ** it is passed a NULL pointer).
6260 **
6261 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6262 ** invoke xMutexInit() multiple times within the same process and without
6263 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6264 ** xMutexInit() must be no-ops.
6265 **
6266 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6267 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6268 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6269 ** memory allocation for a fast or recursive mutex.
6270 **
6271 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6272 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6273 ** If xMutexInit fails in any way, it is expected to clean up after itself
6274 ** prior to returning.
6275 */
6276 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6277 struct sqlite3_mutex_methods {
6278   int (*xMutexInit)(void);
6279   int (*xMutexEnd)(void);
6280   sqlite3_mutex *(*xMutexAlloc)(int);
6281   void (*xMutexFree)(sqlite3_mutex *);
6282   void (*xMutexEnter)(sqlite3_mutex *);
6283   int (*xMutexTry)(sqlite3_mutex *);
6284   void (*xMutexLeave)(sqlite3_mutex *);
6285   int (*xMutexHeld)(sqlite3_mutex *);
6286   int (*xMutexNotheld)(sqlite3_mutex *);
6287 };
6288
6289 /*
6290 ** CAPI3REF: Mutex Verification Routines
6291 **
6292 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6293 ** are intended for use inside assert() statements.  ^The SQLite core
6294 ** never uses these routines except inside an assert() and applications
6295 ** are advised to follow the lead of the core.  ^The SQLite core only
6296 ** provides implementations for these routines when it is compiled
6297 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6298 ** are only required to provide these routines if SQLITE_DEBUG is
6299 ** defined and if NDEBUG is not defined.
6300 **
6301 ** ^These routines should return true if the mutex in their argument
6302 ** is held or not held, respectively, by the calling thread.
6303 **
6304 ** ^The implementation is not required to provide versions of these
6305 ** routines that actually work. If the implementation does not provide working
6306 ** versions of these routines, it should at least provide stubs that always
6307 ** return true so that one does not get spurious assertion failures.
6308 **
6309 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6310 ** the routine should return 1.   This seems counter-intuitive since
6311 ** clearly the mutex cannot be held if it does not exist.  But
6312 ** the reason the mutex does not exist is because the build is not
6313 ** using mutexes.  And we do not want the assert() containing the
6314 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6315 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6316 ** interface should also return 1 when given a NULL pointer.
6317 */
6318 #ifndef NDEBUG
6319 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6320 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6321 #endif
6322
6323 /*
6324 ** CAPI3REF: Mutex Types
6325 **
6326 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6327 ** which is one of these integer constants.
6328 **
6329 ** The set of static mutexes may change from one SQLite release to the
6330 ** next.  Applications that override the built-in mutex logic must be
6331 ** prepared to accommodate additional static mutexes.
6332 */
6333 #define SQLITE_MUTEX_FAST             0
6334 #define SQLITE_MUTEX_RECURSIVE        1
6335 #define SQLITE_MUTEX_STATIC_MASTER    2
6336 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6337 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6338 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6339 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6340 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6341 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6342 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6343
6344 /*
6345 ** CAPI3REF: Retrieve the mutex for a database connection
6346 **
6347 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6348 ** serializes access to the [database connection] given in the argument
6349 ** when the [threading mode] is Serialized.
6350 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6351 ** routine returns a NULL pointer.
6352 */
6353 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6354
6355 /*
6356 ** CAPI3REF: Low-Level Control Of Database Files
6357 **
6358 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6359 ** xFileControl method for the [sqlite3_io_methods] object associated
6360 ** with a particular database identified by the second argument. ^The
6361 ** name of the database is "main" for the main database or "temp" for the
6362 ** TEMP database, or the name that appears after the AS keyword for
6363 ** databases that are added using the [ATTACH] SQL command.
6364 ** ^A NULL pointer can be used in place of "main" to refer to the
6365 ** main database file.
6366 ** ^The third and fourth parameters to this routine
6367 ** are passed directly through to the second and third parameters of
6368 ** the xFileControl method.  ^The return value of the xFileControl
6369 ** method becomes the return value of this routine.
6370 **
6371 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6372 ** a pointer to the underlying [sqlite3_file] object to be written into
6373 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6374 ** case is a short-circuit path which does not actually invoke the
6375 ** underlying sqlite3_io_methods.xFileControl method.
6376 **
6377 ** ^If the second parameter (zDbName) does not match the name of any
6378 ** open database file, then SQLITE_ERROR is returned.  ^This error
6379 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6380 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6381 ** also return SQLITE_ERROR.  There is no way to distinguish between
6382 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6383 ** xFileControl method.
6384 **
6385 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6386 */
6387 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6388
6389 /*
6390 ** CAPI3REF: Testing Interface
6391 **
6392 ** ^The sqlite3_test_control() interface is used to read out internal
6393 ** state of SQLite and to inject faults into SQLite for testing
6394 ** purposes.  ^The first parameter is an operation code that determines
6395 ** the number, meaning, and operation of all subsequent parameters.
6396 **
6397 ** This interface is not for use by applications.  It exists solely
6398 ** for verifying the correct operation of the SQLite library.  Depending
6399 ** on how the SQLite library is compiled, this interface might not exist.
6400 **
6401 ** The details of the operation codes, their meanings, the parameters
6402 ** they take, and what they do are all subject to change without notice.
6403 ** Unlike most of the SQLite API, this function is not guaranteed to
6404 ** operate consistently from one release to the next.
6405 */
6406 SQLITE_API int sqlite3_test_control(int op, ...);
6407
6408 /*
6409 ** CAPI3REF: Testing Interface Operation Codes
6410 **
6411 ** These constants are the valid operation code parameters used
6412 ** as the first argument to [sqlite3_test_control()].
6413 **
6414 ** These parameters and their meanings are subject to change
6415 ** without notice.  These values are for testing purposes only.
6416 ** Applications should not use any of these parameters or the
6417 ** [sqlite3_test_control()] interface.
6418 */
6419 #define SQLITE_TESTCTRL_FIRST                    5
6420 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6421 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6422 #define SQLITE_TESTCTRL_PRNG_RESET               7
6423 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6424 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6425 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6426 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6427 #define SQLITE_TESTCTRL_ASSERT                  12
6428 #define SQLITE_TESTCTRL_ALWAYS                  13
6429 #define SQLITE_TESTCTRL_RESERVE                 14
6430 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6431 #define SQLITE_TESTCTRL_ISKEYWORD               16
6432 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6433 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6434 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6435 #define SQLITE_TESTCTRL_LAST                    19
6436
6437 /*
6438 ** CAPI3REF: SQLite Runtime Status
6439 **
6440 ** ^This interface is used to retrieve runtime status information
6441 ** about the performance of SQLite, and optionally to reset various
6442 ** highwater marks.  ^The first argument is an integer code for
6443 ** the specific parameter to measure.  ^(Recognized integer codes
6444 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6445 ** ^The current value of the parameter is returned into *pCurrent.
6446 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6447 ** resetFlag is true, then the highest record value is reset after
6448 ** *pHighwater is written.  ^(Some parameters do not record the highest
6449 ** value.  For those parameters
6450 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6451 ** ^(Other parameters record only the highwater mark and not the current
6452 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6453 **
6454 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6455 ** non-zero [error code] on failure.
6456 **
6457 ** This routine is threadsafe but is not atomic.  This routine can be
6458 ** called while other threads are running the same or different SQLite
6459 ** interfaces.  However the values returned in *pCurrent and
6460 ** *pHighwater reflect the status of SQLite at different points in time
6461 ** and it is possible that another thread might change the parameter
6462 ** in between the times when *pCurrent and *pHighwater are written.
6463 **
6464 ** See also: [sqlite3_db_status()]
6465 */
6466 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6467
6468
6469 /*
6470 ** CAPI3REF: Status Parameters
6471 ** KEYWORDS: {status parameters}
6472 **
6473 ** These integer constants designate various run-time status parameters
6474 ** that can be returned by [sqlite3_status()].
6475 **
6476 ** <dl>
6477 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6478 ** <dd>This parameter is the current amount of memory checked out
6479 ** using [sqlite3_malloc()], either directly or indirectly.  The
6480 ** figure includes calls made to [sqlite3_malloc()] by the application
6481 ** and internal memory usage by the SQLite library.  Scratch memory
6482 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6483 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6484 ** this parameter.  The amount returned is the sum of the allocation
6485 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6486 **
6487 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6488 ** <dd>This parameter records the largest memory allocation request
6489 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6490 ** internal equivalents).  Only the value returned in the
6491 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6492 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6493 **
6494 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6495 ** <dd>This parameter records the number of separate memory allocations
6496 ** currently checked out.</dd>)^
6497 **
6498 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6499 ** <dd>This parameter returns the number of pages used out of the
6500 ** [pagecache memory allocator] that was configured using 
6501 ** [SQLITE_CONFIG_PAGECACHE].  The
6502 ** value returned is in pages, not in bytes.</dd>)^
6503 **
6504 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6505 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6506 ** <dd>This parameter returns the number of bytes of page cache
6507 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6508 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6509 ** returned value includes allocations that overflowed because they
6510 ** where too large (they were larger than the "sz" parameter to
6511 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6512 ** no space was left in the page cache.</dd>)^
6513 **
6514 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6515 ** <dd>This parameter records the largest memory allocation request
6516 ** handed to [pagecache memory allocator].  Only the value returned in the
6517 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6518 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6519 **
6520 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6521 ** <dd>This parameter returns the number of allocations used out of the
6522 ** [scratch memory allocator] configured using
6523 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6524 ** in bytes.  Since a single thread may only have one scratch allocation
6525 ** outstanding at time, this parameter also reports the number of threads
6526 ** using scratch memory at the same time.</dd>)^
6527 **
6528 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6529 ** <dd>This parameter returns the number of bytes of scratch memory
6530 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6531 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6532 ** returned include overflows because the requested allocation was too
6533 ** larger (that is, because the requested allocation was larger than the
6534 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6535 ** slots were available.
6536 ** </dd>)^
6537 **
6538 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6539 ** <dd>This parameter records the largest memory allocation request
6540 ** handed to [scratch memory allocator].  Only the value returned in the
6541 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6542 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6543 **
6544 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6545 ** <dd>This parameter records the deepest parser stack.  It is only
6546 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6547 ** </dl>
6548 **
6549 ** New status parameters may be added from time to time.
6550 */
6551 #define SQLITE_STATUS_MEMORY_USED          0
6552 #define SQLITE_STATUS_PAGECACHE_USED       1
6553 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6554 #define SQLITE_STATUS_SCRATCH_USED         3
6555 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6556 #define SQLITE_STATUS_MALLOC_SIZE          5
6557 #define SQLITE_STATUS_PARSER_STACK         6
6558 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6559 #define SQLITE_STATUS_SCRATCH_SIZE         8
6560 #define SQLITE_STATUS_MALLOC_COUNT         9
6561
6562 /*
6563 ** CAPI3REF: Database Connection Status
6564 **
6565 ** ^This interface is used to retrieve runtime status information 
6566 ** about a single [database connection].  ^The first argument is the
6567 ** database connection object to be interrogated.  ^The second argument
6568 ** is an integer constant, taken from the set of
6569 ** [SQLITE_DBSTATUS options], that
6570 ** determines the parameter to interrogate.  The set of 
6571 ** [SQLITE_DBSTATUS options] is likely
6572 ** to grow in future releases of SQLite.
6573 **
6574 ** ^The current value of the requested parameter is written into *pCur
6575 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6576 ** the resetFlg is true, then the highest instantaneous value is
6577 ** reset back down to the current value.
6578 **
6579 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6580 ** non-zero [error code] on failure.
6581 **
6582 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6583 */
6584 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6585
6586 /*
6587 ** CAPI3REF: Status Parameters for database connections
6588 ** KEYWORDS: {SQLITE_DBSTATUS options}
6589 **
6590 ** These constants are the available integer "verbs" that can be passed as
6591 ** the second argument to the [sqlite3_db_status()] interface.
6592 **
6593 ** New verbs may be added in future releases of SQLite. Existing verbs
6594 ** might be discontinued. Applications should check the return code from
6595 ** [sqlite3_db_status()] to make sure that the call worked.
6596 ** The [sqlite3_db_status()] interface will return a non-zero error code
6597 ** if a discontinued or unsupported verb is invoked.
6598 **
6599 ** <dl>
6600 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6601 ** <dd>This parameter returns the number of lookaside memory slots currently
6602 ** checked out.</dd>)^
6603 **
6604 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6605 ** <dd>This parameter returns the number malloc attempts that were 
6606 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6607 ** the current value is always zero.)^
6608 **
6609 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6610 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6611 ** <dd>This parameter returns the number malloc attempts that might have
6612 ** been satisfied using lookaside memory but failed due to the amount of
6613 ** memory requested being larger than the lookaside slot size.
6614 ** Only the high-water value is meaningful;
6615 ** the current value is always zero.)^
6616 **
6617 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6618 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6619 ** <dd>This parameter returns the number malloc attempts that might have
6620 ** been satisfied using lookaside memory but failed due to all lookaside
6621 ** memory already being in use.
6622 ** Only the high-water value is meaningful;
6623 ** the current value is always zero.)^
6624 **
6625 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6626 ** <dd>This parameter returns the approximate number of of bytes of heap
6627 ** memory used by all pager caches associated with the database connection.)^
6628 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6629 **
6630 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6631 ** <dd>This parameter returns the approximate number of of bytes of heap
6632 ** memory used to store the schema for all databases associated
6633 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6634 ** ^The full amount of memory used by the schemas is reported, even if the
6635 ** schema memory is shared with other database connections due to
6636 ** [shared cache mode] being enabled.
6637 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6638 **
6639 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6640 ** <dd>This parameter returns the approximate number of of bytes of heap
6641 ** and lookaside memory used by all prepared statements associated with
6642 ** the database connection.)^
6643 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6644 ** </dd>
6645 **
6646 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6647 ** <dd>This parameter returns the number of pager cache hits that have
6648 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
6649 ** is always 0.
6650 ** </dd>
6651 **
6652 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6653 ** <dd>This parameter returns the number of pager cache misses that have
6654 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
6655 ** is always 0.
6656 ** </dd>
6657 **
6658 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6659 ** <dd>This parameter returns the number of dirty cache entries that have
6660 ** been written to disk. Specifically, the number of pages written to the
6661 ** wal file in wal mode databases, or the number of pages written to the
6662 ** database file in rollback mode databases. Any pages written as part of
6663 ** transaction rollback or database recovery operations are not included.
6664 ** If an IO or other error occurs while writing a page to disk, the effect
6665 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6666 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6667 ** </dd>
6668 ** </dl>
6669 */
6670 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6671 #define SQLITE_DBSTATUS_CACHE_USED           1
6672 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6673 #define SQLITE_DBSTATUS_STMT_USED            3
6674 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6675 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6676 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6677 #define SQLITE_DBSTATUS_CACHE_HIT            7
6678 #define SQLITE_DBSTATUS_CACHE_MISS           8
6679 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6680 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6681
6682
6683 /*
6684 ** CAPI3REF: Prepared Statement Status
6685 **
6686 ** ^(Each prepared statement maintains various
6687 ** [SQLITE_STMTSTATUS counters] that measure the number
6688 ** of times it has performed specific operations.)^  These counters can
6689 ** be used to monitor the performance characteristics of the prepared
6690 ** statements.  For example, if the number of table steps greatly exceeds
6691 ** the number of table searches or result rows, that would tend to indicate
6692 ** that the prepared statement is using a full table scan rather than
6693 ** an index.  
6694 **
6695 ** ^(This interface is used to retrieve and reset counter values from
6696 ** a [prepared statement].  The first argument is the prepared statement
6697 ** object to be interrogated.  The second argument
6698 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6699 ** to be interrogated.)^
6700 ** ^The current value of the requested counter is returned.
6701 ** ^If the resetFlg is true, then the counter is reset to zero after this
6702 ** interface call returns.
6703 **
6704 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6705 */
6706 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6707
6708 /*
6709 ** CAPI3REF: Status Parameters for prepared statements
6710 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6711 **
6712 ** These preprocessor macros define integer codes that name counter
6713 ** values associated with the [sqlite3_stmt_status()] interface.
6714 ** The meanings of the various counters are as follows:
6715 **
6716 ** <dl>
6717 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6718 ** <dd>^This is the number of times that SQLite has stepped forward in
6719 ** a table as part of a full table scan.  Large numbers for this counter
6720 ** may indicate opportunities for performance improvement through 
6721 ** careful use of indices.</dd>
6722 **
6723 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6724 ** <dd>^This is the number of sort operations that have occurred.
6725 ** A non-zero value in this counter may indicate an opportunity to
6726 ** improvement performance through careful use of indices.</dd>
6727 **
6728 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6729 ** <dd>^This is the number of rows inserted into transient indices that
6730 ** were created automatically in order to help joins run faster.
6731 ** A non-zero value in this counter may indicate an opportunity to
6732 ** improvement performance by adding permanent indices that do not
6733 ** need to be reinitialized each time the statement is run.</dd>
6734 ** </dl>
6735 */
6736 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6737 #define SQLITE_STMTSTATUS_SORT              2
6738 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6739
6740 /*
6741 ** CAPI3REF: Custom Page Cache Object
6742 **
6743 ** The sqlite3_pcache type is opaque.  It is implemented by
6744 ** the pluggable module.  The SQLite core has no knowledge of
6745 ** its size or internal structure and never deals with the
6746 ** sqlite3_pcache object except by holding and passing pointers
6747 ** to the object.
6748 **
6749 ** See [sqlite3_pcache_methods2] for additional information.
6750 */
6751 typedef struct sqlite3_pcache sqlite3_pcache;
6752
6753 /*
6754 ** CAPI3REF: Custom Page Cache Object
6755 **
6756 ** The sqlite3_pcache_page object represents a single page in the
6757 ** page cache.  The page cache will allocate instances of this
6758 ** object.  Various methods of the page cache use pointers to instances
6759 ** of this object as parameters or as their return value.
6760 **
6761 ** See [sqlite3_pcache_methods2] for additional information.
6762 */
6763 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6764 struct sqlite3_pcache_page {
6765   void *pBuf;        /* The content of the page */
6766   void *pExtra;      /* Extra information associated with the page */
6767 };
6768
6769 /*
6770 ** CAPI3REF: Application Defined Page Cache.
6771 ** KEYWORDS: {page cache}
6772 **
6773 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6774 ** register an alternative page cache implementation by passing in an 
6775 ** instance of the sqlite3_pcache_methods2 structure.)^
6776 ** In many applications, most of the heap memory allocated by 
6777 ** SQLite is used for the page cache.
6778 ** By implementing a 
6779 ** custom page cache using this API, an application can better control
6780 ** the amount of memory consumed by SQLite, the way in which 
6781 ** that memory is allocated and released, and the policies used to 
6782 ** determine exactly which parts of a database file are cached and for 
6783 ** how long.
6784 **
6785 ** The alternative page cache mechanism is an
6786 ** extreme measure that is only needed by the most demanding applications.
6787 ** The built-in page cache is recommended for most uses.
6788 **
6789 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6790 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6791 ** the application may discard the parameter after the call to
6792 ** [sqlite3_config()] returns.)^
6793 **
6794 ** [[the xInit() page cache method]]
6795 ** ^(The xInit() method is called once for each effective 
6796 ** call to [sqlite3_initialize()])^
6797 ** (usually only once during the lifetime of the process). ^(The xInit()
6798 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6799 ** The intent of the xInit() method is to set up global data structures 
6800 ** required by the custom page cache implementation. 
6801 ** ^(If the xInit() method is NULL, then the 
6802 ** built-in default page cache is used instead of the application defined
6803 ** page cache.)^
6804 **
6805 ** [[the xShutdown() page cache method]]
6806 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6807 ** It can be used to clean up 
6808 ** any outstanding resources before process shutdown, if required.
6809 ** ^The xShutdown() method may be NULL.
6810 **
6811 ** ^SQLite automatically serializes calls to the xInit method,
6812 ** so the xInit method need not be threadsafe.  ^The
6813 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6814 ** not need to be threadsafe either.  All other methods must be threadsafe
6815 ** in multithreaded applications.
6816 **
6817 ** ^SQLite will never invoke xInit() more than once without an intervening
6818 ** call to xShutdown().
6819 **
6820 ** [[the xCreate() page cache methods]]
6821 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6822 ** SQLite will typically create one cache instance for each open database file,
6823 ** though this is not guaranteed. ^The
6824 ** first parameter, szPage, is the size in bytes of the pages that must
6825 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6826 ** second parameter szExtra is a number of bytes of extra storage 
6827 ** associated with each page cache entry.  ^The szExtra parameter will
6828 ** a number less than 250.  SQLite will use the
6829 ** extra szExtra bytes on each page to store metadata about the underlying
6830 ** database page on disk.  The value passed into szExtra depends
6831 ** on the SQLite version, the target platform, and how SQLite was compiled.
6832 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6833 ** created will be used to cache database pages of a file stored on disk, or
6834 ** false if it is used for an in-memory database. The cache implementation
6835 ** does not have to do anything special based with the value of bPurgeable;
6836 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6837 ** never invoke xUnpin() except to deliberately delete a page.
6838 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6839 ** false will always have the "discard" flag set to true.  
6840 ** ^Hence, a cache created with bPurgeable false will
6841 ** never contain any unpinned pages.
6842 **
6843 ** [[the xCachesize() page cache method]]
6844 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6845 ** suggested maximum cache-size (number of pages stored by) the cache
6846 ** instance passed as the first argument. This is the value configured using
6847 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6848 ** parameter, the implementation is not required to do anything with this
6849 ** value; it is advisory only.
6850 **
6851 ** [[the xPagecount() page cache methods]]
6852 ** The xPagecount() method must return the number of pages currently
6853 ** stored in the cache, both pinned and unpinned.
6854 ** 
6855 ** [[the xFetch() page cache methods]]
6856 ** The xFetch() method locates a page in the cache and returns a pointer to 
6857 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6858 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6859 ** pointer to a buffer of szPage bytes used to store the content of a 
6860 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6861 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6862 ** for each entry in the page cache.
6863 **
6864 ** The page to be fetched is determined by the key. ^The minimum key value
6865 ** is 1.  After it has been retrieved using xFetch, the page is considered
6866 ** to be "pinned".
6867 **
6868 ** If the requested page is already in the page cache, then the page cache
6869 ** implementation must return a pointer to the page buffer with its content
6870 ** intact.  If the requested page is not already in the cache, then the
6871 ** cache implementation should use the value of the createFlag
6872 ** parameter to help it determined what action to take:
6873 **
6874 ** <table border=1 width=85% align=center>
6875 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6876 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6877 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6878 **                 Otherwise return NULL.
6879 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6880 **                 NULL if allocating a new page is effectively impossible.
6881 ** </table>
6882 **
6883 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6884 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6885 ** failed.)^  In between the to xFetch() calls, SQLite may
6886 ** attempt to unpin one or more cache pages by spilling the content of
6887 ** pinned pages to disk and synching the operating system disk cache.
6888 **
6889 ** [[the xUnpin() page cache method]]
6890 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6891 ** as its second argument.  If the third parameter, discard, is non-zero,
6892 ** then the page must be evicted from the cache.
6893 ** ^If the discard parameter is
6894 ** zero, then the page may be discarded or retained at the discretion of
6895 ** page cache implementation. ^The page cache implementation
6896 ** may choose to evict unpinned pages at any time.
6897 **
6898 ** The cache must not perform any reference counting. A single 
6899 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6900 ** to xFetch().
6901 **
6902 ** [[the xRekey() page cache methods]]
6903 ** The xRekey() method is used to change the key value associated with the
6904 ** page passed as the second argument. If the cache
6905 ** previously contains an entry associated with newKey, it must be
6906 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6907 ** to be pinned.
6908 **
6909 ** When SQLite calls the xTruncate() method, the cache must discard all
6910 ** existing cache entries with page numbers (keys) greater than or equal
6911 ** to the value of the iLimit parameter passed to xTruncate(). If any
6912 ** of these pages are pinned, they are implicitly unpinned, meaning that
6913 ** they can be safely discarded.
6914 **
6915 ** [[the xDestroy() page cache method]]
6916 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6917 ** All resources associated with the specified cache should be freed. ^After
6918 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6919 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6920 ** functions.
6921 **
6922 ** [[the xShrink() page cache method]]
6923 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6924 ** free up as much of heap memory as possible.  The page cache implementation
6925 ** is not obligated to free any memory, but well-behaved implementations should
6926 ** do their best.
6927 */
6928 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6929 struct sqlite3_pcache_methods2 {
6930   int iVersion;
6931   void *pArg;
6932   int (*xInit)(void*);
6933   void (*xShutdown)(void*);
6934   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6935   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6936   int (*xPagecount)(sqlite3_pcache*);
6937   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6938   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6939   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
6940       unsigned oldKey, unsigned newKey);
6941   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6942   void (*xDestroy)(sqlite3_pcache*);
6943   void (*xShrink)(sqlite3_pcache*);
6944 };
6945
6946 /*
6947 ** This is the obsolete pcache_methods object that has now been replaced
6948 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6949 ** retained in the header file for backwards compatibility only.
6950 */
6951 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6952 struct sqlite3_pcache_methods {
6953   void *pArg;
6954   int (*xInit)(void*);
6955   void (*xShutdown)(void*);
6956   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6957   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6958   int (*xPagecount)(sqlite3_pcache*);
6959   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6960   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6961   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6962   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6963   void (*xDestroy)(sqlite3_pcache*);
6964 };
6965
6966
6967 /*
6968 ** CAPI3REF: Online Backup Object
6969 **
6970 ** The sqlite3_backup object records state information about an ongoing
6971 ** online backup operation.  ^The sqlite3_backup object is created by
6972 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6973 ** [sqlite3_backup_finish()].
6974 **
6975 ** See Also: [Using the SQLite Online Backup API]
6976 */
6977 typedef struct sqlite3_backup sqlite3_backup;
6978
6979 /*
6980 ** CAPI3REF: Online Backup API.
6981 **
6982 ** The backup API copies the content of one database into another.
6983 ** It is useful either for creating backups of databases or
6984 ** for copying in-memory databases to or from persistent files. 
6985 **
6986 ** See Also: [Using the SQLite Online Backup API]
6987 **
6988 ** ^SQLite holds a write transaction open on the destination database file
6989 ** for the duration of the backup operation.
6990 ** ^The source database is read-locked only while it is being read;
6991 ** it is not locked continuously for the entire backup operation.
6992 ** ^Thus, the backup may be performed on a live source database without
6993 ** preventing other database connections from
6994 ** reading or writing to the source database while the backup is underway.
6995 ** 
6996 ** ^(To perform a backup operation: 
6997 **   <ol>
6998 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6999 **         backup, 
7000 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
7001 **         the data between the two databases, and finally
7002 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
7003 **         associated with the backup operation. 
7004 **   </ol>)^
7005 ** There should be exactly one call to sqlite3_backup_finish() for each
7006 ** successful call to sqlite3_backup_init().
7007 **
7008 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7009 **
7010 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
7011 ** [database connection] associated with the destination database 
7012 ** and the database name, respectively.
7013 ** ^The database name is "main" for the main database, "temp" for the
7014 ** temporary database, or the name specified after the AS keyword in
7015 ** an [ATTACH] statement for an attached database.
7016 ** ^The S and M arguments passed to 
7017 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7018 ** and database name of the source database, respectively.
7019 ** ^The source and destination [database connections] (parameters S and D)
7020 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7021 ** an error.
7022 **
7023 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7024 ** returned and an error code and error message are stored in the
7025 ** destination [database connection] D.
7026 ** ^The error code and message for the failed call to sqlite3_backup_init()
7027 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7028 ** [sqlite3_errmsg16()] functions.
7029 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7030 ** [sqlite3_backup] object.
7031 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7032 ** sqlite3_backup_finish() functions to perform the specified backup 
7033 ** operation.
7034 **
7035 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7036 **
7037 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
7038 ** the source and destination databases specified by [sqlite3_backup] object B.
7039 ** ^If N is negative, all remaining source pages are copied. 
7040 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7041 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7042 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7043 ** from source to destination, then it returns [SQLITE_DONE].
7044 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7045 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7046 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7047 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7048 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7049 **
7050 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7051 ** <ol>
7052 ** <li> the destination database was opened read-only, or
7053 ** <li> the destination database is using write-ahead-log journaling
7054 ** and the destination and source page sizes differ, or
7055 ** <li> the destination database is an in-memory database and the
7056 ** destination and source page sizes differ.
7057 ** </ol>)^
7058 **
7059 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7060 ** the [sqlite3_busy_handler | busy-handler function]
7061 ** is invoked (if one is specified). ^If the 
7062 ** busy-handler returns non-zero before the lock is available, then 
7063 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7064 ** sqlite3_backup_step() can be retried later. ^If the source
7065 ** [database connection]
7066 ** is being used to write to the source database when sqlite3_backup_step()
7067 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7068 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7069 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7070 ** [SQLITE_READONLY] is returned, then 
7071 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7072 ** errors are considered fatal.)^  The application must accept 
7073 ** that the backup operation has failed and pass the backup operation handle 
7074 ** to the sqlite3_backup_finish() to release associated resources.
7075 **
7076 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7077 ** on the destination file. ^The exclusive lock is not released until either 
7078 ** sqlite3_backup_finish() is called or the backup operation is complete 
7079 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7080 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7081 ** lasts for the duration of the sqlite3_backup_step() call.
7082 ** ^Because the source database is not locked between calls to
7083 ** sqlite3_backup_step(), the source database may be modified mid-way
7084 ** through the backup process.  ^If the source database is modified by an
7085 ** external process or via a database connection other than the one being
7086 ** used by the backup operation, then the backup will be automatically
7087 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
7088 ** database is modified by the using the same database connection as is used
7089 ** by the backup operation, then the backup database is automatically
7090 ** updated at the same time.
7091 **
7092 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7093 **
7094 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7095 ** application wishes to abandon the backup operation, the application
7096 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7097 ** ^The sqlite3_backup_finish() interfaces releases all
7098 ** resources associated with the [sqlite3_backup] object. 
7099 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7100 ** active write-transaction on the destination database is rolled back.
7101 ** The [sqlite3_backup] object is invalid
7102 ** and may not be used following a call to sqlite3_backup_finish().
7103 **
7104 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7105 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7106 ** sqlite3_backup_step() completed.
7107 ** ^If an out-of-memory condition or IO error occurred during any prior
7108 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7109 ** sqlite3_backup_finish() returns the corresponding [error code].
7110 **
7111 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7112 ** is not a permanent error and does not affect the return value of
7113 ** sqlite3_backup_finish().
7114 **
7115 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7116 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7117 **
7118 ** ^Each call to sqlite3_backup_step() sets two values inside
7119 ** the [sqlite3_backup] object: the number of pages still to be backed
7120 ** up and the total number of pages in the source database file.
7121 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7122 ** retrieve these two values, respectively.
7123 **
7124 ** ^The values returned by these functions are only updated by
7125 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7126 ** operation, then the values are not updated to account for any extra
7127 ** pages that need to be updated or the size of the source database file
7128 ** changing.
7129 **
7130 ** <b>Concurrent Usage of Database Handles</b>
7131 **
7132 ** ^The source [database connection] may be used by the application for other
7133 ** purposes while a backup operation is underway or being initialized.
7134 ** ^If SQLite is compiled and configured to support threadsafe database
7135 ** connections, then the source database connection may be used concurrently
7136 ** from within other threads.
7137 **
7138 ** However, the application must guarantee that the destination 
7139 ** [database connection] is not passed to any other API (by any thread) after 
7140 ** sqlite3_backup_init() is called and before the corresponding call to
7141 ** sqlite3_backup_finish().  SQLite does not currently check to see
7142 ** if the application incorrectly accesses the destination [database connection]
7143 ** and so no error code is reported, but the operations may malfunction
7144 ** nevertheless.  Use of the destination database connection while a
7145 ** backup is in progress might also also cause a mutex deadlock.
7146 **
7147 ** If running in [shared cache mode], the application must
7148 ** guarantee that the shared cache used by the destination database
7149 ** is not accessed while the backup is running. In practice this means
7150 ** that the application must guarantee that the disk file being 
7151 ** backed up to is not accessed by any connection within the process,
7152 ** not just the specific connection that was passed to sqlite3_backup_init().
7153 **
7154 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7155 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7156 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7157 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7158 ** same time as another thread is invoking sqlite3_backup_step() it is
7159 ** possible that they return invalid values.
7160 */
7161 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7162   sqlite3 *pDest,                        /* Destination database handle */
7163   const char *zDestName,                 /* Destination database name */
7164   sqlite3 *pSource,                      /* Source database handle */
7165   const char *zSourceName                /* Source database name */
7166 );
7167 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7168 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7169 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7170 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7171
7172 /*
7173 ** CAPI3REF: Unlock Notification
7174 **
7175 ** ^When running in shared-cache mode, a database operation may fail with
7176 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7177 ** individual tables within the shared-cache cannot be obtained. See
7178 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
7179 ** ^This API may be used to register a callback that SQLite will invoke 
7180 ** when the connection currently holding the required lock relinquishes it.
7181 ** ^This API is only available if the library was compiled with the
7182 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7183 **
7184 ** See Also: [Using the SQLite Unlock Notification Feature].
7185 **
7186 ** ^Shared-cache locks are released when a database connection concludes
7187 ** its current transaction, either by committing it or rolling it back. 
7188 **
7189 ** ^When a connection (known as the blocked connection) fails to obtain a
7190 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7191 ** identity of the database connection (the blocking connection) that
7192 ** has locked the required resource is stored internally. ^After an 
7193 ** application receives an SQLITE_LOCKED error, it may call the
7194 ** sqlite3_unlock_notify() method with the blocked connection handle as 
7195 ** the first argument to register for a callback that will be invoked
7196 ** when the blocking connections current transaction is concluded. ^The
7197 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7198 ** call that concludes the blocking connections transaction.
7199 **
7200 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7201 ** there is a chance that the blocking connection will have already
7202 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7203 ** If this happens, then the specified callback is invoked immediately,
7204 ** from within the call to sqlite3_unlock_notify().)^
7205 **
7206 ** ^If the blocked connection is attempting to obtain a write-lock on a
7207 ** shared-cache table, and more than one other connection currently holds
7208 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
7209 ** the other connections to use as the blocking connection.
7210 **
7211 ** ^(There may be at most one unlock-notify callback registered by a 
7212 ** blocked connection. If sqlite3_unlock_notify() is called when the
7213 ** blocked connection already has a registered unlock-notify callback,
7214 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7215 ** called with a NULL pointer as its second argument, then any existing
7216 ** unlock-notify callback is canceled. ^The blocked connections 
7217 ** unlock-notify callback may also be canceled by closing the blocked
7218 ** connection using [sqlite3_close()].
7219 **
7220 ** The unlock-notify callback is not reentrant. If an application invokes
7221 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7222 ** crash or deadlock may be the result.
7223 **
7224 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7225 ** returns SQLITE_OK.
7226 **
7227 ** <b>Callback Invocation Details</b>
7228 **
7229 ** When an unlock-notify callback is registered, the application provides a 
7230 ** single void* pointer that is passed to the callback when it is invoked.
7231 ** However, the signature of the callback function allows SQLite to pass
7232 ** it an array of void* context pointers. The first argument passed to
7233 ** an unlock-notify callback is a pointer to an array of void* pointers,
7234 ** and the second is the number of entries in the array.
7235 **
7236 ** When a blocking connections transaction is concluded, there may be
7237 ** more than one blocked connection that has registered for an unlock-notify
7238 ** callback. ^If two or more such blocked connections have specified the
7239 ** same callback function, then instead of invoking the callback function
7240 ** multiple times, it is invoked once with the set of void* context pointers
7241 ** specified by the blocked connections bundled together into an array.
7242 ** This gives the application an opportunity to prioritize any actions 
7243 ** related to the set of unblocked database connections.
7244 **
7245 ** <b>Deadlock Detection</b>
7246 **
7247 ** Assuming that after registering for an unlock-notify callback a 
7248 ** database waits for the callback to be issued before taking any further
7249 ** action (a reasonable assumption), then using this API may cause the
7250 ** application to deadlock. For example, if connection X is waiting for
7251 ** connection Y's transaction to be concluded, and similarly connection
7252 ** Y is waiting on connection X's transaction, then neither connection
7253 ** will proceed and the system may remain deadlocked indefinitely.
7254 **
7255 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7256 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7257 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7258 ** unlock-notify callback is registered. The system is said to be in
7259 ** a deadlocked state if connection A has registered for an unlock-notify
7260 ** callback on the conclusion of connection B's transaction, and connection
7261 ** B has itself registered for an unlock-notify callback when connection
7262 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7263 ** the system is also considered to be deadlocked if connection B has
7264 ** registered for an unlock-notify callback on the conclusion of connection
7265 ** C's transaction, where connection C is waiting on connection A. ^Any
7266 ** number of levels of indirection are allowed.
7267 **
7268 ** <b>The "DROP TABLE" Exception</b>
7269 **
7270 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
7271 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7272 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7273 ** SQLite checks if there are any currently executing SELECT statements
7274 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7275 ** returned. In this case there is no "blocking connection", so invoking
7276 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7277 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7278 ** or "DROP INDEX" query, an infinite loop might be the result.
7279 **
7280 ** One way around this problem is to check the extended error code returned
7281 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7282 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7283 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
7284 ** SQLITE_LOCKED.)^
7285 */
7286 SQLITE_API int sqlite3_unlock_notify(
7287   sqlite3 *pBlocked,                          /* Waiting connection */
7288   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7289   void *pNotifyArg                            /* Argument to pass to xNotify */
7290 );
7291
7292
7293 /*
7294 ** CAPI3REF: String Comparison
7295 **
7296 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7297 ** and extensions to compare the contents of two buffers containing UTF-8
7298 ** strings in a case-independent fashion, using the same definition of "case
7299 ** independence" that SQLite uses internally when comparing identifiers.
7300 */
7301 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7302 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7303
7304 /*
7305 ** CAPI3REF: Error Logging Interface
7306 **
7307 ** ^The [sqlite3_log()] interface writes a message into the error log
7308 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7309 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7310 ** used with [sqlite3_snprintf()] to generate the final output string.
7311 **
7312 ** The sqlite3_log() interface is intended for use by extensions such as
7313 ** virtual tables, collating functions, and SQL functions.  While there is
7314 ** nothing to prevent an application from calling sqlite3_log(), doing so
7315 ** is considered bad form.
7316 **
7317 ** The zFormat string must not be NULL.
7318 **
7319 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7320 ** will not use dynamically allocated memory.  The log message is stored in
7321 ** a fixed-length buffer on the stack.  If the log message is longer than
7322 ** a few hundred characters, it will be truncated to the length of the
7323 ** buffer.
7324 */
7325 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7326
7327 /*
7328 ** CAPI3REF: Write-Ahead Log Commit Hook
7329 **
7330 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7331 ** will be invoked each time a database connection commits data to a
7332 ** [write-ahead log] (i.e. whenever a transaction is committed in
7333 ** [journal_mode | journal_mode=WAL mode]). 
7334 **
7335 ** ^The callback is invoked by SQLite after the commit has taken place and 
7336 ** the associated write-lock on the database released, so the implementation 
7337 ** may read, write or [checkpoint] the database as required.
7338 **
7339 ** ^The first parameter passed to the callback function when it is invoked
7340 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7341 ** registering the callback. ^The second is a copy of the database handle.
7342 ** ^The third parameter is the name of the database that was written to -
7343 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7344 ** is the number of pages currently in the write-ahead log file,
7345 ** including those that were just committed.
7346 **
7347 ** The callback function should normally return [SQLITE_OK].  ^If an error
7348 ** code is returned, that error will propagate back up through the
7349 ** SQLite code base to cause the statement that provoked the callback
7350 ** to report an error, though the commit will have still occurred. If the
7351 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7352 ** that does not correspond to any valid SQLite error code, the results
7353 ** are undefined.
7354 **
7355 ** A single database handle may have at most a single write-ahead log callback 
7356 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7357 ** previously registered write-ahead log callback. ^Note that the
7358 ** [sqlite3_wal_autocheckpoint()] interface and the
7359 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7360 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7361 */
7362 SQLITE_API void *sqlite3_wal_hook(
7363   sqlite3*, 
7364   int(*)(void *,sqlite3*,const char*,int),
7365   void*
7366 );
7367
7368 /*
7369 ** CAPI3REF: Configure an auto-checkpoint
7370 **
7371 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7372 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7373 ** to automatically [checkpoint]
7374 ** after committing a transaction if there are N or
7375 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7376 ** a negative value as the nFrame parameter disables automatic
7377 ** checkpoints entirely.
7378 **
7379 ** ^The callback registered by this function replaces any existing callback
7380 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7381 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7382 ** configured by this function.
7383 **
7384 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7385 ** from SQL.
7386 **
7387 ** ^Every new [database connection] defaults to having the auto-checkpoint
7388 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7389 ** pages.  The use of this interface
7390 ** is only necessary if the default setting is found to be suboptimal
7391 ** for a particular application.
7392 */
7393 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7394
7395 /*
7396 ** CAPI3REF: Checkpoint a database
7397 **
7398 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7399 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7400 ** empty string, then a checkpoint is run on all databases of
7401 ** connection D.  ^If the database connection D is not in
7402 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7403 **
7404 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7405 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7406 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7407 ** run whenever the WAL reaches a certain size threshold.
7408 **
7409 ** See also: [sqlite3_wal_checkpoint_v2()]
7410 */
7411 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7412
7413 /*
7414 ** CAPI3REF: Checkpoint a database
7415 **
7416 ** Run a checkpoint operation on WAL database zDb attached to database 
7417 ** handle db. The specific operation is determined by the value of the 
7418 ** eMode parameter:
7419 **
7420 ** <dl>
7421 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7422 **   Checkpoint as many frames as possible without waiting for any database 
7423 **   readers or writers to finish. Sync the db file if all frames in the log
7424 **   are checkpointed. This mode is the same as calling 
7425 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7426 **
7427 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7428 **   This mode blocks (calls the busy-handler callback) until there is no
7429 **   database writer and all readers are reading from the most recent database
7430 **   snapshot. It then checkpoints all frames in the log file and syncs the
7431 **   database file. This call blocks database writers while it is running,
7432 **   but not database readers.
7433 **
7434 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7435 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
7436 **   checkpointing the log file it blocks (calls the busy-handler callback)
7437 **   until all readers are reading from the database file only. This ensures 
7438 **   that the next client to write to the database file restarts the log file 
7439 **   from the beginning. This call blocks database writers while it is running,
7440 **   but not database readers.
7441 ** </dl>
7442 **
7443 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7444 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7445 ** the total number of checkpointed frames (including any that were already
7446 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7447 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7448 ** If no values are available because of an error, they are both set to -1
7449 ** before returning to communicate this to the caller.
7450 **
7451 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7452 ** any other process is running a checkpoint operation at the same time, the 
7453 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
7454 ** busy-handler configured, it will not be invoked in this case.
7455 **
7456 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7457 ** "writer" lock on the database file. If the writer lock cannot be obtained
7458 ** immediately, and a busy-handler is configured, it is invoked and the writer
7459 ** lock retried until either the busy-handler returns 0 or the lock is
7460 ** successfully obtained. The busy-handler is also invoked while waiting for
7461 ** database readers as described above. If the busy-handler returns 0 before
7462 ** the writer lock is obtained or while waiting for database readers, the
7463 ** checkpoint operation proceeds from that point in the same way as 
7464 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7465 ** without blocking any further. SQLITE_BUSY is returned in this case.
7466 **
7467 ** If parameter zDb is NULL or points to a zero length string, then the
7468 ** specified operation is attempted on all WAL databases. In this case the
7469 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7470 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7471 ** attached WAL databases, the operation is still attempted on any remaining 
7472 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
7473 ** error occurs while processing an attached database, processing is abandoned 
7474 ** and the error code returned to the caller immediately. If no error 
7475 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7476 ** databases, SQLITE_OK is returned.
7477 **
7478 ** If database zDb is the name of an attached database that is not in WAL
7479 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7480 ** zDb is not NULL (or a zero length string) and is not the name of any
7481 ** attached database, SQLITE_ERROR is returned to the caller.
7482 */
7483 SQLITE_API int sqlite3_wal_checkpoint_v2(
7484   sqlite3 *db,                    /* Database handle */
7485   const char *zDb,                /* Name of attached database (or NULL) */
7486   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7487   int *pnLog,                     /* OUT: Size of WAL log in frames */
7488   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7489 );
7490
7491 /*
7492 ** CAPI3REF: Checkpoint operation parameters
7493 **
7494 ** These constants can be used as the 3rd parameter to
7495 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7496 ** documentation for additional information about the meaning and use of
7497 ** each of these values.
7498 */
7499 #define SQLITE_CHECKPOINT_PASSIVE 0
7500 #define SQLITE_CHECKPOINT_FULL    1
7501 #define SQLITE_CHECKPOINT_RESTART 2
7502
7503 /*
7504 ** CAPI3REF: Virtual Table Interface Configuration
7505 **
7506 ** This function may be called by either the [xConnect] or [xCreate] method
7507 ** of a [virtual table] implementation to configure
7508 ** various facets of the virtual table interface.
7509 **
7510 ** If this interface is invoked outside the context of an xConnect or
7511 ** xCreate virtual table method then the behavior is undefined.
7512 **
7513 ** At present, there is only one option that may be configured using
7514 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7515 ** may be added in the future.
7516 */
7517 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7518
7519 /*
7520 ** CAPI3REF: Virtual Table Configuration Options
7521 **
7522 ** These macros define the various options to the
7523 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7524 ** can use to customize and optimize their behavior.
7525 **
7526 ** <dl>
7527 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7528 ** <dd>Calls of the form
7529 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7530 ** where X is an integer.  If X is zero, then the [virtual table] whose
7531 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7532 ** support constraints.  In this configuration (which is the default) if
7533 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7534 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7535 ** specified as part of the users SQL statement, regardless of the actual
7536 ** ON CONFLICT mode specified.
7537 **
7538 ** If X is non-zero, then the virtual table implementation guarantees
7539 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7540 ** any modifications to internal or persistent data structures have been made.
7541 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7542 ** is able to roll back a statement or database transaction, and abandon
7543 ** or continue processing the current SQL statement as appropriate. 
7544 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7545 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7546 ** had been ABORT.
7547 **
7548 ** Virtual table implementations that are required to handle OR REPLACE
7549 ** must do so within the [xUpdate] method. If a call to the 
7550 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7551 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7552 ** silently replace the appropriate rows within the xUpdate callback and
7553 ** return SQLITE_OK. Or, if this is not possible, it may return
7554 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7555 ** constraint handling.
7556 ** </dl>
7557 */
7558 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7559
7560 /*
7561 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7562 **
7563 ** This function may only be called from within a call to the [xUpdate] method
7564 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7565 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7566 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7567 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7568 ** [virtual table].
7569 */
7570 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7571
7572 /*
7573 ** CAPI3REF: Conflict resolution modes
7574 **
7575 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7576 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7577 ** is for the SQL statement being evaluated.
7578 **
7579 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7580 ** return value from the [sqlite3_set_authorizer()] callback and that
7581 ** [SQLITE_ABORT] is also a [result code].
7582 */
7583 #define SQLITE_ROLLBACK 1
7584 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7585 #define SQLITE_FAIL     3
7586 /* #define SQLITE_ABORT 4  // Also an error code */
7587 #define SQLITE_REPLACE  5
7588
7589
7590
7591 /*
7592 ** Undo the hack that converts floating point types to integer for
7593 ** builds on processors without floating point support.
7594 */
7595 #ifdef SQLITE_OMIT_FLOATING_POINT
7596 # undef double
7597 #endif
7598
7599 #if 0
7600 }  /* End of the 'extern "C"' block */
7601 #endif
7602 #endif
7603
7604 /*
7605 ** 2010 August 30
7606 **
7607 ** The author disclaims copyright to this source code.  In place of
7608 ** a legal notice, here is a blessing:
7609 **
7610 **    May you do good and not evil.
7611 **    May you find forgiveness for yourself and forgive others.
7612 **    May you share freely, never taking more than you give.
7613 **
7614 *************************************************************************
7615 */
7616
7617 #ifndef _SQLITE3RTREE_H_
7618 #define _SQLITE3RTREE_H_
7619
7620
7621 #if 0
7622 extern "C" {
7623 #endif
7624
7625 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7626
7627 /*
7628 ** Register a geometry callback named zGeom that can be used as part of an
7629 ** R-Tree geometry query as follows:
7630 **
7631 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7632 */
7633 SQLITE_API int sqlite3_rtree_geometry_callback(
7634   sqlite3 *db,
7635   const char *zGeom,
7636 #ifdef SQLITE_RTREE_INT_ONLY
7637   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7638 #else
7639   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7640 #endif
7641   void *pContext
7642 );
7643
7644
7645 /*
7646 ** A pointer to a structure of the following type is passed as the first
7647 ** argument to callbacks registered using rtree_geometry_callback().
7648 */
7649 struct sqlite3_rtree_geometry {
7650   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7651   int nParam;                     /* Size of array aParam[] */
7652   double *aParam;                 /* Parameters passed to SQL geom function */
7653   void *pUser;                    /* Callback implementation user data */
7654   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7655 };
7656
7657
7658 #if 0
7659 }  /* end of the 'extern "C"' block */
7660 #endif
7661
7662 #endif  /* ifndef _SQLITE3RTREE_H_ */
7663
7664
7665 /************** End of sqlite3.h *********************************************/
7666 /************** Continuing where we left off in sqliteInt.h ******************/
7667 /************** Include hash.h in the middle of sqliteInt.h ******************/
7668 /************** Begin file hash.h ********************************************/
7669 /*
7670 ** 2001 September 22
7671 **
7672 ** The author disclaims copyright to this source code.  In place of
7673 ** a legal notice, here is a blessing:
7674 **
7675 **    May you do good and not evil.
7676 **    May you find forgiveness for yourself and forgive others.
7677 **    May you share freely, never taking more than you give.
7678 **
7679 *************************************************************************
7680 ** This is the header file for the generic hash-table implemenation
7681 ** used in SQLite.
7682 */
7683 #ifndef _SQLITE_HASH_H_
7684 #define _SQLITE_HASH_H_
7685
7686 /* Forward declarations of structures. */
7687 typedef struct Hash Hash;
7688 typedef struct HashElem HashElem;
7689
7690 /* A complete hash table is an instance of the following structure.
7691 ** The internals of this structure are intended to be opaque -- client
7692 ** code should not attempt to access or modify the fields of this structure
7693 ** directly.  Change this structure only by using the routines below.
7694 ** However, some of the "procedures" and "functions" for modifying and
7695 ** accessing this structure are really macros, so we can't really make
7696 ** this structure opaque.
7697 **
7698 ** All elements of the hash table are on a single doubly-linked list.
7699 ** Hash.first points to the head of this list.
7700 **
7701 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7702 ** the global doubly-linked list.  The contents of the bucket are the
7703 ** element pointed to plus the next _ht.count-1 elements in the list.
7704 **
7705 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7706 ** by a linear search of the global list.  For small tables, the 
7707 ** Hash.ht table is never allocated because if there are few elements
7708 ** in the table, it is faster to do a linear search than to manage
7709 ** the hash table.
7710 */
7711 struct Hash {
7712   unsigned int htsize;      /* Number of buckets in the hash table */
7713   unsigned int count;       /* Number of entries in this table */
7714   HashElem *first;          /* The first element of the array */
7715   struct _ht {              /* the hash table */
7716     int count;                 /* Number of entries with this hash */
7717     HashElem *chain;           /* Pointer to first entry with this hash */
7718   } *ht;
7719 };
7720
7721 /* Each element in the hash table is an instance of the following 
7722 ** structure.  All elements are stored on a single doubly-linked list.
7723 **
7724 ** Again, this structure is intended to be opaque, but it can't really
7725 ** be opaque because it is used by macros.
7726 */
7727 struct HashElem {
7728   HashElem *next, *prev;       /* Next and previous elements in the table */
7729   void *data;                  /* Data associated with this element */
7730   const char *pKey; int nKey;  /* Key associated with this element */
7731 };
7732
7733 /*
7734 ** Access routines.  To delete, insert a NULL pointer.
7735 */
7736 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7737 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7738 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7739 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7740
7741 /*
7742 ** Macros for looping over all elements of a hash table.  The idiom is
7743 ** like this:
7744 **
7745 **   Hash h;
7746 **   HashElem *p;
7747 **   ...
7748 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7749 **     SomeStructure *pData = sqliteHashData(p);
7750 **     // do something with pData
7751 **   }
7752 */
7753 #define sqliteHashFirst(H)  ((H)->first)
7754 #define sqliteHashNext(E)   ((E)->next)
7755 #define sqliteHashData(E)   ((E)->data)
7756 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7757 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7758
7759 /*
7760 ** Number of entries in a hash table
7761 */
7762 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7763
7764 #endif /* _SQLITE_HASH_H_ */
7765
7766 /************** End of hash.h ************************************************/
7767 /************** Continuing where we left off in sqliteInt.h ******************/
7768 /************** Include parse.h in the middle of sqliteInt.h *****************/
7769 /************** Begin file parse.h *******************************************/
7770 #define TK_SEMI                            1
7771 #define TK_EXPLAIN                         2
7772 #define TK_QUERY                           3
7773 #define TK_PLAN                            4
7774 #define TK_BEGIN                           5
7775 #define TK_TRANSACTION                     6
7776 #define TK_DEFERRED                        7
7777 #define TK_IMMEDIATE                       8
7778 #define TK_EXCLUSIVE                       9
7779 #define TK_COMMIT                         10
7780 #define TK_END                            11
7781 #define TK_ROLLBACK                       12
7782 #define TK_SAVEPOINT                      13
7783 #define TK_RELEASE                        14
7784 #define TK_TO                             15
7785 #define TK_TABLE                          16
7786 #define TK_CREATE                         17
7787 #define TK_IF                             18
7788 #define TK_NOT                            19
7789 #define TK_EXISTS                         20
7790 #define TK_TEMP                           21
7791 #define TK_LP                             22
7792 #define TK_RP                             23
7793 #define TK_AS                             24
7794 #define TK_COMMA                          25
7795 #define TK_ID                             26
7796 #define TK_INDEXED                        27
7797 #define TK_ABORT                          28
7798 #define TK_ACTION                         29
7799 #define TK_AFTER                          30
7800 #define TK_ANALYZE                        31
7801 #define TK_ASC                            32
7802 #define TK_ATTACH                         33
7803 #define TK_BEFORE                         34
7804 #define TK_BY                             35
7805 #define TK_CASCADE                        36
7806 #define TK_CAST                           37
7807 #define TK_COLUMNKW                       38
7808 #define TK_CONFLICT                       39
7809 #define TK_DATABASE                       40
7810 #define TK_DESC                           41
7811 #define TK_DETACH                         42
7812 #define TK_EACH                           43
7813 #define TK_FAIL                           44
7814 #define TK_FOR                            45
7815 #define TK_IGNORE                         46
7816 #define TK_INITIALLY                      47
7817 #define TK_INSTEAD                        48
7818 #define TK_LIKE_KW                        49
7819 #define TK_MATCH                          50
7820 #define TK_NO                             51
7821 #define TK_KEY                            52
7822 #define TK_OF                             53
7823 #define TK_OFFSET                         54
7824 #define TK_PRAGMA                         55
7825 #define TK_RAISE                          56
7826 #define TK_REPLACE                        57
7827 #define TK_RESTRICT                       58
7828 #define TK_ROW                            59
7829 #define TK_TRIGGER                        60
7830 #define TK_VACUUM                         61
7831 #define TK_VIEW                           62
7832 #define TK_VIRTUAL                        63
7833 #define TK_REINDEX                        64
7834 #define TK_RENAME                         65
7835 #define TK_CTIME_KW                       66
7836 #define TK_ANY                            67
7837 #define TK_OR                             68
7838 #define TK_AND                            69
7839 #define TK_IS                             70
7840 #define TK_BETWEEN                        71
7841 #define TK_IN                             72
7842 #define TK_ISNULL                         73
7843 #define TK_NOTNULL                        74
7844 #define TK_NE                             75
7845 #define TK_EQ                             76
7846 #define TK_GT                             77
7847 #define TK_LE                             78
7848 #define TK_LT                             79
7849 #define TK_GE                             80
7850 #define TK_ESCAPE                         81
7851 #define TK_BITAND                         82
7852 #define TK_BITOR                          83
7853 #define TK_LSHIFT                         84
7854 #define TK_RSHIFT                         85
7855 #define TK_PLUS                           86
7856 #define TK_MINUS                          87
7857 #define TK_STAR                           88
7858 #define TK_SLASH                          89
7859 #define TK_REM                            90
7860 #define TK_CONCAT                         91
7861 #define TK_COLLATE                        92
7862 #define TK_BITNOT                         93
7863 #define TK_STRING                         94
7864 #define TK_JOIN_KW                        95
7865 #define TK_CONSTRAINT                     96
7866 #define TK_DEFAULT                        97
7867 #define TK_NULL                           98
7868 #define TK_PRIMARY                        99
7869 #define TK_UNIQUE                         100
7870 #define TK_CHECK                          101
7871 #define TK_REFERENCES                     102
7872 #define TK_AUTOINCR                       103
7873 #define TK_ON                             104
7874 #define TK_INSERT                         105
7875 #define TK_DELETE                         106
7876 #define TK_UPDATE                         107
7877 #define TK_SET                            108
7878 #define TK_DEFERRABLE                     109
7879 #define TK_FOREIGN                        110
7880 #define TK_DROP                           111
7881 #define TK_UNION                          112
7882 #define TK_ALL                            113
7883 #define TK_EXCEPT                         114
7884 #define TK_INTERSECT                      115
7885 #define TK_SELECT                         116
7886 #define TK_DISTINCT                       117
7887 #define TK_DOT                            118
7888 #define TK_FROM                           119
7889 #define TK_JOIN                           120
7890 #define TK_USING                          121
7891 #define TK_ORDER                          122
7892 #define TK_GROUP                          123
7893 #define TK_HAVING                         124
7894 #define TK_LIMIT                          125
7895 #define TK_WHERE                          126
7896 #define TK_INTO                           127
7897 #define TK_VALUES                         128
7898 #define TK_INTEGER                        129
7899 #define TK_FLOAT                          130
7900 #define TK_BLOB                           131
7901 #define TK_REGISTER                       132
7902 #define TK_VARIABLE                       133
7903 #define TK_CASE                           134
7904 #define TK_WHEN                           135
7905 #define TK_THEN                           136
7906 #define TK_ELSE                           137
7907 #define TK_INDEX                          138
7908 #define TK_ALTER                          139
7909 #define TK_ADD                            140
7910 #define TK_TO_TEXT                        141
7911 #define TK_TO_BLOB                        142
7912 #define TK_TO_NUMERIC                     143
7913 #define TK_TO_INT                         144
7914 #define TK_TO_REAL                        145
7915 #define TK_ISNOT                          146
7916 #define TK_END_OF_FILE                    147
7917 #define TK_ILLEGAL                        148
7918 #define TK_SPACE                          149
7919 #define TK_UNCLOSED_STRING                150
7920 #define TK_FUNCTION                       151
7921 #define TK_COLUMN                         152
7922 #define TK_AGG_FUNCTION                   153
7923 #define TK_AGG_COLUMN                     154
7924 #define TK_CONST_FUNC                     155
7925 #define TK_UMINUS                         156
7926 #define TK_UPLUS                          157
7927
7928 /************** End of parse.h ***********************************************/
7929 /************** Continuing where we left off in sqliteInt.h ******************/
7930 #include <stdio.h>
7931 #include <stdlib.h>
7932 #include <string.h>
7933 #include <assert.h>
7934 #include <stddef.h>
7935
7936 /*
7937 ** If compiling for a processor that lacks floating point support,
7938 ** substitute integer for floating-point
7939 */
7940 #ifdef SQLITE_OMIT_FLOATING_POINT
7941 # define double sqlite_int64
7942 # define float sqlite_int64
7943 # define LONGDOUBLE_TYPE sqlite_int64
7944 # ifndef SQLITE_BIG_DBL
7945 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7946 # endif
7947 # define SQLITE_OMIT_DATETIME_FUNCS 1
7948 # define SQLITE_OMIT_TRACE 1
7949 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7950 # undef SQLITE_HAVE_ISNAN
7951 #endif
7952 #ifndef SQLITE_BIG_DBL
7953 # define SQLITE_BIG_DBL (1e99)
7954 #endif
7955
7956 /*
7957 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7958 ** afterward. Having this macro allows us to cause the C compiler 
7959 ** to omit code used by TEMP tables without messy #ifndef statements.
7960 */
7961 #ifdef SQLITE_OMIT_TEMPDB
7962 #define OMIT_TEMPDB 1
7963 #else
7964 #define OMIT_TEMPDB 0
7965 #endif
7966
7967 /*
7968 ** The "file format" number is an integer that is incremented whenever
7969 ** the VDBE-level file format changes.  The following macros define the
7970 ** the default file format for new databases and the maximum file format
7971 ** that the library can read.
7972 */
7973 #define SQLITE_MAX_FILE_FORMAT 4
7974 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7975 # define SQLITE_DEFAULT_FILE_FORMAT 4
7976 #endif
7977
7978 /*
7979 ** Determine whether triggers are recursive by default.  This can be
7980 ** changed at run-time using a pragma.
7981 */
7982 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7983 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7984 #endif
7985
7986 /*
7987 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7988 ** on the command-line
7989 */
7990 #ifndef SQLITE_TEMP_STORE
7991 # define SQLITE_TEMP_STORE 1
7992 #endif
7993
7994 /*
7995 ** GCC does not define the offsetof() macro so we'll have to do it
7996 ** ourselves.
7997 */
7998 #ifndef offsetof
7999 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8000 #endif
8001
8002 /*
8003 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8004 ** not, there are still machines out there that use EBCDIC.)
8005 */
8006 #if 'A' == '\301'
8007 # define SQLITE_EBCDIC 1
8008 #else
8009 # define SQLITE_ASCII 1
8010 #endif
8011
8012 /*
8013 ** Integers of known sizes.  These typedefs might change for architectures
8014 ** where the sizes very.  Preprocessor macros are available so that the
8015 ** types can be conveniently redefined at compile-type.  Like this:
8016 **
8017 **         cc '-DUINTPTR_TYPE=long long int' ...
8018 */
8019 #ifndef UINT32_TYPE
8020 # ifdef HAVE_UINT32_T
8021 #  define UINT32_TYPE uint32_t
8022 # else
8023 #  define UINT32_TYPE unsigned int
8024 # endif
8025 #endif
8026 #ifndef UINT16_TYPE
8027 # ifdef HAVE_UINT16_T
8028 #  define UINT16_TYPE uint16_t
8029 # else
8030 #  define UINT16_TYPE unsigned short int
8031 # endif
8032 #endif
8033 #ifndef INT16_TYPE
8034 # ifdef HAVE_INT16_T
8035 #  define INT16_TYPE int16_t
8036 # else
8037 #  define INT16_TYPE short int
8038 # endif
8039 #endif
8040 #ifndef UINT8_TYPE
8041 # ifdef HAVE_UINT8_T
8042 #  define UINT8_TYPE uint8_t
8043 # else
8044 #  define UINT8_TYPE unsigned char
8045 # endif
8046 #endif
8047 #ifndef INT8_TYPE
8048 # ifdef HAVE_INT8_T
8049 #  define INT8_TYPE int8_t
8050 # else
8051 #  define INT8_TYPE signed char
8052 # endif
8053 #endif
8054 #ifndef LONGDOUBLE_TYPE
8055 # define LONGDOUBLE_TYPE long double
8056 #endif
8057 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8058 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8059 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8060 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8061 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8062 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8063 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8064
8065 /*
8066 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8067 ** that can be stored in a u32 without loss of data.  The value
8068 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8069 ** have to specify the value in the less intuitive manner shown:
8070 */
8071 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8072
8073 /*
8074 ** The datatype used to store estimates of the number of rows in a
8075 ** table or index.  This is an unsigned integer type.  For 99.9% of
8076 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8077 ** can be used at compile-time if desired.
8078 */
8079 #ifdef SQLITE_64BIT_STATS
8080  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8081 #else
8082  typedef u32 tRowcnt;    /* 32-bit is the default */
8083 #endif
8084
8085 /*
8086 ** Macros to determine whether the machine is big or little endian,
8087 ** evaluated at runtime.
8088 */
8089 #ifdef SQLITE_AMALGAMATION
8090 SQLITE_PRIVATE const int sqlite3one = 1;
8091 #else
8092 SQLITE_PRIVATE const int sqlite3one;
8093 #endif
8094 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8095                              || defined(__x86_64) || defined(__x86_64__)
8096 # define SQLITE_BIGENDIAN    0
8097 # define SQLITE_LITTLEENDIAN 1
8098 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8099 #else
8100 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8101 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8102 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8103 #endif
8104
8105 /*
8106 ** Constants for the largest and smallest possible 64-bit signed integers.
8107 ** These macros are designed to work correctly on both 32-bit and 64-bit
8108 ** compilers.
8109 */
8110 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8111 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8112
8113 /* 
8114 ** Round up a number to the next larger multiple of 8.  This is used
8115 ** to force 8-byte alignment on 64-bit architectures.
8116 */
8117 #define ROUND8(x)     (((x)+7)&~7)
8118
8119 /*
8120 ** Round down to the nearest multiple of 8
8121 */
8122 #define ROUNDDOWN8(x) ((x)&~7)
8123
8124 /*
8125 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8126 ** macro is used only within assert() to verify that the code gets
8127 ** all alignment restrictions correct.
8128 **
8129 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8130 ** underlying malloc() implemention might return us 4-byte aligned
8131 ** pointers.  In that case, only verify 4-byte alignment.
8132 */
8133 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8134 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8135 #else
8136 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8137 #endif
8138
8139
8140 /*
8141 ** An instance of the following structure is used to store the busy-handler
8142 ** callback for a given sqlite handle. 
8143 **
8144 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8145 ** callback for the database handle. Each pager opened via the sqlite
8146 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8147 ** callback is currently invoked only from within pager.c.
8148 */
8149 typedef struct BusyHandler BusyHandler;
8150 struct BusyHandler {
8151   int (*xFunc)(void *,int);  /* The busy callback */
8152   void *pArg;                /* First arg to busy callback */
8153   int nBusy;                 /* Incremented with each busy call */
8154 };
8155
8156 /*
8157 ** Name of the master database table.  The master database table
8158 ** is a special table that holds the names and attributes of all
8159 ** user tables and indices.
8160 */
8161 #define MASTER_NAME       "sqlite_master"
8162 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8163
8164 /*
8165 ** The root-page of the master database table.
8166 */
8167 #define MASTER_ROOT       1
8168
8169 /*
8170 ** The name of the schema table.
8171 */
8172 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8173
8174 /*
8175 ** A convenience macro that returns the number of elements in
8176 ** an array.
8177 */
8178 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8179
8180 /*
8181 ** The following value as a destructor means to use sqlite3DbFree().
8182 ** The sqlite3DbFree() routine requires two parameters instead of the 
8183 ** one parameter that destructors normally want.  So we have to introduce 
8184 ** this magic value that the code knows to handle differently.  Any 
8185 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8186 ** and SQLITE_TRANSIENT.
8187 */
8188 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8189
8190 /*
8191 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8192 ** not support Writable Static Data (WSD) such as global and static variables.
8193 ** All variables must either be on the stack or dynamically allocated from
8194 ** the heap.  When WSD is unsupported, the variable declarations scattered
8195 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8196 ** macro is used for this purpose.  And instead of referencing the variable
8197 ** directly, we use its constant as a key to lookup the run-time allocated
8198 ** buffer that holds real variable.  The constant is also the initializer
8199 ** for the run-time allocated buffer.
8200 **
8201 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8202 ** macros become no-ops and have zero performance impact.
8203 */
8204 #ifdef SQLITE_OMIT_WSD
8205   #define SQLITE_WSD const
8206   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8207   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8208 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8209 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8210 #else
8211   #define SQLITE_WSD 
8212   #define GLOBAL(t,v) v
8213   #define sqlite3GlobalConfig sqlite3Config
8214 #endif
8215
8216 /*
8217 ** The following macros are used to suppress compiler warnings and to
8218 ** make it clear to human readers when a function parameter is deliberately 
8219 ** left unused within the body of a function. This usually happens when
8220 ** a function is called via a function pointer. For example the 
8221 ** implementation of an SQL aggregate step callback may not use the
8222 ** parameter indicating the number of arguments passed to the aggregate,
8223 ** if it knows that this is enforced elsewhere.
8224 **
8225 ** When a function parameter is not used at all within the body of a function,
8226 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8227 ** However, these macros may also be used to suppress warnings related to
8228 ** parameters that may or may not be used depending on compilation options.
8229 ** For example those parameters only used in assert() statements. In these
8230 ** cases the parameters are named as per the usual conventions.
8231 */
8232 #define UNUSED_PARAMETER(x) (void)(x)
8233 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8234
8235 /*
8236 ** Forward references to structures
8237 */
8238 typedef struct AggInfo AggInfo;
8239 typedef struct AuthContext AuthContext;
8240 typedef struct AutoincInfo AutoincInfo;
8241 typedef struct Bitvec Bitvec;
8242 typedef struct CollSeq CollSeq;
8243 typedef struct Column Column;
8244 typedef struct Db Db;
8245 typedef struct Schema Schema;
8246 typedef struct Expr Expr;
8247 typedef struct ExprList ExprList;
8248 typedef struct ExprSpan ExprSpan;
8249 typedef struct FKey FKey;
8250 typedef struct FuncDestructor FuncDestructor;
8251 typedef struct FuncDef FuncDef;
8252 typedef struct FuncDefHash FuncDefHash;
8253 typedef struct IdList IdList;
8254 typedef struct Index Index;
8255 typedef struct IndexSample IndexSample;
8256 typedef struct KeyClass KeyClass;
8257 typedef struct KeyInfo KeyInfo;
8258 typedef struct Lookaside Lookaside;
8259 typedef struct LookasideSlot LookasideSlot;
8260 typedef struct Module Module;
8261 typedef struct NameContext NameContext;
8262 typedef struct Parse Parse;
8263 typedef struct RowSet RowSet;
8264 typedef struct Savepoint Savepoint;
8265 typedef struct Select Select;
8266 typedef struct SrcList SrcList;
8267 typedef struct StrAccum StrAccum;
8268 typedef struct Table Table;
8269 typedef struct TableLock TableLock;
8270 typedef struct Token Token;
8271 typedef struct Trigger Trigger;
8272 typedef struct TriggerPrg TriggerPrg;
8273 typedef struct TriggerStep TriggerStep;
8274 typedef struct UnpackedRecord UnpackedRecord;
8275 typedef struct VTable VTable;
8276 typedef struct VtabCtx VtabCtx;
8277 typedef struct Walker Walker;
8278 typedef struct WherePlan WherePlan;
8279 typedef struct WhereInfo WhereInfo;
8280 typedef struct WhereLevel WhereLevel;
8281
8282 /*
8283 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
8284 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8285 ** pointer types (i.e. FuncDef) defined above.
8286 */
8287 /************** Include btree.h in the middle of sqliteInt.h *****************/
8288 /************** Begin file btree.h *******************************************/
8289 /*
8290 ** 2001 September 15
8291 **
8292 ** The author disclaims copyright to this source code.  In place of
8293 ** a legal notice, here is a blessing:
8294 **
8295 **    May you do good and not evil.
8296 **    May you find forgiveness for yourself and forgive others.
8297 **    May you share freely, never taking more than you give.
8298 **
8299 *************************************************************************
8300 ** This header file defines the interface that the sqlite B-Tree file
8301 ** subsystem.  See comments in the source code for a detailed description
8302 ** of what each interface routine does.
8303 */
8304 #ifndef _BTREE_H_
8305 #define _BTREE_H_
8306
8307 /* TODO: This definition is just included so other modules compile. It
8308 ** needs to be revisited.
8309 */
8310 #define SQLITE_N_BTREE_META 10
8311
8312 /*
8313 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8314 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8315 */
8316 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8317   #define SQLITE_DEFAULT_AUTOVACUUM 0
8318 #endif
8319
8320 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8321 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8322 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8323
8324 /*
8325 ** Forward declarations of structure
8326 */
8327 typedef struct Btree Btree;
8328 typedef struct BtCursor BtCursor;
8329 typedef struct BtShared BtShared;
8330
8331
8332 SQLITE_PRIVATE int sqlite3BtreeOpen(
8333   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8334   const char *zFilename,   /* Name of database file to open */
8335   sqlite3 *db,             /* Associated database connection */
8336   Btree **ppBtree,         /* Return open Btree* here */
8337   int flags,               /* Flags */
8338   int vfsFlags             /* Flags passed through to VFS open */
8339 );
8340
8341 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8342 ** following values.
8343 **
8344 ** NOTE:  These values must match the corresponding PAGER_ values in
8345 ** pager.h.
8346 */
8347 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8348 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8349 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8350 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8351
8352 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8353 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8354 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8355 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8356 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8357 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8358 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8359 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8360 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8361 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8362 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8363 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8364 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8365 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8366 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8367 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8368 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8369 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8370 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8371 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8372 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8373 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8374 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8375 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8376 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8377 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8378
8379 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8380 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8381 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8382
8383 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8384
8385 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8386 ** of the flags shown below.
8387 **
8388 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8389 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8390 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8391 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8392 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8393 ** indices.)
8394 */
8395 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8396 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8397
8398 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8399 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8400 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8401
8402 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8403 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8404
8405 /*
8406 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8407 ** should be one of the following values. The integer values are assigned 
8408 ** to constants so that the offset of the corresponding field in an
8409 ** SQLite database header may be found using the following formula:
8410 **
8411 **   offset = 36 + (idx * 4)
8412 **
8413 ** For example, the free-page-count field is located at byte offset 36 of
8414 ** the database file header. The incr-vacuum-flag field is located at
8415 ** byte offset 64 (== 36+4*7).
8416 */
8417 #define BTREE_FREE_PAGE_COUNT     0
8418 #define BTREE_SCHEMA_VERSION      1
8419 #define BTREE_FILE_FORMAT         2
8420 #define BTREE_DEFAULT_CACHE_SIZE  3
8421 #define BTREE_LARGEST_ROOT_PAGE   4
8422 #define BTREE_TEXT_ENCODING       5
8423 #define BTREE_USER_VERSION        6
8424 #define BTREE_INCR_VACUUM         7
8425
8426 /*
8427 ** Values that may be OR'd together to form the second argument of an
8428 ** sqlite3BtreeCursorHints() call.
8429 */
8430 #define BTREE_BULKLOAD 0x00000001
8431
8432 SQLITE_PRIVATE int sqlite3BtreeCursor(
8433   Btree*,                              /* BTree containing table to open */
8434   int iTable,                          /* Index of root page */
8435   int wrFlag,                          /* 1 for writing.  0 for read-only */
8436   struct KeyInfo*,                     /* First argument to compare function */
8437   BtCursor *pCursor                    /* Space to write cursor structure */
8438 );
8439 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8440 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8441
8442 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8443 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8444   BtCursor*,
8445   UnpackedRecord *pUnKey,
8446   i64 intKey,
8447   int bias,
8448   int *pRes
8449 );
8450 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8451 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8452 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8453                                   const void *pData, int nData,
8454                                   int nZero, int bias, int seekResult);
8455 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8456 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8457 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8458 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8459 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8460 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8461 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8462 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8463 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8464 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8465 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8466 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8467 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8468
8469 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8470 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8471
8472 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8473 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8474 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8475 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8476 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8477
8478 #ifndef NDEBUG
8479 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8480 #endif
8481
8482 #ifndef SQLITE_OMIT_BTREECOUNT
8483 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8484 #endif
8485
8486 #ifdef SQLITE_TEST
8487 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8488 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8489 #endif
8490
8491 #ifndef SQLITE_OMIT_WAL
8492 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8493 #endif
8494
8495 /*
8496 ** If we are not using shared cache, then there is no need to
8497 ** use mutexes to access the BtShared structures.  So make the
8498 ** Enter and Leave procedures no-ops.
8499 */
8500 #ifndef SQLITE_OMIT_SHARED_CACHE
8501 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8502 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8503 #else
8504 # define sqlite3BtreeEnter(X) 
8505 # define sqlite3BtreeEnterAll(X)
8506 #endif
8507
8508 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8509 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8510 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8511 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8512 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8513 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8514 #ifndef NDEBUG
8515   /* These routines are used inside assert() statements only. */
8516 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8517 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8518 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8519 #endif
8520 #else
8521
8522 # define sqlite3BtreeSharable(X) 0
8523 # define sqlite3BtreeLeave(X)
8524 # define sqlite3BtreeEnterCursor(X)
8525 # define sqlite3BtreeLeaveCursor(X)
8526 # define sqlite3BtreeLeaveAll(X)
8527
8528 # define sqlite3BtreeHoldsMutex(X) 1
8529 # define sqlite3BtreeHoldsAllMutexes(X) 1
8530 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8531 #endif
8532
8533
8534 #endif /* _BTREE_H_ */
8535
8536 /************** End of btree.h ***********************************************/
8537 /************** Continuing where we left off in sqliteInt.h ******************/
8538 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8539 /************** Begin file vdbe.h ********************************************/
8540 /*
8541 ** 2001 September 15
8542 **
8543 ** The author disclaims copyright to this source code.  In place of
8544 ** a legal notice, here is a blessing:
8545 **
8546 **    May you do good and not evil.
8547 **    May you find forgiveness for yourself and forgive others.
8548 **    May you share freely, never taking more than you give.
8549 **
8550 *************************************************************************
8551 ** Header file for the Virtual DataBase Engine (VDBE)
8552 **
8553 ** This header defines the interface to the virtual database engine
8554 ** or VDBE.  The VDBE implements an abstract machine that runs a
8555 ** simple program to access and modify the underlying database.
8556 */
8557 #ifndef _SQLITE_VDBE_H_
8558 #define _SQLITE_VDBE_H_
8559 /* #include <stdio.h> */
8560
8561 /*
8562 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8563 ** in the source file sqliteVdbe.c are allowed to see the insides
8564 ** of this structure.
8565 */
8566 typedef struct Vdbe Vdbe;
8567
8568 /*
8569 ** The names of the following types declared in vdbeInt.h are required
8570 ** for the VdbeOp definition.
8571 */
8572 typedef struct VdbeFunc VdbeFunc;
8573 typedef struct Mem Mem;
8574 typedef struct SubProgram SubProgram;
8575
8576 /*
8577 ** A single instruction of the virtual machine has an opcode
8578 ** and as many as three operands.  The instruction is recorded
8579 ** as an instance of the following structure:
8580 */
8581 struct VdbeOp {
8582   u8 opcode;          /* What operation to perform */
8583   signed char p4type; /* One of the P4_xxx constants for p4 */
8584   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8585   u8 p5;              /* Fifth parameter is an unsigned character */
8586   int p1;             /* First operand */
8587   int p2;             /* Second parameter (often the jump destination) */
8588   int p3;             /* The third parameter */
8589   union {             /* fourth parameter */
8590     int i;                 /* Integer value if p4type==P4_INT32 */
8591     void *p;               /* Generic pointer */
8592     char *z;               /* Pointer to data for string (char array) types */
8593     i64 *pI64;             /* Used when p4type is P4_INT64 */
8594     double *pReal;         /* Used when p4type is P4_REAL */
8595     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8596     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8597     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8598     Mem *pMem;             /* Used when p4type is P4_MEM */
8599     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8600     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8601     int *ai;               /* Used when p4type is P4_INTARRAY */
8602     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8603     int (*xAdvance)(BtCursor *, int *);
8604   } p4;
8605 #ifdef SQLITE_DEBUG
8606   char *zComment;          /* Comment to improve readability */
8607 #endif
8608 #ifdef VDBE_PROFILE
8609   int cnt;                 /* Number of times this instruction was executed */
8610   u64 cycles;              /* Total time spent executing this instruction */
8611 #endif
8612 };
8613 typedef struct VdbeOp VdbeOp;
8614
8615
8616 /*
8617 ** A sub-routine used to implement a trigger program.
8618 */
8619 struct SubProgram {
8620   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8621   int nOp;                      /* Elements in aOp[] */
8622   int nMem;                     /* Number of memory cells required */
8623   int nCsr;                     /* Number of cursors required */
8624   int nOnce;                    /* Number of OP_Once instructions */
8625   void *token;                  /* id that may be used to recursive triggers */
8626   SubProgram *pNext;            /* Next sub-program already visited */
8627 };
8628
8629 /*
8630 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8631 ** it takes up less space.
8632 */
8633 struct VdbeOpList {
8634   u8 opcode;          /* What operation to perform */
8635   signed char p1;     /* First operand */
8636   signed char p2;     /* Second parameter (often the jump destination) */
8637   signed char p3;     /* Third parameter */
8638 };
8639 typedef struct VdbeOpList VdbeOpList;
8640
8641 /*
8642 ** Allowed values of VdbeOp.p4type
8643 */
8644 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8645 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8646 #define P4_STATIC   (-2)  /* Pointer to a static string */
8647 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8648 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8649 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8650 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8651 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8652 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8653 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8654 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8655 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8656 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8657 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8658 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8659 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8660 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8661
8662 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8663 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8664 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8665 ** gets freed when the Vdbe is finalized so it still should be obtained
8666 ** from a single sqliteMalloc().  But no copy is made and the calling
8667 ** function should *not* try to free the KeyInfo.
8668 */
8669 #define P4_KEYINFO_HANDOFF (-16)
8670 #define P4_KEYINFO_STATIC  (-17)
8671
8672 /*
8673 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8674 ** number of columns of data returned by the statement.
8675 */
8676 #define COLNAME_NAME     0
8677 #define COLNAME_DECLTYPE 1
8678 #define COLNAME_DATABASE 2
8679 #define COLNAME_TABLE    3
8680 #define COLNAME_COLUMN   4
8681 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8682 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8683 #else
8684 # ifdef SQLITE_OMIT_DECLTYPE
8685 #   define COLNAME_N      1      /* Store only the name */
8686 # else
8687 #   define COLNAME_N      2      /* Store the name and decltype */
8688 # endif
8689 #endif
8690
8691 /*
8692 ** The following macro converts a relative address in the p2 field
8693 ** of a VdbeOp structure into a negative number so that 
8694 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8695 ** the macro again restores the address.
8696 */
8697 #define ADDR(X)  (-1-(X))
8698
8699 /*
8700 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8701 ** header file that defines a number for each opcode used by the VDBE.
8702 */
8703 /************** Include opcodes.h in the middle of vdbe.h ********************/
8704 /************** Begin file opcodes.h *****************************************/
8705 /* Automatically generated.  Do not edit */
8706 /* See the mkopcodeh.awk script for details */
8707 #define OP_Goto                                 1
8708 #define OP_Gosub                                2
8709 #define OP_Return                               3
8710 #define OP_Yield                                4
8711 #define OP_HaltIfNull                           5
8712 #define OP_Halt                                 6
8713 #define OP_Integer                              7
8714 #define OP_Int64                                8
8715 #define OP_Real                               130   /* same as TK_FLOAT    */
8716 #define OP_String8                             94   /* same as TK_STRING   */
8717 #define OP_String                               9
8718 #define OP_Null                                10
8719 #define OP_Blob                                11
8720 #define OP_Variable                            12
8721 #define OP_Move                                13
8722 #define OP_Copy                                14
8723 #define OP_SCopy                               15
8724 #define OP_ResultRow                           16
8725 #define OP_Concat                              91   /* same as TK_CONCAT   */
8726 #define OP_Add                                 86   /* same as TK_PLUS     */
8727 #define OP_Subtract                            87   /* same as TK_MINUS    */
8728 #define OP_Multiply                            88   /* same as TK_STAR     */
8729 #define OP_Divide                              89   /* same as TK_SLASH    */
8730 #define OP_Remainder                           90   /* same as TK_REM      */
8731 #define OP_CollSeq                             17
8732 #define OP_Function                            18
8733 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8734 #define OP_BitOr                               83   /* same as TK_BITOR    */
8735 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8736 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8737 #define OP_AddImm                              20
8738 #define OP_MustBeInt                           21
8739 #define OP_RealAffinity                        22
8740 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8741 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8742 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8743 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8744 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8745 #define OP_Eq                                  76   /* same as TK_EQ       */
8746 #define OP_Ne                                  75   /* same as TK_NE       */
8747 #define OP_Lt                                  79   /* same as TK_LT       */
8748 #define OP_Le                                  78   /* same as TK_LE       */
8749 #define OP_Gt                                  77   /* same as TK_GT       */
8750 #define OP_Ge                                  80   /* same as TK_GE       */
8751 #define OP_Permutation                         23
8752 #define OP_Compare                             24
8753 #define OP_Jump                                25
8754 #define OP_And                                 69   /* same as TK_AND      */
8755 #define OP_Or                                  68   /* same as TK_OR       */
8756 #define OP_Not                                 19   /* same as TK_NOT      */
8757 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8758 #define OP_Once                                26
8759 #define OP_If                                  27
8760 #define OP_IfNot                               28
8761 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8762 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8763 #define OP_Column                              29
8764 #define OP_Affinity                            30
8765 #define OP_MakeRecord                          31
8766 #define OP_Count                               32
8767 #define OP_Savepoint                           33
8768 #define OP_AutoCommit                          34
8769 #define OP_Transaction                         35
8770 #define OP_ReadCookie                          36
8771 #define OP_SetCookie                           37
8772 #define OP_VerifyCookie                        38
8773 #define OP_OpenRead                            39
8774 #define OP_OpenWrite                           40
8775 #define OP_OpenAutoindex                       41
8776 #define OP_OpenEphemeral                       42
8777 #define OP_SorterOpen                          43
8778 #define OP_OpenPseudo                          44
8779 #define OP_Close                               45
8780 #define OP_SeekLt                              46
8781 #define OP_SeekLe                              47
8782 #define OP_SeekGe                              48
8783 #define OP_SeekGt                              49
8784 #define OP_Seek                                50
8785 #define OP_NotFound                            51
8786 #define OP_Found                               52
8787 #define OP_IsUnique                            53
8788 #define OP_NotExists                           54
8789 #define OP_Sequence                            55
8790 #define OP_NewRowid                            56
8791 #define OP_Insert                              57
8792 #define OP_InsertInt                           58
8793 #define OP_Delete                              59
8794 #define OP_ResetCount                          60
8795 #define OP_SorterCompare                       61
8796 #define OP_SorterData                          62
8797 #define OP_RowKey                              63
8798 #define OP_RowData                             64
8799 #define OP_Rowid                               65
8800 #define OP_NullRow                             66
8801 #define OP_Last                                67
8802 #define OP_SorterSort                          70
8803 #define OP_Sort                                71
8804 #define OP_Rewind                              72
8805 #define OP_SorterNext                          81
8806 #define OP_Prev                                92
8807 #define OP_Next                                95
8808 #define OP_SorterInsert                        96
8809 #define OP_IdxInsert                           97
8810 #define OP_IdxDelete                           98
8811 #define OP_IdxRowid                            99
8812 #define OP_IdxLT                              100
8813 #define OP_IdxGE                              101
8814 #define OP_Destroy                            102
8815 #define OP_Clear                              103
8816 #define OP_CreateIndex                        104
8817 #define OP_CreateTable                        105
8818 #define OP_ParseSchema                        106
8819 #define OP_LoadAnalysis                       107
8820 #define OP_DropTable                          108
8821 #define OP_DropIndex                          109
8822 #define OP_DropTrigger                        110
8823 #define OP_IntegrityCk                        111
8824 #define OP_RowSetAdd                          112
8825 #define OP_RowSetRead                         113
8826 #define OP_RowSetTest                         114
8827 #define OP_Program                            115
8828 #define OP_Param                              116
8829 #define OP_FkCounter                          117
8830 #define OP_FkIfZero                           118
8831 #define OP_MemMax                             119
8832 #define OP_IfPos                              120
8833 #define OP_IfNeg                              121
8834 #define OP_IfZero                             122
8835 #define OP_AggStep                            123
8836 #define OP_AggFinal                           124
8837 #define OP_Checkpoint                         125
8838 #define OP_JournalMode                        126
8839 #define OP_Vacuum                             127
8840 #define OP_IncrVacuum                         128
8841 #define OP_Expire                             129
8842 #define OP_TableLock                          131
8843 #define OP_VBegin                             132
8844 #define OP_VCreate                            133
8845 #define OP_VDestroy                           134
8846 #define OP_VOpen                              135
8847 #define OP_VFilter                            136
8848 #define OP_VColumn                            137
8849 #define OP_VNext                              138
8850 #define OP_VRename                            139
8851 #define OP_VUpdate                            140
8852 #define OP_Pagecount                          146
8853 #define OP_MaxPgcnt                           147
8854 #define OP_Trace                              148
8855 #define OP_Noop                               149
8856 #define OP_Explain                            150
8857
8858
8859 /* Properties such as "out2" or "jump" that are specified in
8860 ** comments following the "case" for each opcode in the vdbe.c
8861 ** are encoded into bitvectors as follows:
8862 */
8863 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8864 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8865 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8866 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8867 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8868 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8869 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8870 #define OPFLG_INITIALIZER {\
8871 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8872 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8873 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8874 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8875 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8876 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8877 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8878 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8879 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8880 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8881 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8882 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8883 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8884 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8885 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8886 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8887 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8888 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8889 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8890
8891 /************** End of opcodes.h *********************************************/
8892 /************** Continuing where we left off in vdbe.h ***********************/
8893
8894 /*
8895 ** Prototypes for the VDBE interface.  See comments on the implementation
8896 ** for a description of what each of these routines does.
8897 */
8898 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8899 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8900 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8901 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8902 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8903 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8904 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8905 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8906 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8907 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8908 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8909 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8910 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8911 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8912 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8913 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8914 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8915 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8916 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8917 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8918 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8919 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8920 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8921 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8922 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8923 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8924 #ifdef SQLITE_DEBUG
8925 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8926 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8927 #endif
8928 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8929 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8930 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8931 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8932 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8933 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8934 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8935 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8936 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8937 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8938 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8939 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8940 #ifndef SQLITE_OMIT_TRACE
8941 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8942 #endif
8943
8944 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8945 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8946 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8947
8948 #ifndef SQLITE_OMIT_TRIGGER
8949 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8950 #endif
8951
8952
8953 #ifndef NDEBUG
8954 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8955 # define VdbeComment(X)  sqlite3VdbeComment X
8956 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8957 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8958 #else
8959 # define VdbeComment(X)
8960 # define VdbeNoopComment(X)
8961 #endif
8962
8963 #endif
8964
8965 /************** End of vdbe.h ************************************************/
8966 /************** Continuing where we left off in sqliteInt.h ******************/
8967 /************** Include pager.h in the middle of sqliteInt.h *****************/
8968 /************** Begin file pager.h *******************************************/
8969 /*
8970 ** 2001 September 15
8971 **
8972 ** The author disclaims copyright to this source code.  In place of
8973 ** a legal notice, here is a blessing:
8974 **
8975 **    May you do good and not evil.
8976 **    May you find forgiveness for yourself and forgive others.
8977 **    May you share freely, never taking more than you give.
8978 **
8979 *************************************************************************
8980 ** This header file defines the interface that the sqlite page cache
8981 ** subsystem.  The page cache subsystem reads and writes a file a page
8982 ** at a time and provides a journal for rollback.
8983 */
8984
8985 #ifndef _PAGER_H_
8986 #define _PAGER_H_
8987
8988 /*
8989 ** Default maximum size for persistent journal files. A negative 
8990 ** value means no limit. This value may be overridden using the 
8991 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8992 */
8993 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8994   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8995 #endif
8996
8997 /*
8998 ** The type used to represent a page number.  The first page in a file
8999 ** is called page 1.  0 is used to represent "not a page".
9000 */
9001 typedef u32 Pgno;
9002
9003 /*
9004 ** Each open file is managed by a separate instance of the "Pager" structure.
9005 */
9006 typedef struct Pager Pager;
9007
9008 /*
9009 ** Handle type for pages.
9010 */
9011 typedef struct PgHdr DbPage;
9012
9013 /*
9014 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9015 ** reserved for working around a windows/posix incompatibility). It is
9016 ** used in the journal to signify that the remainder of the journal file 
9017 ** is devoted to storing a master journal name - there are no more pages to
9018 ** roll back. See comments for function writeMasterJournal() in pager.c 
9019 ** for details.
9020 */
9021 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9022
9023 /*
9024 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9025 **
9026 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9027 */
9028 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9029 #define PAGER_MEMORY        0x0002    /* In-memory database */
9030
9031 /*
9032 ** Valid values for the second argument to sqlite3PagerLockingMode().
9033 */
9034 #define PAGER_LOCKINGMODE_QUERY      -1
9035 #define PAGER_LOCKINGMODE_NORMAL      0
9036 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9037
9038 /*
9039 ** Numeric constants that encode the journalmode.  
9040 */
9041 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9042 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9043 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9044 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9045 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9046 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9047 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9048
9049 /*
9050 ** The remainder of this file contains the declarations of the functions
9051 ** that make up the Pager sub-system API. See source code comments for 
9052 ** a detailed description of each routine.
9053 */
9054
9055 /* Open and close a Pager connection. */ 
9056 SQLITE_PRIVATE int sqlite3PagerOpen(
9057   sqlite3_vfs*,
9058   Pager **ppPager,
9059   const char*,
9060   int,
9061   int,
9062   int,
9063   void(*)(DbPage*)
9064 );
9065 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9066 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9067
9068 /* Functions used to configure a Pager object. */
9069 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9070 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9071 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9072 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9073 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9074 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9075 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9076 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9077 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9078 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9079 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9080 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9081
9082 /* Functions used to obtain and release page references. */ 
9083 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9084 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9085 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9086 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9087 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9088
9089 /* Operations on page references. */
9090 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9091 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9092 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9093 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9094 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
9095 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
9096
9097 /* Functions used to manage pager transactions and savepoints. */
9098 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9099 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9100 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9101 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9102 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9103 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9104 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9105 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9106 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9107 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9108
9109 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9110 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9111 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9112 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9113 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9114 #ifdef SQLITE_ENABLE_ZIPVFS
9115 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9116 #endif
9117
9118 /* Functions used to query pager state and configuration. */
9119 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9120 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9121 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9122 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9123 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9124 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9125 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9126 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9127 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9128 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9129 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9130 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9131
9132 /* Functions used to truncate the database file. */
9133 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9134
9135 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9136 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9137 #endif
9138
9139 /* Functions to support testing and debugging. */
9140 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9141 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9142 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9143 #endif
9144 #ifdef SQLITE_TEST
9145 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9146 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9147   void disable_simulated_io_errors(void);
9148   void enable_simulated_io_errors(void);
9149 #else
9150 # define disable_simulated_io_errors()
9151 # define enable_simulated_io_errors()
9152 #endif
9153
9154 #endif /* _PAGER_H_ */
9155
9156 /************** End of pager.h ***********************************************/
9157 /************** Continuing where we left off in sqliteInt.h ******************/
9158 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9159 /************** Begin file pcache.h ******************************************/
9160 /*
9161 ** 2008 August 05
9162 **
9163 ** The author disclaims copyright to this source code.  In place of
9164 ** a legal notice, here is a blessing:
9165 **
9166 **    May you do good and not evil.
9167 **    May you find forgiveness for yourself and forgive others.
9168 **    May you share freely, never taking more than you give.
9169 **
9170 *************************************************************************
9171 ** This header file defines the interface that the sqlite page cache
9172 ** subsystem. 
9173 */
9174
9175 #ifndef _PCACHE_H_
9176
9177 typedef struct PgHdr PgHdr;
9178 typedef struct PCache PCache;
9179
9180 /*
9181 ** Every page in the cache is controlled by an instance of the following
9182 ** structure.
9183 */
9184 struct PgHdr {
9185   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9186   void *pData;                   /* Page data */
9187   void *pExtra;                  /* Extra content */
9188   PgHdr *pDirty;                 /* Transient list of dirty pages */
9189   Pager *pPager;                 /* The pager this page is part of */
9190   Pgno pgno;                     /* Page number for this page */
9191 #ifdef SQLITE_CHECK_PAGES
9192   u32 pageHash;                  /* Hash of page content */
9193 #endif
9194   u16 flags;                     /* PGHDR flags defined below */
9195
9196   /**********************************************************************
9197   ** Elements above are public.  All that follows is private to pcache.c
9198   ** and should not be accessed by other modules.
9199   */
9200   i16 nRef;                      /* Number of users of this page */
9201   PCache *pCache;                /* Cache that owns this page */
9202
9203   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9204   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9205 };
9206
9207 /* Bit values for PgHdr.flags */
9208 #define PGHDR_DIRTY             0x002  /* Page has changed */
9209 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9210                                        ** writing this page to the database */
9211 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9212 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9213 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9214
9215 /* Initialize and shutdown the page cache subsystem */
9216 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9217 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9218
9219 /* Page cache buffer management:
9220 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9221 */
9222 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9223
9224 /* Create a new pager cache.
9225 ** Under memory stress, invoke xStress to try to make pages clean.
9226 ** Only clean and unpinned pages can be reclaimed.
9227 */
9228 SQLITE_PRIVATE void sqlite3PcacheOpen(
9229   int szPage,                    /* Size of every page */
9230   int szExtra,                   /* Extra space associated with each page */
9231   int bPurgeable,                /* True if pages are on backing store */
9232   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9233   void *pStress,                 /* Argument to xStress */
9234   PCache *pToInit                /* Preallocated space for the PCache */
9235 );
9236
9237 /* Modify the page-size after the cache has been created. */
9238 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9239
9240 /* Return the size in bytes of a PCache object.  Used to preallocate
9241 ** storage space.
9242 */
9243 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9244
9245 /* One release per successful fetch.  Page is pinned until released.
9246 ** Reference counted. 
9247 */
9248 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9249 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9250
9251 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9252 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9253 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9254 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9255
9256 /* Change a page number.  Used by incr-vacuum. */
9257 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9258
9259 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9260 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9261
9262 /* Get a list of all dirty pages in the cache, sorted by page number */
9263 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9264
9265 /* Reset and close the cache object */
9266 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9267
9268 /* Clear flags from pages of the page cache */
9269 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9270
9271 /* Discard the contents of the cache */
9272 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9273
9274 /* Return the total number of outstanding page references */
9275 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9276
9277 /* Increment the reference count of an existing page */
9278 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9279
9280 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9281
9282 /* Return the total number of pages stored in the cache */
9283 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9284
9285 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9286 /* Iterate through all dirty pages currently stored in the cache. This
9287 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
9288 ** library is built.
9289 */
9290 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9291 #endif
9292
9293 /* Set and get the suggested cache-size for the specified pager-cache.
9294 **
9295 ** If no global maximum is configured, then the system attempts to limit
9296 ** the total number of pages cached by purgeable pager-caches to the sum
9297 ** of the suggested cache-sizes.
9298 */
9299 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9300 #ifdef SQLITE_TEST
9301 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9302 #endif
9303
9304 /* Free up as much memory as possible from the page cache */
9305 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9306
9307 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9308 /* Try to return memory used by the pcache module to the main memory heap */
9309 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9310 #endif
9311
9312 #ifdef SQLITE_TEST
9313 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9314 #endif
9315
9316 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9317
9318 #endif /* _PCACHE_H_ */
9319
9320 /************** End of pcache.h **********************************************/
9321 /************** Continuing where we left off in sqliteInt.h ******************/
9322
9323 /************** Include os.h in the middle of sqliteInt.h ********************/
9324 /************** Begin file os.h **********************************************/
9325 /*
9326 ** 2001 September 16
9327 **
9328 ** The author disclaims copyright to this source code.  In place of
9329 ** a legal notice, here is a blessing:
9330 **
9331 **    May you do good and not evil.
9332 **    May you find forgiveness for yourself and forgive others.
9333 **    May you share freely, never taking more than you give.
9334 **
9335 ******************************************************************************
9336 **
9337 ** This header file (together with is companion C source-code file
9338 ** "os.c") attempt to abstract the underlying operating system so that
9339 ** the SQLite library will work on both POSIX and windows systems.
9340 **
9341 ** This header file is #include-ed by sqliteInt.h and thus ends up
9342 ** being included by every source file.
9343 */
9344 #ifndef _SQLITE_OS_H_
9345 #define _SQLITE_OS_H_
9346
9347 /*
9348 ** Figure out if we are dealing with Unix, Windows, or some other
9349 ** operating system.  After the following block of preprocess macros,
9350 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER 
9351 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9352 ** three will be 0.
9353 */
9354 #if defined(SQLITE_OS_OTHER)
9355 # if SQLITE_OS_OTHER==1
9356 #   undef SQLITE_OS_UNIX
9357 #   define SQLITE_OS_UNIX 0
9358 #   undef SQLITE_OS_WIN
9359 #   define SQLITE_OS_WIN 0
9360 # else
9361 #   undef SQLITE_OS_OTHER
9362 # endif
9363 #endif
9364 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9365 # define SQLITE_OS_OTHER 0
9366 # ifndef SQLITE_OS_WIN
9367 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9368 #     define SQLITE_OS_WIN 1
9369 #     define SQLITE_OS_UNIX 0
9370 #   else
9371 #     define SQLITE_OS_WIN 0
9372 #     define SQLITE_OS_UNIX 1
9373 #  endif
9374 # else
9375 #  define SQLITE_OS_UNIX 0
9376 # endif
9377 #else
9378 # ifndef SQLITE_OS_WIN
9379 #  define SQLITE_OS_WIN 0
9380 # endif
9381 #endif
9382
9383 #if SQLITE_OS_WIN
9384 # include <windows.h>
9385 #endif
9386
9387 /*
9388 ** Determine if we are dealing with Windows NT.
9389 **
9390 ** We ought to be able to determine if we are compiling for win98 or winNT
9391 ** using the _WIN32_WINNT macro as follows:
9392 **
9393 ** #if defined(_WIN32_WINNT)
9394 ** # define SQLITE_OS_WINNT 1
9395 ** #else
9396 ** # define SQLITE_OS_WINNT 0
9397 ** #endif
9398 **
9399 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9400 ** so the above test does not work.  We'll just assume that everything is
9401 ** winNT unless the programmer explicitly says otherwise by setting
9402 ** SQLITE_OS_WINNT to 0.
9403 */
9404 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9405 # define SQLITE_OS_WINNT 1
9406 #endif
9407
9408 /*
9409 ** Determine if we are dealing with WindowsCE - which has a much
9410 ** reduced API.
9411 */
9412 #if defined(_WIN32_WCE)
9413 # define SQLITE_OS_WINCE 1
9414 #else
9415 # define SQLITE_OS_WINCE 0
9416 #endif
9417
9418 /*
9419 ** Determine if we are dealing with WinRT, which provides only a subset of
9420 ** the full Win32 API.
9421 */
9422 #if !defined(SQLITE_OS_WINRT)
9423 # define SQLITE_OS_WINRT 0
9424 #endif
9425
9426 /*
9427 ** When compiled for WinCE or WinRT, there is no concept of the current
9428 ** directory.
9429  */
9430 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
9431 # define SQLITE_CURDIR 1
9432 #endif
9433
9434 /* If the SET_FULLSYNC macro is not defined above, then make it
9435 ** a no-op
9436 */
9437 #ifndef SET_FULLSYNC
9438 # define SET_FULLSYNC(x,y)
9439 #endif
9440
9441 /*
9442 ** The default size of a disk sector
9443 */
9444 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9445 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9446 #endif
9447
9448 /*
9449 ** Temporary files are named starting with this prefix followed by 16 random
9450 ** alphanumeric characters, and no file extension. They are stored in the
9451 ** OS's standard temporary file directory, and are deleted prior to exit.
9452 ** If sqlite is being embedded in another program, you may wish to change the
9453 ** prefix to reflect your program's name, so that if your program exits
9454 ** prematurely, old temporary files can be easily identified. This can be done
9455 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9456 **
9457 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9458 ** Mcafee started using SQLite in their anti-virus product and it
9459 ** started putting files with the "sqlite" name in the c:/temp folder.
9460 ** This annoyed many windows users.  Those users would then do a 
9461 ** Google search for "sqlite", find the telephone numbers of the
9462 ** developers and call to wake them up at night and complain.
9463 ** For this reason, the default name prefix is changed to be "sqlite" 
9464 ** spelled backwards.  So the temp files are still identified, but
9465 ** anybody smart enough to figure out the code is also likely smart
9466 ** enough to know that calling the developer will not help get rid
9467 ** of the file.
9468 */
9469 #ifndef SQLITE_TEMP_FILE_PREFIX
9470 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9471 #endif
9472
9473 /*
9474 ** The following values may be passed as the second argument to
9475 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9476 **
9477 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9478 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9479 **            any time. Other processes may hold and obtain new SHARED locks.
9480 ** PENDING:   A single process may hold a PENDING lock on a file at
9481 **            any one time. Existing SHARED locks may persist, but no new
9482 **            SHARED locks may be obtained by other processes.
9483 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9484 **
9485 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9486 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9487 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9488 ** sqlite3OsLock().
9489 */
9490 #define NO_LOCK         0
9491 #define SHARED_LOCK     1
9492 #define RESERVED_LOCK   2
9493 #define PENDING_LOCK    3
9494 #define EXCLUSIVE_LOCK  4
9495
9496 /*
9497 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9498 **
9499 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9500 ** those functions are not available.  So we use only LockFile() and
9501 ** UnlockFile().
9502 **
9503 ** LockFile() prevents not just writing but also reading by other processes.
9504 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9505 ** byte out of a specific range of bytes. The lock byte is obtained at 
9506 ** random so two separate readers can probably access the file at the 
9507 ** same time, unless they are unlucky and choose the same lock byte.
9508 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9509 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9510 ** a single byte of the file that is designated as the reserved lock byte.
9511 ** A PENDING_LOCK is obtained by locking a designated byte different from
9512 ** the RESERVED_LOCK byte.
9513 **
9514 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9515 ** which means we can use reader/writer locks.  When reader/writer locks
9516 ** are used, the lock is placed on the same range of bytes that is used
9517 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9518 ** will support two or more Win95 readers or two or more WinNT readers.
9519 ** But a single Win95 reader will lock out all WinNT readers and a single
9520 ** WinNT reader will lock out all other Win95 readers.
9521 **
9522 ** The following #defines specify the range of bytes used for locking.
9523 ** SHARED_SIZE is the number of bytes available in the pool from which
9524 ** a random byte is selected for a shared lock.  The pool of bytes for
9525 ** shared locks begins at SHARED_FIRST. 
9526 **
9527 ** The same locking strategy and
9528 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9529 ** clients on win95, winNT, and unix all talking to the same shared file
9530 ** and all locking correctly.  To do so would require that samba (or whatever
9531 ** tool is being used for file sharing) implements locks correctly between
9532 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9533 ** using the same locking range we are at least open to the possibility.
9534 **
9535 ** Locking in windows is manditory.  For this reason, we cannot store
9536 ** actual data in the bytes used for locking.  The pager never allocates
9537 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9538 ** that all locks will fit on a single page even at the minimum page size.
9539 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9540 ** is set high so that we don't have to allocate an unused page except
9541 ** for very large databases.  But one should test the page skipping logic 
9542 ** by setting PENDING_BYTE low and running the entire regression suite.
9543 **
9544 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9545 ** file format.  Depending on how it is changed, you might not notice
9546 ** the incompatibility right away, even running a full regression test.
9547 ** The default location of PENDING_BYTE is the first byte past the
9548 ** 1GB boundary.
9549 **
9550 */
9551 #ifdef SQLITE_OMIT_WSD
9552 # define PENDING_BYTE     (0x40000000)
9553 #else
9554 # define PENDING_BYTE      sqlite3PendingByte
9555 #endif
9556 #define RESERVED_BYTE     (PENDING_BYTE+1)
9557 #define SHARED_FIRST      (PENDING_BYTE+2)
9558 #define SHARED_SIZE       510
9559
9560 /*
9561 ** Wrapper around OS specific sqlite3_os_init() function.
9562 */
9563 SQLITE_PRIVATE int sqlite3OsInit(void);
9564
9565 /* 
9566 ** Functions for accessing sqlite3_file methods 
9567 */
9568 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9569 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9570 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9571 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9572 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9573 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9574 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9575 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9576 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9577 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9578 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9579 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9580 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9581 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9582 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9583 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9584 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9585 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9586
9587
9588 /* 
9589 ** Functions for accessing sqlite3_vfs methods 
9590 */
9591 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9592 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9593 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9594 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9595 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9596 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9597 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9598 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9599 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9600 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9601 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9602 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9603 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9604
9605 /*
9606 ** Convenience functions for opening and closing files using 
9607 ** sqlite3_malloc() to obtain space for the file-handle structure.
9608 */
9609 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9610 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9611
9612 #endif /* _SQLITE_OS_H_ */
9613
9614 /************** End of os.h **************************************************/
9615 /************** Continuing where we left off in sqliteInt.h ******************/
9616 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9617 /************** Begin file mutex.h *******************************************/
9618 /*
9619 ** 2007 August 28
9620 **
9621 ** The author disclaims copyright to this source code.  In place of
9622 ** a legal notice, here is a blessing:
9623 **
9624 **    May you do good and not evil.
9625 **    May you find forgiveness for yourself and forgive others.
9626 **    May you share freely, never taking more than you give.
9627 **
9628 *************************************************************************
9629 **
9630 ** This file contains the common header for all mutex implementations.
9631 ** The sqliteInt.h header #includes this file so that it is available
9632 ** to all source files.  We break it out in an effort to keep the code
9633 ** better organized.
9634 **
9635 ** NOTE:  source files should *not* #include this header file directly.
9636 ** Source files should #include the sqliteInt.h file and let that file
9637 ** include this one indirectly.
9638 */
9639
9640
9641 /*
9642 ** Figure out what version of the code to use.  The choices are
9643 **
9644 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9645 **                             mutexes implemention cannot be overridden
9646 **                             at start-time.
9647 **
9648 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9649 **                             mutual exclusion is provided.  But this
9650 **                             implementation can be overridden at
9651 **                             start-time.
9652 **
9653 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9654 **
9655 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9656 */
9657 #if !SQLITE_THREADSAFE
9658 # define SQLITE_MUTEX_OMIT
9659 #endif
9660 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9661 #  if SQLITE_OS_UNIX
9662 #    define SQLITE_MUTEX_PTHREADS
9663 #  elif SQLITE_OS_WIN
9664 #    define SQLITE_MUTEX_W32
9665 #  else
9666 #    define SQLITE_MUTEX_NOOP
9667 #  endif
9668 #endif
9669
9670 #ifdef SQLITE_MUTEX_OMIT
9671 /*
9672 ** If this is a no-op implementation, implement everything as macros.
9673 */
9674 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9675 #define sqlite3_mutex_free(X)
9676 #define sqlite3_mutex_enter(X)    
9677 #define sqlite3_mutex_try(X)      SQLITE_OK
9678 #define sqlite3_mutex_leave(X)    
9679 #define sqlite3_mutex_held(X)     ((void)(X),1)
9680 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9681 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9682 #define sqlite3MutexInit()        SQLITE_OK
9683 #define sqlite3MutexEnd()
9684 #define MUTEX_LOGIC(X)
9685 #else
9686 #define MUTEX_LOGIC(X)            X
9687 #endif /* defined(SQLITE_MUTEX_OMIT) */
9688
9689 /************** End of mutex.h ***********************************************/
9690 /************** Continuing where we left off in sqliteInt.h ******************/
9691
9692
9693 /*
9694 ** Each database file to be accessed by the system is an instance
9695 ** of the following structure.  There are normally two of these structures
9696 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9697 ** aDb[1] is the database file used to hold temporary tables.  Additional
9698 ** databases may be attached.
9699 */
9700 struct Db {
9701   char *zName;         /* Name of this database */
9702   Btree *pBt;          /* The B*Tree structure for this database file */
9703   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9704   u8 safety_level;     /* How aggressive at syncing data to disk */
9705   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9706 };
9707
9708 /*
9709 ** An instance of the following structure stores a database schema.
9710 **
9711 ** Most Schema objects are associated with a Btree.  The exception is
9712 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9713 ** In shared cache mode, a single Schema object can be shared by multiple
9714 ** Btrees that refer to the same underlying BtShared object.
9715 ** 
9716 ** Schema objects are automatically deallocated when the last Btree that
9717 ** references them is destroyed.   The TEMP Schema is manually freed by
9718 ** sqlite3_close().
9719 *
9720 ** A thread must be holding a mutex on the corresponding Btree in order
9721 ** to access Schema content.  This implies that the thread must also be
9722 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9723 ** For a TEMP Schema, only the connection mutex is required.
9724 */
9725 struct Schema {
9726   int schema_cookie;   /* Database schema version number for this file */
9727   int iGeneration;     /* Generation counter.  Incremented with each change */
9728   Hash tblHash;        /* All tables indexed by name */
9729   Hash idxHash;        /* All (named) indices indexed by name */
9730   Hash trigHash;       /* All triggers indexed by name */
9731   Hash fkeyHash;       /* All foreign keys by referenced table name */
9732   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9733   u8 file_format;      /* Schema format version for this file */
9734   u8 enc;              /* Text encoding used by this database */
9735   u16 flags;           /* Flags associated with this schema */
9736   int cache_size;      /* Number of pages to use in the cache */
9737 };
9738
9739 /*
9740 ** These macros can be used to test, set, or clear bits in the 
9741 ** Db.pSchema->flags field.
9742 */
9743 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9744 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9745 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9746 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9747
9748 /*
9749 ** Allowed values for the DB.pSchema->flags field.
9750 **
9751 ** The DB_SchemaLoaded flag is set after the database schema has been
9752 ** read into internal hash tables.
9753 **
9754 ** DB_UnresetViews means that one or more views have column names that
9755 ** have been filled out.  If the schema changes, these column names might
9756 ** changes and so the view will need to be reset.
9757 */
9758 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9759 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9760 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9761
9762 /*
9763 ** The number of different kinds of things that can be limited
9764 ** using the sqlite3_limit() interface.
9765 */
9766 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9767
9768 /*
9769 ** Lookaside malloc is a set of fixed-size buffers that can be used
9770 ** to satisfy small transient memory allocation requests for objects
9771 ** associated with a particular database connection.  The use of
9772 ** lookaside malloc provides a significant performance enhancement
9773 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9774 ** SQL statements.
9775 **
9776 ** The Lookaside structure holds configuration information about the
9777 ** lookaside malloc subsystem.  Each available memory allocation in
9778 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9779 ** objects.
9780 **
9781 ** Lookaside allocations are only allowed for objects that are associated
9782 ** with a particular database connection.  Hence, schema information cannot
9783 ** be stored in lookaside because in shared cache mode the schema information
9784 ** is shared by multiple database connections.  Therefore, while parsing
9785 ** schema information, the Lookaside.bEnabled flag is cleared so that
9786 ** lookaside allocations are not used to construct the schema objects.
9787 */
9788 struct Lookaside {
9789   u16 sz;                 /* Size of each buffer in bytes */
9790   u8 bEnabled;            /* False to disable new lookaside allocations */
9791   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9792   int nOut;               /* Number of buffers currently checked out */
9793   int mxOut;              /* Highwater mark for nOut */
9794   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9795   LookasideSlot *pFree;   /* List of available buffers */
9796   void *pStart;           /* First byte of available memory space */
9797   void *pEnd;             /* First byte past end of available space */
9798 };
9799 struct LookasideSlot {
9800   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9801 };
9802
9803 /*
9804 ** A hash table for function definitions.
9805 **
9806 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9807 ** Collisions are on the FuncDef.pHash chain.
9808 */
9809 struct FuncDefHash {
9810   FuncDef *a[23];       /* Hash table for functions */
9811 };
9812
9813 /*
9814 ** Each database connection is an instance of the following structure.
9815 */
9816 struct sqlite3 {
9817   sqlite3_vfs *pVfs;            /* OS Interface */
9818   struct Vdbe *pVdbe;           /* List of active virtual machines */
9819   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9820   sqlite3_mutex *mutex;         /* Connection mutex */
9821   Db *aDb;                      /* All backends */
9822   int nDb;                      /* Number of backends currently in use */
9823   int flags;                    /* Miscellaneous flags. See below */
9824   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9825   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9826   int errCode;                  /* Most recent error code (SQLITE_*) */
9827   int errMask;                  /* & result codes with this before returning */
9828   u8 autoCommit;                /* The auto-commit flag. */
9829   u8 temp_store;                /* 1: file 2: memory 0: default */
9830   u8 mallocFailed;              /* True if we have seen a malloc failure */
9831   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9832   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9833   u8 suppressErr;               /* Do not issue error messages if true */
9834   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9835   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9836   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9837   u32 magic;                    /* Magic number for detect library misuse */
9838   int nChange;                  /* Value returned by sqlite3_changes() */
9839   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9840   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9841   struct sqlite3InitInfo {      /* Information used during initialization */
9842     int newTnum;                /* Rootpage of table being initialized */
9843     u8 iDb;                     /* Which db file is being initialized */
9844     u8 busy;                    /* TRUE if currently initializing */
9845     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9846   } init;
9847   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9848   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9849   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9850   int nExtension;               /* Number of loaded extensions */
9851   void **aExtension;            /* Array of shared library handles */
9852   void (*xTrace)(void*,const char*);        /* Trace function */
9853   void *pTraceArg;                          /* Argument to the trace function */
9854   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9855   void *pProfileArg;                        /* Argument to profile function */
9856   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9857   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9858   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9859   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9860   void *pUpdateArg;
9861   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9862 #ifndef SQLITE_OMIT_WAL
9863   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9864   void *pWalArg;
9865 #endif
9866   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9867   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9868   void *pCollNeededArg;
9869   sqlite3_value *pErr;          /* Most recent error message */
9870   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9871   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9872   union {
9873     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9874     double notUsed1;            /* Spacer */
9875   } u1;
9876   Lookaside lookaside;          /* Lookaside malloc configuration */
9877 #ifndef SQLITE_OMIT_AUTHORIZATION
9878   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9879                                 /* Access authorization function */
9880   void *pAuthArg;               /* 1st argument to the access auth function */
9881 #endif
9882 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9883   int (*xProgress)(void *);     /* The progress callback */
9884   void *pProgressArg;           /* Argument to the progress callback */
9885   int nProgressOps;             /* Number of opcodes for progress callback */
9886 #endif
9887 #ifndef SQLITE_OMIT_VIRTUALTABLE
9888   int nVTrans;                  /* Allocated size of aVTrans */
9889   Hash aModule;                 /* populated by sqlite3_create_module() */
9890   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9891   VTable **aVTrans;             /* Virtual tables with open transactions */
9892   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9893 #endif
9894   FuncDefHash aFunc;            /* Hash table of connection functions */
9895   Hash aCollSeq;                /* All collating sequences */
9896   BusyHandler busyHandler;      /* Busy callback */
9897   Db aDbStatic[2];              /* Static space for the 2 default backends */
9898   Savepoint *pSavepoint;        /* List of active savepoints */
9899   int busyTimeout;              /* Busy handler timeout, in msec */
9900   int nSavepoint;               /* Number of non-transaction savepoints */
9901   int nStatement;               /* Number of nested statement-transactions  */
9902   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9903   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9904
9905 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9906   /* The following variables are all protected by the STATIC_MASTER 
9907   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9908   **
9909   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9910   ** unlock so that it can proceed.
9911   **
9912   ** When X.pBlockingConnection==Y, that means that something that X tried
9913   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9914   ** held by Y.
9915   */
9916   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9917   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9918   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9919   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9920   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9921 #endif
9922 };
9923
9924 /*
9925 ** A macro to discover the encoding of a database.
9926 */
9927 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9928
9929 /*
9930 ** Possible values for the sqlite3.flags.
9931 */
9932 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9933 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9934 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9935 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9936 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9937                                           /*   DELETE, or UPDATE and return */
9938                                           /*   the count using a callback. */
9939 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9940                                           /*   result set is empty */
9941 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9942 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9943 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9944                          /*   0x00020000  Unused */
9945 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9946 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9947 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9948 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9949 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9950 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9951 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9952 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9953 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9954 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9955 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9956 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9957 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9958
9959 /*
9960 ** Bits of the sqlite3.flags field that are used by the
9961 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9962 ** These must be the low-order bits of the flags field.
9963 */
9964 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9965 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9966 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9967 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9968 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9969 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9970 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9971 #define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9972 #define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
9973 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9974
9975 /*
9976 ** Possible values for the sqlite.magic field.
9977 ** The numbers are obtained at random and have no special meaning, other
9978 ** than being distinct from one another.
9979 */
9980 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9981 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9982 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9983 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9984 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9985 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
9986
9987 /*
9988 ** Each SQL function is defined by an instance of the following
9989 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9990 ** hash table.  When multiple functions have the same name, the hash table
9991 ** points to a linked list of these structures.
9992 */
9993 struct FuncDef {
9994   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9995   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9996   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9997   void *pUserData;     /* User data parameter */
9998   FuncDef *pNext;      /* Next function with same name */
9999   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10000   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10001   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10002   char *zName;         /* SQL name of the function. */
10003   FuncDef *pHash;      /* Next with a different name but the same hash */
10004   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10005 };
10006
10007 /*
10008 ** This structure encapsulates a user-function destructor callback (as
10009 ** configured using create_function_v2()) and a reference counter. When
10010 ** create_function_v2() is called to create a function with a destructor,
10011 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
10012 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10013 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10014 ** member of each of the new FuncDef objects is set to point to the allocated
10015 ** FuncDestructor.
10016 **
10017 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10018 ** count on this object is decremented. When it reaches 0, the destructor
10019 ** is invoked and the FuncDestructor structure freed.
10020 */
10021 struct FuncDestructor {
10022   int nRef;
10023   void (*xDestroy)(void *);
10024   void *pUserData;
10025 };
10026
10027 /*
10028 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10029 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10030 ** are assert() statements in the code to verify this.
10031 */
10032 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10033 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10034 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10035 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10036 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10037 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10038 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10039 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10040
10041 /*
10042 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10043 ** used to create the initializers for the FuncDef structures.
10044 **
10045 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10046 **     Used to create a scalar function definition of a function zName 
10047 **     implemented by C function xFunc that accepts nArg arguments. The
10048 **     value passed as iArg is cast to a (void*) and made available
10049 **     as the user-data (sqlite3_user_data()) for the function. If 
10050 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10051 **
10052 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10053 **     Used to create an aggregate function definition implemented by
10054 **     the C functions xStep and xFinal. The first four parameters
10055 **     are interpreted in the same way as the first 4 parameters to
10056 **     FUNCTION().
10057 **
10058 **   LIKEFUNC(zName, nArg, pArg, flags)
10059 **     Used to create a scalar function definition of a function zName 
10060 **     that accepts nArg arguments and is implemented by a call to C 
10061 **     function likeFunc. Argument pArg is cast to a (void *) and made
10062 **     available as the function user-data (sqlite3_user_data()). The
10063 **     FuncDef.flags variable is set to the value passed as the flags
10064 **     parameter.
10065 */
10066 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10067   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10068    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10069 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10070   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10071    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10072 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10073   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10074    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10075 #define LIKEFUNC(zName, nArg, arg, flags) \
10076   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10077 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10078   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10079    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10080
10081 /*
10082 ** All current savepoints are stored in a linked list starting at
10083 ** sqlite3.pSavepoint. The first element in the list is the most recently
10084 ** opened savepoint. Savepoints are added to the list by the vdbe
10085 ** OP_Savepoint instruction.
10086 */
10087 struct Savepoint {
10088   char *zName;                        /* Savepoint name (nul-terminated) */
10089   i64 nDeferredCons;                  /* Number of deferred fk violations */
10090   Savepoint *pNext;                   /* Parent savepoint (if any) */
10091 };
10092
10093 /*
10094 ** The following are used as the second parameter to sqlite3Savepoint(),
10095 ** and as the P1 argument to the OP_Savepoint instruction.
10096 */
10097 #define SAVEPOINT_BEGIN      0
10098 #define SAVEPOINT_RELEASE    1
10099 #define SAVEPOINT_ROLLBACK   2
10100
10101
10102 /*
10103 ** Each SQLite module (virtual table definition) is defined by an
10104 ** instance of the following structure, stored in the sqlite3.aModule
10105 ** hash table.
10106 */
10107 struct Module {
10108   const sqlite3_module *pModule;       /* Callback pointers */
10109   const char *zName;                   /* Name passed to create_module() */
10110   void *pAux;                          /* pAux passed to create_module() */
10111   void (*xDestroy)(void *);            /* Module destructor function */
10112 };
10113
10114 /*
10115 ** information about each column of an SQL table is held in an instance
10116 ** of this structure.
10117 */
10118 struct Column {
10119   char *zName;     /* Name of this column */
10120   Expr *pDflt;     /* Default value of this column */
10121   char *zDflt;     /* Original text of the default value */
10122   char *zType;     /* Data type for this column */
10123   char *zColl;     /* Collating sequence.  If NULL, use the default */
10124   u8 notNull;      /* True if there is a NOT NULL constraint */
10125   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
10126   char affinity;   /* One of the SQLITE_AFF_... values */
10127 #ifndef SQLITE_OMIT_VIRTUALTABLE
10128   u8 isHidden;     /* True if this column is 'hidden' */
10129 #endif
10130 };
10131
10132 /*
10133 ** A "Collating Sequence" is defined by an instance of the following
10134 ** structure. Conceptually, a collating sequence consists of a name and
10135 ** a comparison routine that defines the order of that sequence.
10136 **
10137 ** There may two separate implementations of the collation function, one
10138 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
10139 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
10140 ** native byte order. When a collation sequence is invoked, SQLite selects
10141 ** the version that will require the least expensive encoding
10142 ** translations, if any.
10143 **
10144 ** The CollSeq.pUser member variable is an extra parameter that passed in
10145 ** as the first argument to the UTF-8 comparison function, xCmp.
10146 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
10147 ** xCmp16.
10148 **
10149 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
10150 ** collating sequence is undefined.  Indices built on an undefined
10151 ** collating sequence may not be read or written.
10152 */
10153 struct CollSeq {
10154   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10155   u8 enc;               /* Text encoding handled by xCmp() */
10156   void *pUser;          /* First argument to xCmp() */
10157   int (*xCmp)(void*,int, const void*, int, const void*);
10158   void (*xDel)(void*);  /* Destructor for pUser */
10159 };
10160
10161 /*
10162 ** A sort order can be either ASC or DESC.
10163 */
10164 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10165 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10166
10167 /*
10168 ** Column affinity types.
10169 **
10170 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10171 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10172 ** the speed a little by numbering the values consecutively.  
10173 **
10174 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10175 ** when multiple affinity types are concatenated into a string and
10176 ** used as the P4 operand, they will be more readable.
10177 **
10178 ** Note also that the numeric types are grouped together so that testing
10179 ** for a numeric type is a single comparison.
10180 */
10181 #define SQLITE_AFF_TEXT     'a'
10182 #define SQLITE_AFF_NONE     'b'
10183 #define SQLITE_AFF_NUMERIC  'c'
10184 #define SQLITE_AFF_INTEGER  'd'
10185 #define SQLITE_AFF_REAL     'e'
10186
10187 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10188
10189 /*
10190 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10191 ** affinity value. 
10192 */
10193 #define SQLITE_AFF_MASK     0x67
10194
10195 /*
10196 ** Additional bit values that can be ORed with an affinity without
10197 ** changing the affinity.
10198 */
10199 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10200 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10201 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10202
10203 /*
10204 ** An object of this type is created for each virtual table present in
10205 ** the database schema. 
10206 **
10207 ** If the database schema is shared, then there is one instance of this
10208 ** structure for each database connection (sqlite3*) that uses the shared
10209 ** schema. This is because each database connection requires its own unique
10210 ** instance of the sqlite3_vtab* handle used to access the virtual table 
10211 ** implementation. sqlite3_vtab* handles can not be shared between 
10212 ** database connections, even when the rest of the in-memory database 
10213 ** schema is shared, as the implementation often stores the database
10214 ** connection handle passed to it via the xConnect() or xCreate() method
10215 ** during initialization internally. This database connection handle may
10216 ** then be used by the virtual table implementation to access real tables 
10217 ** within the database. So that they appear as part of the callers 
10218 ** transaction, these accesses need to be made via the same database 
10219 ** connection as that used to execute SQL operations on the virtual table.
10220 **
10221 ** All VTable objects that correspond to a single table in a shared
10222 ** database schema are initially stored in a linked-list pointed to by
10223 ** the Table.pVTable member variable of the corresponding Table object.
10224 ** When an sqlite3_prepare() operation is required to access the virtual
10225 ** table, it searches the list for the VTable that corresponds to the
10226 ** database connection doing the preparing so as to use the correct
10227 ** sqlite3_vtab* handle in the compiled query.
10228 **
10229 ** When an in-memory Table object is deleted (for example when the
10230 ** schema is being reloaded for some reason), the VTable objects are not 
10231 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
10232 ** immediately. Instead, they are moved from the Table.pVTable list to
10233 ** another linked list headed by the sqlite3.pDisconnect member of the
10234 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
10235 ** next time a statement is prepared using said sqlite3*. This is done
10236 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10237 ** Refer to comments above function sqlite3VtabUnlockList() for an
10238 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10239 ** list without holding the corresponding sqlite3.mutex mutex.
10240 **
10241 ** The memory for objects of this type is always allocated by 
10242 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
10243 ** the first argument.
10244 */
10245 struct VTable {
10246   sqlite3 *db;              /* Database connection associated with this table */
10247   Module *pMod;             /* Pointer to module implementation */
10248   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10249   int nRef;                 /* Number of pointers to this structure */
10250   u8 bConstraint;           /* True if constraints are supported */
10251   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10252   VTable *pNext;            /* Next in linked list (see above) */
10253 };
10254
10255 /*
10256 ** Each SQL table is represented in memory by an instance of the
10257 ** following structure.
10258 **
10259 ** Table.zName is the name of the table.  The case of the original
10260 ** CREATE TABLE statement is stored, but case is not significant for
10261 ** comparisons.
10262 **
10263 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10264 ** pointer to an array of Column structures, one for each column.
10265 **
10266 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10267 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10268 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10269 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10270 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10271 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10272 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10273 **
10274 ** Table.tnum is the page number for the root BTree page of the table in the
10275 ** database file.  If Table.iDb is the index of the database table backend
10276 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10277 ** holds temporary tables and indices.  If TF_Ephemeral is set
10278 ** then the table is stored in a file that is automatically deleted
10279 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
10280 ** refers VDBE cursor number that holds the table open, not to the root
10281 ** page number.  Transient tables are used to hold the results of a
10282 ** sub-query that appears instead of a real table name in the FROM clause 
10283 ** of a SELECT statement.
10284 */
10285 struct Table {
10286   char *zName;         /* Name of the table or view */
10287   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10288   int nCol;            /* Number of columns in this table */
10289   Column *aCol;        /* Information about each column */
10290   Index *pIndex;       /* List of SQL indexes on this table. */
10291   int tnum;            /* Root BTree node for this table (see note above) */
10292   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10293   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10294   u16 nRef;            /* Number of pointers to this Table */
10295   u8 tabFlags;         /* Mask of TF_* values */
10296   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10297   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10298   char *zColAff;       /* String defining the affinity of each column */
10299 #ifndef SQLITE_OMIT_CHECK
10300   ExprList *pCheck;    /* All CHECK constraints */
10301 #endif
10302 #ifndef SQLITE_OMIT_ALTERTABLE
10303   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10304 #endif
10305 #ifndef SQLITE_OMIT_VIRTUALTABLE
10306   VTable *pVTable;     /* List of VTable objects. */
10307   int nModuleArg;      /* Number of arguments to the module */
10308   char **azModuleArg;  /* Text of all module args. [0] is module name */
10309 #endif
10310   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10311   Schema *pSchema;     /* Schema that contains this table */
10312   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10313 };
10314
10315 /*
10316 ** Allowed values for Tabe.tabFlags.
10317 */
10318 #define TF_Readonly        0x01    /* Read-only system table */
10319 #define TF_Ephemeral       0x02    /* An ephemeral table */
10320 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10321 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10322 #define TF_Virtual         0x10    /* Is a virtual table */
10323
10324
10325 /*
10326 ** Test to see whether or not a table is a virtual table.  This is
10327 ** done as a macro so that it will be optimized out when virtual
10328 ** table support is omitted from the build.
10329 */
10330 #ifndef SQLITE_OMIT_VIRTUALTABLE
10331 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10332 #  define IsHiddenColumn(X) ((X)->isHidden)
10333 #else
10334 #  define IsVirtual(X)      0
10335 #  define IsHiddenColumn(X) 0
10336 #endif
10337
10338 /*
10339 ** Each foreign key constraint is an instance of the following structure.
10340 **
10341 ** A foreign key is associated with two tables.  The "from" table is
10342 ** the table that contains the REFERENCES clause that creates the foreign
10343 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10344 ** Consider this example:
10345 **
10346 **     CREATE TABLE ex1(
10347 **       a INTEGER PRIMARY KEY,
10348 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10349 **     );
10350 **
10351 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10352 **
10353 ** Each REFERENCES clause generates an instance of the following structure
10354 ** which is attached to the from-table.  The to-table need not exist when
10355 ** the from-table is created.  The existence of the to-table is not checked.
10356 */
10357 struct FKey {
10358   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10359   FKey *pNextFrom;  /* Next foreign key in pFrom */
10360   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10361   FKey *pNextTo;    /* Next foreign key on table named zTo */
10362   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10363   int nCol;         /* Number of columns in this key */
10364   /* EV: R-30323-21917 */
10365   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10366   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10367   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10368   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10369     int iFrom;         /* Index of column in pFrom */
10370     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10371   } aCol[1];        /* One entry for each of nCol column s */
10372 };
10373
10374 /*
10375 ** SQLite supports many different ways to resolve a constraint
10376 ** error.  ROLLBACK processing means that a constraint violation
10377 ** causes the operation in process to fail and for the current transaction
10378 ** to be rolled back.  ABORT processing means the operation in process
10379 ** fails and any prior changes from that one operation are backed out,
10380 ** but the transaction is not rolled back.  FAIL processing means that
10381 ** the operation in progress stops and returns an error code.  But prior
10382 ** changes due to the same operation are not backed out and no rollback
10383 ** occurs.  IGNORE means that the particular row that caused the constraint
10384 ** error is not inserted or updated.  Processing continues and no error
10385 ** is returned.  REPLACE means that preexisting database rows that caused
10386 ** a UNIQUE constraint violation are removed so that the new insert or
10387 ** update can proceed.  Processing continues and no error is reported.
10388 **
10389 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10390 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10391 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10392 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10393 ** referenced table row is propagated into the row that holds the
10394 ** foreign key.
10395 ** 
10396 ** The following symbolic values are used to record which type
10397 ** of action to take.
10398 */
10399 #define OE_None     0   /* There is no constraint to check */
10400 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10401 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10402 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10403 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10404 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10405
10406 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10407 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10408 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10409 #define OE_Cascade  9   /* Cascade the changes */
10410
10411 #define OE_Default  99  /* Do whatever the default action is */
10412
10413
10414 /*
10415 ** An instance of the following structure is passed as the first
10416 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10417 ** comparison of the two index keys.
10418 */
10419 struct KeyInfo {
10420   sqlite3 *db;        /* The database connection */
10421   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10422   u16 nField;         /* Number of entries in aColl[] */
10423   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10424   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10425 };
10426
10427 /*
10428 ** An instance of the following structure holds information about a
10429 ** single index record that has already been parsed out into individual
10430 ** values.
10431 **
10432 ** A record is an object that contains one or more fields of data.
10433 ** Records are used to store the content of a table row and to store
10434 ** the key of an index.  A blob encoding of a record is created by
10435 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10436 ** OP_Column opcode.
10437 **
10438 ** This structure holds a record that has already been disassembled
10439 ** into its constituent fields.
10440 */
10441 struct UnpackedRecord {
10442   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10443   u16 nField;         /* Number of entries in apMem[] */
10444   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10445   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10446   Mem *aMem;          /* Values */
10447 };
10448
10449 /*
10450 ** Allowed values of UnpackedRecord.flags
10451 */
10452 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10453 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10454 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10455
10456 /*
10457 ** Each SQL index is represented in memory by an
10458 ** instance of the following structure.
10459 **
10460 ** The columns of the table that are to be indexed are described
10461 ** by the aiColumn[] field of this structure.  For example, suppose
10462 ** we have the following table and index:
10463 **
10464 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10465 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10466 **
10467 ** In the Table structure describing Ex1, nCol==3 because there are
10468 ** three columns in the table.  In the Index structure describing
10469 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10470 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10471 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10472 ** The second column to be indexed (c1) has an index of 0 in
10473 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10474 **
10475 ** The Index.onError field determines whether or not the indexed columns
10476 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10477 ** it means this is not a unique index.  Otherwise it is a unique index
10478 ** and the value of Index.onError indicate the which conflict resolution 
10479 ** algorithm to employ whenever an attempt is made to insert a non-unique
10480 ** element.
10481 */
10482 struct Index {
10483   char *zName;     /* Name of this index */
10484   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10485   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10486   Table *pTable;   /* The SQL table being indexed */
10487   char *zColAff;   /* String defining the affinity of each column */
10488   Index *pNext;    /* The next index associated with the same table */
10489   Schema *pSchema; /* Schema containing this index */
10490   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10491   char **azColl;   /* Array of collation sequence names for index */
10492   int nColumn;     /* Number of columns in the table used by this index */
10493   int tnum;        /* Page containing root of this index in database file */
10494   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10495   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10496   u8 bUnordered;   /* Use this index for == or IN queries only */
10497 #ifdef SQLITE_ENABLE_STAT3
10498   int nSample;             /* Number of elements in aSample[] */
10499   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10500   IndexSample *aSample;    /* Samples of the left-most key */
10501 #endif
10502 };
10503
10504 /*
10505 ** Each sample stored in the sqlite_stat3 table is represented in memory 
10506 ** using a structure of this type.  See documentation at the top of the
10507 ** analyze.c source file for additional information.
10508 */
10509 struct IndexSample {
10510   union {
10511     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10512     double r;       /* Value if eType is SQLITE_FLOAT */
10513     i64 i;          /* Value if eType is SQLITE_INTEGER */
10514   } u;
10515   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10516   int nByte;        /* Size in byte of text or blob. */
10517   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10518   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10519   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10520 };
10521
10522 /*
10523 ** Each token coming out of the lexer is an instance of
10524 ** this structure.  Tokens are also used as part of an expression.
10525 **
10526 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10527 ** may contain random values.  Do not make any assumptions about Token.dyn
10528 ** and Token.n when Token.z==0.
10529 */
10530 struct Token {
10531   const char *z;     /* Text of the token.  Not NULL-terminated! */
10532   unsigned int n;    /* Number of characters in this token */
10533 };
10534
10535 /*
10536 ** An instance of this structure contains information needed to generate
10537 ** code for a SELECT that contains aggregate functions.
10538 **
10539 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10540 ** pointer to this structure.  The Expr.iColumn field is the index in
10541 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10542 ** code for that node.
10543 **
10544 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10545 ** original Select structure that describes the SELECT statement.  These
10546 ** fields do not need to be freed when deallocating the AggInfo structure.
10547 */
10548 struct AggInfo {
10549   u8 directMode;          /* Direct rendering mode means take data directly
10550                           ** from source tables rather than from accumulators */
10551   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10552                           ** than the source table */
10553   int sortingIdx;         /* Cursor number of the sorting index */
10554   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10555   int nSortingColumn;     /* Number of columns in the sorting index */
10556   ExprList *pGroupBy;     /* The group by clause */
10557   struct AggInfo_col {    /* For each column used in source tables */
10558     Table *pTab;             /* Source table */
10559     int iTable;              /* Cursor number of the source table */
10560     int iColumn;             /* Column number within the source table */
10561     int iSorterColumn;       /* Column number in the sorting index */
10562     int iMem;                /* Memory location that acts as accumulator */
10563     Expr *pExpr;             /* The original expression */
10564   } *aCol;
10565   int nColumn;            /* Number of used entries in aCol[] */
10566   int nAccumulator;       /* Number of columns that show through to the output.
10567                           ** Additional columns are used only as parameters to
10568                           ** aggregate functions */
10569   struct AggInfo_func {   /* For each aggregate function */
10570     Expr *pExpr;             /* Expression encoding the function */
10571     FuncDef *pFunc;          /* The aggregate function implementation */
10572     int iMem;                /* Memory location that acts as accumulator */
10573     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10574   } *aFunc;
10575   int nFunc;              /* Number of entries in aFunc[] */
10576 };
10577
10578 /*
10579 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10580 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10581 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10582 ** it uses less memory in the Expr object, which is a big memory user
10583 ** in systems with lots of prepared statements.  And few applications
10584 ** need more than about 10 or 20 variables.  But some extreme users want
10585 ** to have prepared statements with over 32767 variables, and for them
10586 ** the option is available (at compile-time).
10587 */
10588 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10589 typedef i16 ynVar;
10590 #else
10591 typedef int ynVar;
10592 #endif
10593
10594 /*
10595 ** Each node of an expression in the parse tree is an instance
10596 ** of this structure.
10597 **
10598 ** Expr.op is the opcode. The integer parser token codes are reused
10599 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10600 ** code representing the ">=" operator. This same integer code is reused
10601 ** to represent the greater-than-or-equal-to operator in the expression
10602 ** tree.
10603 **
10604 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10605 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10606 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10607 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10608 ** then Expr.token contains the name of the function.
10609 **
10610 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10611 ** binary operator. Either or both may be NULL.
10612 **
10613 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10614 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10615 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10616 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10617 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10618 ** valid.
10619 **
10620 ** An expression of the form ID or ID.ID refers to a column in a table.
10621 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10622 ** the integer cursor number of a VDBE cursor pointing to that table and
10623 ** Expr.iColumn is the column number for the specific column.  If the
10624 ** expression is used as a result in an aggregate SELECT, then the
10625 ** value is also stored in the Expr.iAgg column in the aggregate so that
10626 ** it can be accessed after all aggregates are computed.
10627 **
10628 ** If the expression is an unbound variable marker (a question mark 
10629 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10630 ** number for that variable.
10631 **
10632 ** If the expression is a subquery then Expr.iColumn holds an integer
10633 ** register number containing the result of the subquery.  If the
10634 ** subquery gives a constant result, then iTable is -1.  If the subquery
10635 ** gives a different answer at different times during statement processing
10636 ** then iTable is the address of a subroutine that computes the subquery.
10637 **
10638 ** If the Expr is of type OP_Column, and the table it is selecting from
10639 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10640 ** corresponding table definition.
10641 **
10642 ** ALLOCATION NOTES:
10643 **
10644 ** Expr objects can use a lot of memory space in database schema.  To
10645 ** help reduce memory requirements, sometimes an Expr object will be
10646 ** truncated.  And to reduce the number of memory allocations, sometimes
10647 ** two or more Expr objects will be stored in a single memory allocation,
10648 ** together with Expr.zToken strings.
10649 **
10650 ** If the EP_Reduced and EP_TokenOnly flags are set when
10651 ** an Expr object is truncated.  When EP_Reduced is set, then all
10652 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10653 ** are contained within the same memory allocation.  Note, however, that
10654 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10655 ** allocated, regardless of whether or not EP_Reduced is set.
10656 */
10657 struct Expr {
10658   u8 op;                 /* Operation performed by this node */
10659   char affinity;         /* The affinity of the column or 0 if not a column */
10660   u16 flags;             /* Various flags.  EP_* See below */
10661   union {
10662     char *zToken;          /* Token value. Zero terminated and dequoted */
10663     int iValue;            /* Non-negative integer value if EP_IntValue */
10664   } u;
10665
10666   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10667   ** space is allocated for the fields below this point. An attempt to
10668   ** access them will result in a segfault or malfunction. 
10669   *********************************************************************/
10670
10671   Expr *pLeft;           /* Left subnode */
10672   Expr *pRight;          /* Right subnode */
10673   union {
10674     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10675     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10676   } x;
10677   CollSeq *pColl;        /* The collation type of the column or 0 */
10678
10679   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10680   ** space is allocated for the fields below this point. An attempt to
10681   ** access them will result in a segfault or malfunction.
10682   *********************************************************************/
10683
10684   int iTable;            /* TK_COLUMN: cursor number of table holding column
10685                          ** TK_REGISTER: register number
10686                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10687   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10688                          ** TK_VARIABLE: variable number (always >= 1). */
10689   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10690   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10691   u8 flags2;             /* Second set of flags.  EP2_... */
10692   u8 op2;                /* TK_REGISTER: original value of Expr.op
10693                          ** TK_COLUMN: the value of p5 for OP_Column
10694                          ** TK_AGG_FUNCTION: nesting depth */
10695   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10696   Table *pTab;           /* Table for TK_COLUMN expressions. */
10697 #if SQLITE_MAX_EXPR_DEPTH>0
10698   int nHeight;           /* Height of the tree headed by this node */
10699 #endif
10700 };
10701
10702 /*
10703 ** The following are the meanings of bits in the Expr.flags field.
10704 */
10705 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10706 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10707 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10708 #define EP_Error      0x0008  /* Expression contains one or more errors */
10709 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10710 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10711 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10712 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10713 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10714 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10715 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10716 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10717 #define EP_Hint       0x1000  /* Not used */
10718 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10719 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10720 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10721
10722 /*
10723 ** The following are the meanings of bits in the Expr.flags2 field.
10724 */
10725 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10726 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10727
10728 /*
10729 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10730 ** flag on an expression structure.  This flag is used for VV&A only.  The
10731 ** routine is implemented as a macro that only works when in debugging mode,
10732 ** so as not to burden production code.
10733 */
10734 #ifdef SQLITE_DEBUG
10735 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10736 #else
10737 # define ExprSetIrreducible(X)
10738 #endif
10739
10740 /*
10741 ** These macros can be used to test, set, or clear bits in the 
10742 ** Expr.flags field.
10743 */
10744 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10745 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10746 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10747 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10748
10749 /*
10750 ** Macros to determine the number of bytes required by a normal Expr 
10751 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10752 ** and an Expr struct with the EP_TokenOnly flag set.
10753 */
10754 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10755 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10756 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10757
10758 /*
10759 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10760 ** above sqlite3ExprDup() for details.
10761 */
10762 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10763
10764 /*
10765 ** A list of expressions.  Each expression may optionally have a
10766 ** name.  An expr/name combination can be used in several ways, such
10767 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10768 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10769 ** also be used as the argument to a function, in which case the a.zName
10770 ** field is not used.
10771 */
10772 struct ExprList {
10773   int nExpr;             /* Number of expressions on the list */
10774   int iECursor;          /* VDBE Cursor associated with this ExprList */
10775   struct ExprList_item { /* For each expression in the list */
10776     Expr *pExpr;           /* The list of expressions */
10777     char *zName;           /* Token associated with this expression */
10778     char *zSpan;           /* Original text of the expression */
10779     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10780     u8 done;               /* A flag to indicate when processing is finished */
10781     u16 iOrderByCol;       /* For ORDER BY, column number in result set */
10782     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10783   } *a;                  /* Alloc a power of two greater or equal to nExpr */
10784 };
10785
10786 /*
10787 ** An instance of this structure is used by the parser to record both
10788 ** the parse tree for an expression and the span of input text for an
10789 ** expression.
10790 */
10791 struct ExprSpan {
10792   Expr *pExpr;          /* The expression parse tree */
10793   const char *zStart;   /* First character of input text */
10794   const char *zEnd;     /* One character past the end of input text */
10795 };
10796
10797 /*
10798 ** An instance of this structure can hold a simple list of identifiers,
10799 ** such as the list "a,b,c" in the following statements:
10800 **
10801 **      INSERT INTO t(a,b,c) VALUES ...;
10802 **      CREATE INDEX idx ON t(a,b,c);
10803 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10804 **
10805 ** The IdList.a.idx field is used when the IdList represents the list of
10806 ** column names after a table name in an INSERT statement.  In the statement
10807 **
10808 **     INSERT INTO t(a,b,c) ...
10809 **
10810 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10811 */
10812 struct IdList {
10813   struct IdList_item {
10814     char *zName;      /* Name of the identifier */
10815     int idx;          /* Index in some Table.aCol[] of a column named zName */
10816   } *a;
10817   int nId;         /* Number of identifiers on the list */
10818 };
10819
10820 /*
10821 ** The bitmask datatype defined below is used for various optimizations.
10822 **
10823 ** Changing this from a 64-bit to a 32-bit type limits the number of
10824 ** tables in a join to 32 instead of 64.  But it also reduces the size
10825 ** of the library by 738 bytes on ix86.
10826 */
10827 typedef u64 Bitmask;
10828
10829 /*
10830 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10831 */
10832 #define BMS  ((int)(sizeof(Bitmask)*8))
10833
10834 /*
10835 ** The following structure describes the FROM clause of a SELECT statement.
10836 ** Each table or subquery in the FROM clause is a separate element of
10837 ** the SrcList.a[] array.
10838 **
10839 ** With the addition of multiple database support, the following structure
10840 ** can also be used to describe a particular table such as the table that
10841 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10842 ** such a table must be a simple name: ID.  But in SQLite, the table can
10843 ** now be identified by a database name, a dot, then the table name: ID.ID.
10844 **
10845 ** The jointype starts out showing the join type between the current table
10846 ** and the next table on the list.  The parser builds the list this way.
10847 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10848 ** jointype expresses the join between the table and the previous table.
10849 **
10850 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10851 ** contains more than 63 columns and the 64-th or later column is used.
10852 */
10853 struct SrcList {
10854   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10855   i16 nAlloc;      /* Number of entries allocated in a[] below */
10856   struct SrcList_item {
10857     char *zDatabase;  /* Name of database holding this table */
10858     char *zName;      /* Name of the table */
10859     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10860     Table *pTab;      /* An SQL table corresponding to zName */
10861     Select *pSelect;  /* A SELECT statement used in place of a table name */
10862     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10863     int regReturn;    /* Register holding return address of addrFillSub */
10864     u8 jointype;      /* Type of join between this able and the previous */
10865     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10866     u8 isCorrelated;  /* True if sub-query is correlated */
10867 #ifndef SQLITE_OMIT_EXPLAIN
10868     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10869 #endif
10870     int iCursor;      /* The VDBE cursor number used to access this table */
10871     Expr *pOn;        /* The ON clause of a join */
10872     IdList *pUsing;   /* The USING clause of a join */
10873     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10874     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10875     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10876   } a[1];             /* One entry for each identifier on the list */
10877 };
10878
10879 /*
10880 ** Permitted values of the SrcList.a.jointype field
10881 */
10882 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10883 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10884 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10885 #define JT_LEFT      0x0008    /* Left outer join */
10886 #define JT_RIGHT     0x0010    /* Right outer join */
10887 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10888 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10889
10890
10891 /*
10892 ** A WherePlan object holds information that describes a lookup
10893 ** strategy.
10894 **
10895 ** This object is intended to be opaque outside of the where.c module.
10896 ** It is included here only so that that compiler will know how big it
10897 ** is.  None of the fields in this object should be used outside of
10898 ** the where.c module.
10899 **
10900 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10901 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10902 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10903 ** case that more than one of these conditions is true.
10904 */
10905 struct WherePlan {
10906   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10907   u32 nEq;                       /* Number of == constraints */
10908   double nRow;                   /* Estimated number of rows (for EQP) */
10909   union {
10910     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10911     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10912     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10913   } u;
10914 };
10915
10916 /*
10917 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10918 ** structure contains a single instance of this structure.  This structure
10919 ** is intended to be private to the where.c module and should not be
10920 ** access or modified by other modules.
10921 **
10922 ** The pIdxInfo field is used to help pick the best index on a
10923 ** virtual table.  The pIdxInfo pointer contains indexing
10924 ** information for the i-th table in the FROM clause before reordering.
10925 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10926 ** All other information in the i-th WhereLevel object for the i-th table
10927 ** after FROM clause ordering.
10928 */
10929 struct WhereLevel {
10930   WherePlan plan;       /* query plan for this element of the FROM clause */
10931   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10932   int iTabCur;          /* The VDBE cursor used to access the table */
10933   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10934   int addrBrk;          /* Jump here to break out of the loop */
10935   int addrNxt;          /* Jump here to start the next IN combination */
10936   int addrCont;         /* Jump here to continue with the next loop cycle */
10937   int addrFirst;        /* First instruction of interior of the loop */
10938   u8 iFrom;             /* Which entry in the FROM clause */
10939   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10940   int p1, p2;           /* Operands of the opcode used to ends the loop */
10941   union {               /* Information that depends on plan.wsFlags */
10942     struct {
10943       int nIn;              /* Number of entries in aInLoop[] */
10944       struct InLoop {
10945         int iCur;              /* The VDBE cursor used by this IN operator */
10946         int addrInTop;         /* Top of the IN loop */
10947       } *aInLoop;           /* Information about each nested IN operator */
10948     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10949     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
10950   } u;
10951
10952   /* The following field is really not part of the current level.  But
10953   ** we need a place to cache virtual table index information for each
10954   ** virtual table in the FROM clause and the WhereLevel structure is
10955   ** a convenient place since there is one WhereLevel for each FROM clause
10956   ** element.
10957   */
10958   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10959 };
10960
10961 /*
10962 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10963 ** and the WhereInfo.wctrlFlags member.
10964 */
10965 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10966 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10967 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10968 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10969 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10970 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10971 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10972 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10973 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10974
10975 /*
10976 ** The WHERE clause processing routine has two halves.  The
10977 ** first part does the start of the WHERE loop and the second
10978 ** half does the tail of the WHERE loop.  An instance of
10979 ** this structure is returned by the first half and passed
10980 ** into the second half to give some continuity.
10981 */
10982 struct WhereInfo {
10983   Parse *pParse;       /* Parsing and code generating context */
10984   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10985   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10986   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10987   u8 eDistinct;
10988   SrcList *pTabList;             /* List of tables in the join */
10989   int iTop;                      /* The very beginning of the WHERE loop */
10990   int iContinue;                 /* Jump here to continue with next record */
10991   int iBreak;                    /* Jump here to break out of the loop */
10992   int nLevel;                    /* Number of nested loop */
10993   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10994   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10995   double nRowOut;                /* Estimated number of output rows */
10996   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10997 };
10998
10999 #define WHERE_DISTINCT_UNIQUE 1
11000 #define WHERE_DISTINCT_ORDERED 2
11001
11002 /*
11003 ** A NameContext defines a context in which to resolve table and column
11004 ** names.  The context consists of a list of tables (the pSrcList) field and
11005 ** a list of named expression (pEList).  The named expression list may
11006 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11007 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11008 ** pEList corresponds to the result set of a SELECT and is NULL for
11009 ** other statements.
11010 **
11011 ** NameContexts can be nested.  When resolving names, the inner-most 
11012 ** context is searched first.  If no match is found, the next outer
11013 ** context is checked.  If there is still no match, the next context
11014 ** is checked.  This process continues until either a match is found
11015 ** or all contexts are check.  When a match is found, the nRef member of
11016 ** the context containing the match is incremented. 
11017 **
11018 ** Each subquery gets a new NameContext.  The pNext field points to the
11019 ** NameContext in the parent query.  Thus the process of scanning the
11020 ** NameContext list corresponds to searching through successively outer
11021 ** subqueries looking for a match.
11022 */
11023 struct NameContext {
11024   Parse *pParse;       /* The parser */
11025   SrcList *pSrcList;   /* One or more tables used to resolve names */
11026   ExprList *pEList;    /* Optional list of named expressions */
11027   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11028   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11029   int nRef;            /* Number of names resolved by this context */
11030   int nErr;            /* Number of errors encountered while resolving names */
11031   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11032 };
11033
11034 /*
11035 ** Allowed values for the NameContext, ncFlags field.
11036 */
11037 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11038 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11039 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11040 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11041
11042 /*
11043 ** An instance of the following structure contains all information
11044 ** needed to generate code for a single SELECT statement.
11045 **
11046 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11047 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11048 ** limit and nOffset to the value of the offset (or 0 if there is not
11049 ** offset).  But later on, nLimit and nOffset become the memory locations
11050 ** in the VDBE that record the limit and offset counters.
11051 **
11052 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11053 ** These addresses must be stored so that we can go back and fill in
11054 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11055 ** the number of columns in P2 can be computed at the same time
11056 ** as the OP_OpenEphm instruction is coded because not
11057 ** enough information about the compound query is known at that point.
11058 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11059 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
11060 ** sequences for the ORDER BY clause.
11061 */
11062 struct Select {
11063   ExprList *pEList;      /* The fields of the result */
11064   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11065   char affinity;         /* MakeRecord with this affinity for SRT_Set */
11066   u16 selFlags;          /* Various SF_* values */
11067   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11068   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11069   double nSelectRow;     /* Estimated number of result rows */
11070   SrcList *pSrc;         /* The FROM clause */
11071   Expr *pWhere;          /* The WHERE clause */
11072   ExprList *pGroupBy;    /* The GROUP BY clause */
11073   Expr *pHaving;         /* The HAVING clause */
11074   ExprList *pOrderBy;    /* The ORDER BY clause */
11075   Select *pPrior;        /* Prior select in a compound select statement */
11076   Select *pNext;         /* Next select to the left in a compound */
11077   Select *pRightmost;    /* Right-most select in a compound select statement */
11078   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11079   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11080 };
11081
11082 /*
11083 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11084 ** "Select Flag".
11085 */
11086 #define SF_Distinct        0x01  /* Output should be DISTINCT */
11087 #define SF_Resolved        0x02  /* Identifiers have been resolved */
11088 #define SF_Aggregate       0x04  /* Contains aggregate functions */
11089 #define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */
11090 #define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */
11091 #define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */
11092 #define SF_UseSorter       0x40  /* Sort using a sorter */
11093 #define SF_Values          0x80  /* Synthesized from VALUES clause */
11094
11095
11096 /*
11097 ** The results of a select can be distributed in several ways.  The
11098 ** "SRT" prefix means "SELECT Result Type".
11099 */
11100 #define SRT_Union        1  /* Store result as keys in an index */
11101 #define SRT_Except       2  /* Remove result from a UNION index */
11102 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11103 #define SRT_Discard      4  /* Do not save the results anywhere */
11104
11105 /* The ORDER BY clause is ignored for all of the above */
11106 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11107
11108 #define SRT_Output       5  /* Output each row of result */
11109 #define SRT_Mem          6  /* Store result in a memory cell */
11110 #define SRT_Set          7  /* Store results as keys in an index */
11111 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11112 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11113 #define SRT_Coroutine   10  /* Generate a single row of result */
11114
11115 /*
11116 ** A structure used to customize the behavior of sqlite3Select(). See
11117 ** comments above sqlite3Select() for details.
11118 */
11119 typedef struct SelectDest SelectDest;
11120 struct SelectDest {
11121   u8 eDest;         /* How to dispose of the results */
11122   u8 affSdst;       /* Affinity used when eDest==SRT_Set */
11123   int iSDParm;      /* A parameter used by the eDest disposal method */
11124   int iSdst;        /* Base register where results are written */
11125   int nSdst;        /* Number of registers allocated */
11126 };
11127
11128 /*
11129 ** During code generation of statements that do inserts into AUTOINCREMENT 
11130 ** tables, the following information is attached to the Table.u.autoInc.p
11131 ** pointer of each autoincrement table to record some side information that
11132 ** the code generator needs.  We have to keep per-table autoincrement
11133 ** information in case inserts are down within triggers.  Triggers do not
11134 ** normally coordinate their activities, but we do need to coordinate the
11135 ** loading and saving of autoincrement information.
11136 */
11137 struct AutoincInfo {
11138   AutoincInfo *pNext;   /* Next info block in a list of them all */
11139   Table *pTab;          /* Table this info block refers to */
11140   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11141   int regCtr;           /* Memory register holding the rowid counter */
11142 };
11143
11144 /*
11145 ** Size of the column cache
11146 */
11147 #ifndef SQLITE_N_COLCACHE
11148 # define SQLITE_N_COLCACHE 10
11149 #endif
11150
11151 /*
11152 ** At least one instance of the following structure is created for each 
11153 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11154 ** statement. All such objects are stored in the linked list headed at
11155 ** Parse.pTriggerPrg and deleted once statement compilation has been
11156 ** completed.
11157 **
11158 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11159 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11160 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11161 ** The Parse.pTriggerPrg list never contains two entries with the same
11162 ** values for both pTrigger and orconf.
11163 **
11164 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11165 ** accessed (or set to 0 for triggers fired as a result of INSERT 
11166 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11167 ** a mask of new.* columns used by the program.
11168 */
11169 struct TriggerPrg {
11170   Trigger *pTrigger;      /* Trigger this program was coded from */
11171   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11172   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11173   int orconf;             /* Default ON CONFLICT policy */
11174   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11175 };
11176
11177 /*
11178 ** The yDbMask datatype for the bitmask of all attached databases.
11179 */
11180 #if SQLITE_MAX_ATTACHED>30
11181   typedef sqlite3_uint64 yDbMask;
11182 #else
11183   typedef unsigned int yDbMask;
11184 #endif
11185
11186 /*
11187 ** An SQL parser context.  A copy of this structure is passed through
11188 ** the parser and down into all the parser action routine in order to
11189 ** carry around information that is global to the entire parse.
11190 **
11191 ** The structure is divided into two parts.  When the parser and code
11192 ** generate call themselves recursively, the first part of the structure
11193 ** is constant but the second part is reset at the beginning and end of
11194 ** each recursion.
11195 **
11196 ** The nTableLock and aTableLock variables are only used if the shared-cache 
11197 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11198 ** used to store the set of table-locks required by the statement being
11199 ** compiled. Function sqlite3TableLock() is used to add entries to the
11200 ** list.
11201 */
11202 struct Parse {
11203   sqlite3 *db;         /* The main database structure */
11204   char *zErrMsg;       /* An error message */
11205   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11206   int rc;              /* Return code from execution */
11207   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11208   u8 checkSchema;      /* Causes schema cookie check after an error */
11209   u8 nested;           /* Number of nested calls to the parser/code generator */
11210   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11211   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11212   u8 nColCache;        /* Number of entries in aColCache[] */
11213   u8 iColCache;        /* Next entry in aColCache[] to replace */
11214   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11215   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11216   int aTempReg[8];     /* Holding area for temporary registers */
11217   int nRangeReg;       /* Size of the temporary register block */
11218   int iRangeReg;       /* First register in temporary register block */
11219   int nErr;            /* Number of errors seen */
11220   int nTab;            /* Number of previously allocated VDBE cursors */
11221   int nMem;            /* Number of memory cells used so far */
11222   int nSet;            /* Number of sets used so far */
11223   int nOnce;           /* Number of OP_Once instructions so far */
11224   int ckBase;          /* Base register of data during check constraints */
11225   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11226   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11227   struct yColCache {
11228     int iTable;           /* Table cursor number */
11229     int iColumn;          /* Table column number */
11230     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11231     int iLevel;           /* Nesting level */
11232     int iReg;             /* Reg with value of this column. 0 means none. */
11233     int lru;              /* Least recently used entry has the smallest value */
11234   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11235   yDbMask writeMask;   /* Start a write transaction on these databases */
11236   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11237   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11238   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11239   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11240   int regRoot;         /* Register holding root page number for new objects */
11241   int nMaxArg;         /* Max args passed to user function by sub-program */
11242   Token constraintName;/* Name of the constraint currently being parsed */
11243 #ifndef SQLITE_OMIT_SHARED_CACHE
11244   int nTableLock;        /* Number of locks in aTableLock */
11245   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11246 #endif
11247   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11248
11249   /* Information used while coding trigger programs. */
11250   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11251   Table *pTriggerTab;  /* Table triggers are being coded for */
11252   double nQueryLoop;   /* Estimated number of iterations of a query */
11253   u32 oldmask;         /* Mask of old.* columns referenced */
11254   u32 newmask;         /* Mask of new.* columns referenced */
11255   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11256   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11257   u8 disableTriggers;  /* True to disable triggers */
11258
11259   /* Above is constant between recursions.  Below is reset before and after
11260   ** each recursion */
11261
11262   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11263   int nzVar;                /* Number of available slots in azVar[] */
11264   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11265 #ifndef SQLITE_OMIT_VIRTUALTABLE
11266   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11267   int nVtabLock;            /* Number of virtual tables to lock */
11268 #endif
11269   int nAlias;               /* Number of aliased result set columns */
11270   int nHeight;              /* Expression tree height of current sub-select */
11271 #ifndef SQLITE_OMIT_EXPLAIN
11272   int iSelectId;            /* ID of current select for EXPLAIN output */
11273   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11274 #endif
11275   char **azVar;             /* Pointers to names of parameters */
11276   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11277   int *aAlias;              /* Register used to hold aliased result */
11278   const char *zTail;        /* All SQL text past the last semicolon parsed */
11279   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11280   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11281   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11282   Token sNameToken;         /* Token with unqualified schema object name */
11283   Token sLastToken;         /* The last token parsed */
11284 #ifndef SQLITE_OMIT_VIRTUALTABLE
11285   Token sArg;               /* Complete text of a module argument */
11286   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11287 #endif
11288   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11289   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11290 };
11291
11292 /*
11293 ** Return true if currently inside an sqlite3_declare_vtab() call.
11294 */
11295 #ifdef SQLITE_OMIT_VIRTUALTABLE
11296   #define IN_DECLARE_VTAB 0
11297 #else
11298   #define IN_DECLARE_VTAB (pParse->declareVtab)
11299 #endif
11300
11301 /*
11302 ** An instance of the following structure can be declared on a stack and used
11303 ** to save the Parse.zAuthContext value so that it can be restored later.
11304 */
11305 struct AuthContext {
11306   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11307   Parse *pParse;              /* The Parse structure */
11308 };
11309
11310 /*
11311 ** Bitfield flags for P5 value in various opcodes.
11312 */
11313 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11314 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11315 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11316 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11317 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11318 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11319 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11320 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11321 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11322 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11323
11324 /*
11325  * Each trigger present in the database schema is stored as an instance of
11326  * struct Trigger. 
11327  *
11328  * Pointers to instances of struct Trigger are stored in two ways.
11329  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
11330  *    database). This allows Trigger structures to be retrieved by name.
11331  * 2. All triggers associated with a single table form a linked list, using the
11332  *    pNext member of struct Trigger. A pointer to the first element of the
11333  *    linked list is stored as the "pTrigger" member of the associated
11334  *    struct Table.
11335  *
11336  * The "step_list" member points to the first element of a linked list
11337  * containing the SQL statements specified as the trigger program.
11338  */
11339 struct Trigger {
11340   char *zName;            /* The name of the trigger                        */
11341   char *table;            /* The table or view to which the trigger applies */
11342   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11343   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11344   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11345   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11346                              the <column-list> is stored here */
11347   Schema *pSchema;        /* Schema containing the trigger */
11348   Schema *pTabSchema;     /* Schema containing the table */
11349   TriggerStep *step_list; /* Link list of trigger program steps             */
11350   Trigger *pNext;         /* Next trigger associated with the table */
11351 };
11352
11353 /*
11354 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11355 ** determine which. 
11356 **
11357 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11358 ** In that cases, the constants below can be ORed together.
11359 */
11360 #define TRIGGER_BEFORE  1
11361 #define TRIGGER_AFTER   2
11362
11363 /*
11364  * An instance of struct TriggerStep is used to store a single SQL statement
11365  * that is a part of a trigger-program. 
11366  *
11367  * Instances of struct TriggerStep are stored in a singly linked list (linked
11368  * using the "pNext" member) referenced by the "step_list" member of the 
11369  * associated struct Trigger instance. The first element of the linked list is
11370  * the first step of the trigger-program.
11371  * 
11372  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11373  * "SELECT" statement. The meanings of the other members is determined by the 
11374  * value of "op" as follows:
11375  *
11376  * (op == TK_INSERT)
11377  * orconf    -> stores the ON CONFLICT algorithm
11378  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11379  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11380  * target    -> A token holding the quoted name of the table to insert into.
11381  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11382  *              this stores values to be inserted. Otherwise NULL.
11383  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11384  *              statement, then this stores the column-names to be
11385  *              inserted into.
11386  *
11387  * (op == TK_DELETE)
11388  * target    -> A token holding the quoted name of the table to delete from.
11389  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11390  *              Otherwise NULL.
11391  * 
11392  * (op == TK_UPDATE)
11393  * target    -> A token holding the quoted name of the table to update rows of.
11394  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11395  *              Otherwise NULL.
11396  * pExprList -> A list of the columns to update and the expressions to update
11397  *              them to. See sqlite3Update() documentation of "pChanges"
11398  *              argument.
11399  * 
11400  */
11401 struct TriggerStep {
11402   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11403   u8 orconf;           /* OE_Rollback etc. */
11404   Trigger *pTrig;      /* The trigger that this step is a part of */
11405   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11406   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11407   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11408   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11409   IdList *pIdList;     /* Column names for INSERT */
11410   TriggerStep *pNext;  /* Next in the link-list */
11411   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11412 };
11413
11414 /*
11415 ** The following structure contains information used by the sqliteFix...
11416 ** routines as they walk the parse tree to make database references
11417 ** explicit.  
11418 */
11419 typedef struct DbFixer DbFixer;
11420 struct DbFixer {
11421   Parse *pParse;      /* The parsing context.  Error messages written here */
11422   const char *zDb;    /* Make sure all objects are contained in this database */
11423   const char *zType;  /* Type of the container - used for error messages */
11424   const Token *pName; /* Name of the container - used for error messages */
11425 };
11426
11427 /*
11428 ** An objected used to accumulate the text of a string where we
11429 ** do not necessarily know how big the string will be in the end.
11430 */
11431 struct StrAccum {
11432   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11433   char *zBase;         /* A base allocation.  Not from malloc. */
11434   char *zText;         /* The string collected so far */
11435   int  nChar;          /* Length of the string so far */
11436   int  nAlloc;         /* Amount of space allocated in zText */
11437   int  mxAlloc;        /* Maximum allowed string length */
11438   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11439   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11440   u8   tooBig;         /* Becomes true if string size exceeds limits */
11441 };
11442
11443 /*
11444 ** A pointer to this structure is used to communicate information
11445 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11446 */
11447 typedef struct {
11448   sqlite3 *db;        /* The database being initialized */
11449   char **pzErrMsg;    /* Error message stored here */
11450   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11451   int rc;             /* Result code stored here */
11452 } InitData;
11453
11454 /*
11455 ** Structure containing global configuration data for the SQLite library.
11456 **
11457 ** This structure also contains some state information.
11458 */
11459 struct Sqlite3Config {
11460   int bMemstat;                     /* True to enable memory status */
11461   int bCoreMutex;                   /* True to enable core mutexing */
11462   int bFullMutex;                   /* True to enable full mutexing */
11463   int bOpenUri;                     /* True to interpret filenames as URIs */
11464   int mxStrlen;                     /* Maximum string length */
11465   int szLookaside;                  /* Default lookaside buffer size */
11466   int nLookaside;                   /* Default lookaside buffer count */
11467   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11468   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11469   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11470   void *pHeap;                      /* Heap storage space */
11471   int nHeap;                        /* Size of pHeap[] */
11472   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11473   void *pScratch;                   /* Scratch memory */
11474   int szScratch;                    /* Size of each scratch buffer */
11475   int nScratch;                     /* Number of scratch buffers */
11476   void *pPage;                      /* Page cache memory */
11477   int szPage;                       /* Size of each page in pPage[] */
11478   int nPage;                        /* Number of pages in pPage[] */
11479   int mxParserStack;                /* maximum depth of the parser stack */
11480   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11481   /* The above might be initialized to non-zero.  The following need to always
11482   ** initially be zero, however. */
11483   int isInit;                       /* True after initialization has finished */
11484   int inProgress;                   /* True while initialization in progress */
11485   int isMutexInit;                  /* True after mutexes are initialized */
11486   int isMallocInit;                 /* True after malloc is initialized */
11487   int isPCacheInit;                 /* True after malloc is initialized */
11488   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11489   int nRefInitMutex;                /* Number of users of pInitMutex */
11490   void (*xLog)(void*,int,const char*); /* Function for logging */
11491   void *pLogArg;                       /* First argument to xLog() */
11492   int bLocaltimeFault;              /* True to fail localtime() calls */
11493 };
11494
11495 /*
11496 ** Context pointer passed down through the tree-walk.
11497 */
11498 struct Walker {
11499   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11500   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11501   Parse *pParse;                            /* Parser context.  */
11502   int walkerDepth;                          /* Number of subqueries */
11503   union {                                   /* Extra data for callback */
11504     NameContext *pNC;                          /* Naming context */
11505     int i;                                     /* Integer value */
11506     SrcList *pSrcList;                         /* FROM clause */
11507     struct SrcCount *pSrcCount;                /* Counting column references */
11508   } u;
11509 };
11510
11511 /* Forward declarations */
11512 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11513 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11514 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11515 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11516 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11517
11518 /*
11519 ** Return code from the parse-tree walking primitives and their
11520 ** callbacks.
11521 */
11522 #define WRC_Continue    0   /* Continue down into children */
11523 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11524 #define WRC_Abort       2   /* Abandon the tree walk */
11525
11526 /*
11527 ** Assuming zIn points to the first byte of a UTF-8 character,
11528 ** advance zIn to point to the first byte of the next UTF-8 character.
11529 */
11530 #define SQLITE_SKIP_UTF8(zIn) {                        \
11531   if( (*(zIn++))>=0xc0 ){                              \
11532     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11533   }                                                    \
11534 }
11535
11536 /*
11537 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11538 ** the same name but without the _BKPT suffix.  These macros invoke
11539 ** routines that report the line-number on which the error originated
11540 ** using sqlite3_log().  The routines also provide a convenient place
11541 ** to set a debugger breakpoint.
11542 */
11543 SQLITE_PRIVATE int sqlite3CorruptError(int);
11544 SQLITE_PRIVATE int sqlite3MisuseError(int);
11545 SQLITE_PRIVATE int sqlite3CantopenError(int);
11546 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11547 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11548 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11549
11550
11551 /*
11552 ** FTS4 is really an extension for FTS3.  It is enabled using the
11553 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11554 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11555 */
11556 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11557 # define SQLITE_ENABLE_FTS3
11558 #endif
11559
11560 /*
11561 ** The ctype.h header is needed for non-ASCII systems.  It is also
11562 ** needed by FTS3 when FTS3 is included in the amalgamation.
11563 */
11564 #if !defined(SQLITE_ASCII) || \
11565     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11566 # include <ctype.h>
11567 #endif
11568
11569 /*
11570 ** The following macros mimic the standard library functions toupper(),
11571 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11572 ** sqlite versions only work for ASCII characters, regardless of locale.
11573 */
11574 #ifdef SQLITE_ASCII
11575 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11576 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11577 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11578 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11579 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11580 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11581 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11582 #else
11583 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11584 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11585 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11586 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11587 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11588 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11589 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11590 #endif
11591
11592 /*
11593 ** Internal function prototypes
11594 */
11595 #define sqlite3StrICmp sqlite3_stricmp
11596 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11597 #define sqlite3StrNICmp sqlite3_strnicmp
11598
11599 SQLITE_PRIVATE int sqlite3MallocInit(void);
11600 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11601 SQLITE_PRIVATE void *sqlite3Malloc(int);
11602 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11603 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11604 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11605 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11606 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11607 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11608 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11609 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11610 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11611 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11612 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11613 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11614 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11615 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11616 SQLITE_PRIVATE void sqlite3PageFree(void*);
11617 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11618 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11619 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11620
11621 /*
11622 ** On systems with ample stack space and that support alloca(), make
11623 ** use of alloca() to obtain space for large automatic objects.  By default,
11624 ** obtain space from malloc().
11625 **
11626 ** The alloca() routine never returns NULL.  This will cause code paths
11627 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11628 */
11629 #ifdef SQLITE_USE_ALLOCA
11630 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11631 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11632 # define sqlite3StackFree(D,P)       
11633 #else
11634 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11635 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11636 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11637 #endif
11638
11639 #ifdef SQLITE_ENABLE_MEMSYS3
11640 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11641 #endif
11642 #ifdef SQLITE_ENABLE_MEMSYS5
11643 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11644 #endif
11645
11646
11647 #ifndef SQLITE_MUTEX_OMIT
11648 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11649 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11650 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11651 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11652 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11653 #endif
11654
11655 SQLITE_PRIVATE int sqlite3StatusValue(int);
11656 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11657 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11658
11659 #ifndef SQLITE_OMIT_FLOATING_POINT
11660 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11661 #else
11662 # define sqlite3IsNaN(X)  0
11663 #endif
11664
11665 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11666 #ifndef SQLITE_OMIT_TRACE
11667 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11668 #endif
11669 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11670 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11671 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11672 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11673 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11674 #endif
11675 #if defined(SQLITE_TEST)
11676 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11677 #endif
11678
11679 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11680 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11681 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11682 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11683 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11684 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11685 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11686 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11687 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11688 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11689 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11690 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11691 #else
11692 # define sqlite3ExplainBegin(X)
11693 # define sqlite3ExplainSelect(A,B)
11694 # define sqlite3ExplainExpr(A,B)
11695 # define sqlite3ExplainExprList(A,B)
11696 # define sqlite3ExplainFinish(X)
11697 # define sqlite3VdbeExplanation(X) 0
11698 #endif
11699
11700
11701 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11702 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11703 SQLITE_PRIVATE int sqlite3Dequote(char*);
11704 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11705 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11706 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11707 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11708 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11709 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11710 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11711 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11712 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11713 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11714 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11715 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11716 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11717 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11718 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11719 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11720 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11721 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11722 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11723 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11724 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11725 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11726 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11727 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11728 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11729 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11730 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11731 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11732 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11733 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11734 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11735 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11736 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11737 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11738 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11739 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11740 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11741 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11742 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11743 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11744                     sqlite3_vfs**,char**,char **);
11745 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11746 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11747
11748 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11749 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11750 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11751 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11752 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11753 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11754 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11755
11756 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11757 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11758 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11759 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11760 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11761
11762 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11763
11764 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11765 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11766 #else
11767 # define sqlite3ViewGetColumnNames(A,B) 0
11768 #endif
11769
11770 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11771 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11772 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11773 #ifndef SQLITE_OMIT_AUTOINCREMENT
11774 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11775 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11776 #else
11777 # define sqlite3AutoincrementBegin(X)
11778 # define sqlite3AutoincrementEnd(X)
11779 #endif
11780 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11781 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11782 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11783 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11784 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11785 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11786 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11787                                       Token*, Select*, Expr*, IdList*);
11788 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11789 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11790 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11791 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11792 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11793 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11794 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11795                         Token*, int, int);
11796 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11797 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11798 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11799                          Expr*,ExprList*,int,Expr*,Expr*);
11800 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11801 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11802 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11803 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11804 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11805 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11806 #endif
11807 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11808 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11809 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
11810     Parse*,SrcList*,Expr*,ExprList**,ExprList*,u16,int);
11811 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11812 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11813 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11814 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11815 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11816 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11817 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11818 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11819 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11820 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11821 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11822 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11823 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11824 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11825 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11826 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11827 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11828 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11829 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11830 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11831 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11832 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11833 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11834 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11835 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11836 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11837 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11838 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11839 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11840 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11841 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11842 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
11843 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11844 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11845 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11846 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11847 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11848 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11849 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11850 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11851 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11852 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11853 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11854 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11855 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
11856 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11857 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11858 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11859 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11860 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11861 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11862 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11863 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11864 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11865 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11866 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11867 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11868                                      int*,int,int,int,int,int*);
11869 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11870 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11871 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11872 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11873 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11874 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11875 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11876 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11877 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11878 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11879 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11880 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11881 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
11882 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11883 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11884 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11885 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11886 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11887 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11888
11889 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11890 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11891 #endif
11892
11893 #ifndef SQLITE_OMIT_TRIGGER
11894 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11895                            Expr*,int, int);
11896 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11897 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11898 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11899 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11900 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11901 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11902                             int, int, int);
11903 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11904   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11905 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11906 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11907 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11908                                         ExprList*,Select*,u8);
11909 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11910 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11911 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11912 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11913 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11914 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11915 #else
11916 # define sqlite3TriggersExist(B,C,D,E,F) 0
11917 # define sqlite3DeleteTrigger(A,B)
11918 # define sqlite3DropTriggerPtr(A,B)
11919 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11920 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11921 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11922 # define sqlite3TriggerList(X, Y) 0
11923 # define sqlite3ParseToplevel(p) p
11924 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11925 #endif
11926
11927 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11928 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11929 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11930 #ifndef SQLITE_OMIT_AUTHORIZATION
11931 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11932 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11933 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11934 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11935 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11936 #else
11937 # define sqlite3AuthRead(a,b,c,d)
11938 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11939 # define sqlite3AuthContextPush(a,b,c)
11940 # define sqlite3AuthContextPop(a)  ((void)(a))
11941 #endif
11942 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11943 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11944 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11945 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11946 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11947 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11948 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11949 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11950 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11951 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11952 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11953 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11954 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11955 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11956
11957 /*
11958 ** Routines to read and write variable-length integers.  These used to
11959 ** be defined locally, but now we use the varint routines in the util.c
11960 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11961 ** are coded to assume the single byte case is already handled (which 
11962 ** the MACRO form does).
11963 */
11964 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11965 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11966 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11967 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11968 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11969
11970 /*
11971 ** The header of a record consists of a sequence variable-length integers.
11972 ** These integers are almost always small and are encoded as a single byte.
11973 ** The following macros take advantage this fact to provide a fast encode
11974 ** and decode of the integers in a record header.  It is faster for the common
11975 ** case where the integer is a single byte.  It is a little slower when the
11976 ** integer is two or more bytes.  But overall it is faster.
11977 **
11978 ** The following expressions are equivalent:
11979 **
11980 **     x = sqlite3GetVarint32( A, &B );
11981 **     x = sqlite3PutVarint32( A, B );
11982 **
11983 **     x = getVarint32( A, B );
11984 **     x = putVarint32( A, B );
11985 **
11986 */
11987 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11988 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11989 #define getVarint    sqlite3GetVarint
11990 #define putVarint    sqlite3PutVarint
11991
11992
11993 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11994 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11995 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11996 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11997 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11998 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11999 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12000 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12001 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12002 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12003 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12004 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12005 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12006 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12007 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12008 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
12009 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
12010 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12011 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12012 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12013 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12014 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12015 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12016 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12017 #ifdef SQLITE_ENABLE_8_3_NAMES
12018 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12019 #else
12020 # define sqlite3FileSuffix3(X,Y)
12021 #endif
12022 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12023
12024 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12025 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12026 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
12027                         void(*)(void*));
12028 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12029 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12030 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12031 #ifdef SQLITE_ENABLE_STAT3
12032 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12033 #endif
12034 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12035 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12036 #ifndef SQLITE_AMALGAMATION
12037 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12038 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12039 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12040 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12041 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12042 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12043 #ifndef SQLITE_OMIT_WSD
12044 SQLITE_PRIVATE int sqlite3PendingByte;
12045 #endif
12046 #endif
12047 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12048 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12049 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12050 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12051 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12052 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12053 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12054 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12055 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12056 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12057 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12058 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12059 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12060 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12061 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12062 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
12063 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12064 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12065 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12066 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12067 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12068 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12069 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12070 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12071 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12072 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12073 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12074 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12075 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12076 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12077 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12078 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
12079   void (*)(sqlite3_context*,int,sqlite3_value **),
12080   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12081   FuncDestructor *pDestructor
12082 );
12083 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12084 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12085
12086 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12087 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12088 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12089 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12090 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12091 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12092 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12093
12094 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12095 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12096
12097 /*
12098 ** The interface to the LEMON-generated parser
12099 */
12100 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12101 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12102 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12103 #ifdef YYTRACKMAXSTACKDEPTH
12104 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12105 #endif
12106
12107 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12108 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12109 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12110 #else
12111 # define sqlite3CloseExtensions(X)
12112 #endif
12113
12114 #ifndef SQLITE_OMIT_SHARED_CACHE
12115 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12116 #else
12117   #define sqlite3TableLock(v,w,x,y,z)
12118 #endif
12119
12120 #ifdef SQLITE_TEST
12121 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12122 #endif
12123
12124 #ifdef SQLITE_OMIT_VIRTUALTABLE
12125 #  define sqlite3VtabClear(Y)
12126 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12127 #  define sqlite3VtabRollback(X)
12128 #  define sqlite3VtabCommit(X)
12129 #  define sqlite3VtabInSync(db) 0
12130 #  define sqlite3VtabLock(X) 
12131 #  define sqlite3VtabUnlock(X)
12132 #  define sqlite3VtabUnlockList(X)
12133 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12134 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12135 #else
12136 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12137 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12138 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12139 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12140 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12141 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12142 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12143 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12144 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12145 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12146 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12147 #endif
12148 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12149 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12150 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12151 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12152 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12153 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12154 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12155 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12156 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12157 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12158 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12159 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12160 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12161 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12162 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12163 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12164 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12165 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12166 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12167 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12168
12169 /* Declarations for functions in fkey.c. All of these are replaced by
12170 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12171 ** key functionality is available. If OMIT_TRIGGER is defined but
12172 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12173 ** this case foreign keys are parsed, but no other functionality is 
12174 ** provided (enforcement of FK constraints requires the triggers sub-system).
12175 */
12176 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12177 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12178 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12179 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12180 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12181 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12182 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12183 #else
12184   #define sqlite3FkActions(a,b,c,d)
12185   #define sqlite3FkCheck(a,b,c,d)
12186   #define sqlite3FkDropTable(a,b,c)
12187   #define sqlite3FkOldmask(a,b)      0
12188   #define sqlite3FkRequired(a,b,c,d) 0
12189 #endif
12190 #ifndef SQLITE_OMIT_FOREIGN_KEY
12191 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12192 #else
12193   #define sqlite3FkDelete(a,b)
12194 #endif
12195
12196
12197 /*
12198 ** Available fault injectors.  Should be numbered beginning with 0.
12199 */
12200 #define SQLITE_FAULTINJECTOR_MALLOC     0
12201 #define SQLITE_FAULTINJECTOR_COUNT      1
12202
12203 /*
12204 ** The interface to the code in fault.c used for identifying "benign"
12205 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12206 ** is not defined.
12207 */
12208 #ifndef SQLITE_OMIT_BUILTIN_TEST
12209 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12210 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12211 #else
12212   #define sqlite3BeginBenignMalloc()
12213   #define sqlite3EndBenignMalloc()
12214 #endif
12215
12216 #define IN_INDEX_ROWID           1
12217 #define IN_INDEX_EPH             2
12218 #define IN_INDEX_INDEX           3
12219 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12220
12221 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12222 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12223 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12224 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12225 #else
12226   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12227 #endif
12228
12229 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12230 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12231 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12232
12233 #if SQLITE_MAX_EXPR_DEPTH>0
12234 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12235 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12236 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12237 #else
12238   #define sqlite3ExprSetHeight(x,y)
12239   #define sqlite3SelectExprHeight(x) 0
12240   #define sqlite3ExprCheckHeight(x,y)
12241 #endif
12242
12243 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12244 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12245
12246 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12247 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12248 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12249 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12250 #else
12251   #define sqlite3ConnectionBlocked(x,y)
12252   #define sqlite3ConnectionUnlocked(x)
12253   #define sqlite3ConnectionClosed(x)
12254 #endif
12255
12256 #ifdef SQLITE_DEBUG
12257 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12258 #endif
12259
12260 /*
12261 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12262 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12263 ** print I/O tracing messages. 
12264 */
12265 #ifdef SQLITE_ENABLE_IOTRACE
12266 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12267 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12268 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12269 #else
12270 # define IOTRACE(A)
12271 # define sqlite3VdbeIOTraceSql(X)
12272 #endif
12273
12274 /*
12275 ** These routines are available for the mem2.c debugging memory allocator
12276 ** only.  They are used to verify that different "types" of memory
12277 ** allocations are properly tracked by the system.
12278 **
12279 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12280 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12281 ** a single bit set.
12282 **
12283 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12284 ** argument match the type set by the previous sqlite3MemdebugSetType().
12285 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12286 **
12287 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12288 ** argument match the type set by the previous sqlite3MemdebugSetType().
12289 **
12290 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12291 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12292 ** it might have been allocated by lookaside, except the allocation was
12293 ** too large or lookaside was already full.  It is important to verify
12294 ** that allocations that might have been satisfied by lookaside are not
12295 ** passed back to non-lookaside free() routines.  Asserts such as the
12296 ** example above are placed on the non-lookaside free() routines to verify
12297 ** this constraint. 
12298 **
12299 ** All of this is no-op for a production build.  It only comes into
12300 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12301 */
12302 #ifdef SQLITE_MEMDEBUG
12303 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12304 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12305 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12306 #else
12307 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12308 # define sqlite3MemdebugHasType(X,Y)  1
12309 # define sqlite3MemdebugNoType(X,Y)   1
12310 #endif
12311 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12312 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12313 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12314 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12315 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12316
12317 #endif /* _SQLITEINT_H_ */
12318
12319 /************** End of sqliteInt.h *******************************************/
12320 /************** Begin file global.c ******************************************/
12321 /*
12322 ** 2008 June 13
12323 **
12324 ** The author disclaims copyright to this source code.  In place of
12325 ** a legal notice, here is a blessing:
12326 **
12327 **    May you do good and not evil.
12328 **    May you find forgiveness for yourself and forgive others.
12329 **    May you share freely, never taking more than you give.
12330 **
12331 *************************************************************************
12332 **
12333 ** This file contains definitions of global variables and contants.
12334 */
12335
12336 /* An array to map all upper-case characters into their corresponding
12337 ** lower-case character. 
12338 **
12339 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12340 ** handle case conversions for the UTF character set since the tables
12341 ** involved are nearly as big or bigger than SQLite itself.
12342 */
12343 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12344 #ifdef SQLITE_ASCII
12345       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12346      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12347      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12348      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12349     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12350     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12351     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12352     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12353     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12354     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12355     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12356     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12357     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12358     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12359     252,253,254,255
12360 #endif
12361 #ifdef SQLITE_EBCDIC
12362       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12363      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12364      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12365      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12366      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12367      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12368      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12369     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12370     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12371     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12372     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12373     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12374     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12375     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12376     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12377     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12378 #endif
12379 };
12380
12381 /*
12382 ** The following 256 byte lookup table is used to support SQLites built-in
12383 ** equivalents to the following standard library functions:
12384 **
12385 **   isspace()                        0x01
12386 **   isalpha()                        0x02
12387 **   isdigit()                        0x04
12388 **   isalnum()                        0x06
12389 **   isxdigit()                       0x08
12390 **   toupper()                        0x20
12391 **   SQLite identifier character      0x40
12392 **
12393 ** Bit 0x20 is set if the mapped character requires translation to upper
12394 ** case. i.e. if the character is a lower-case ASCII character.
12395 ** If x is a lower-case ASCII character, then its upper-case equivalent
12396 ** is (x - 0x20). Therefore toupper() can be implemented as:
12397 **
12398 **   (x & ~(map[x]&0x20))
12399 **
12400 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12401 ** array. tolower() is used more often than toupper() by SQLite.
12402 **
12403 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12404 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12405 ** non-ASCII UTF character. Hence the test for whether or not a character is
12406 ** part of an identifier is 0x46.
12407 **
12408 ** SQLite's versions are identical to the standard versions assuming a
12409 ** locale of "C". They are implemented as macros in sqliteInt.h.
12410 */
12411 #ifdef SQLITE_ASCII
12412 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12413   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12414   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12415   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12416   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12417   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12418   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12419   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12420   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12421
12422   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12423   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12424   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12425   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12426   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12427   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12428   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12429   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12430
12431   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12432   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12433   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12434   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12435   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12436   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12437   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12438   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12439
12440   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12441   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12442   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12443   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12444   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12445   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12446   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12447   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12448 };
12449 #endif
12450
12451 #ifndef SQLITE_USE_URI
12452 # define  SQLITE_USE_URI 0
12453 #endif
12454
12455 /*
12456 ** The following singleton contains the global configuration for
12457 ** the SQLite library.
12458 */
12459 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12460    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12461    1,                         /* bCoreMutex */
12462    SQLITE_THREADSAFE==1,      /* bFullMutex */
12463    SQLITE_USE_URI,            /* bOpenUri */
12464    0x7ffffffe,                /* mxStrlen */
12465    128,                       /* szLookaside */
12466    500,                       /* nLookaside */
12467    {0,0,0,0,0,0,0,0},         /* m */
12468    {0,0,0,0,0,0,0,0,0},       /* mutex */
12469    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12470    (void*)0,                  /* pHeap */
12471    0,                         /* nHeap */
12472    0, 0,                      /* mnHeap, mxHeap */
12473    (void*)0,                  /* pScratch */
12474    0,                         /* szScratch */
12475    0,                         /* nScratch */
12476    (void*)0,                  /* pPage */
12477    0,                         /* szPage */
12478    0,                         /* nPage */
12479    0,                         /* mxParserStack */
12480    0,                         /* sharedCacheEnabled */
12481    /* All the rest should always be initialized to zero */
12482    0,                         /* isInit */
12483    0,                         /* inProgress */
12484    0,                         /* isMutexInit */
12485    0,                         /* isMallocInit */
12486    0,                         /* isPCacheInit */
12487    0,                         /* pInitMutex */
12488    0,                         /* nRefInitMutex */
12489    0,                         /* xLog */
12490    0,                         /* pLogArg */
12491    0,                         /* bLocaltimeFault */
12492 };
12493
12494
12495 /*
12496 ** Hash table for global functions - functions common to all
12497 ** database connections.  After initialization, this table is
12498 ** read-only.
12499 */
12500 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12501
12502 /*
12503 ** Constant tokens for values 0 and 1.
12504 */
12505 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12506    { "0", 1 },
12507    { "1", 1 }
12508 };
12509
12510
12511 /*
12512 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12513 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12514 ** the database page that contains the pending byte.  It never attempts
12515 ** to read or write that page.  The pending byte page is set assign
12516 ** for use by the VFS layers as space for managing file locks.
12517 **
12518 ** During testing, it is often desirable to move the pending byte to
12519 ** a different position in the file.  This allows code that has to
12520 ** deal with the pending byte to run on files that are much smaller
12521 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12522 ** move the pending byte.
12523 **
12524 ** IMPORTANT:  Changing the pending byte to any value other than
12525 ** 0x40000000 results in an incompatible database file format!
12526 ** Changing the pending byte during operating results in undefined
12527 ** and dileterious behavior.
12528 */
12529 #ifndef SQLITE_OMIT_WSD
12530 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12531 #endif
12532
12533 /*
12534 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12535 ** created by mkopcodeh.awk during compilation.  Data is obtained
12536 ** from the comments following the "case OP_xxxx:" statements in
12537 ** the vdbe.c file.  
12538 */
12539 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12540
12541 /************** End of global.c **********************************************/
12542 /************** Begin file ctime.c *******************************************/
12543 /*
12544 ** 2010 February 23
12545 **
12546 ** The author disclaims copyright to this source code.  In place of
12547 ** a legal notice, here is a blessing:
12548 **
12549 **    May you do good and not evil.
12550 **    May you find forgiveness for yourself and forgive others.
12551 **    May you share freely, never taking more than you give.
12552 **
12553 *************************************************************************
12554 **
12555 ** This file implements routines used to report what compile-time options
12556 ** SQLite was built with.
12557 */
12558
12559 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12560
12561
12562 /*
12563 ** An array of names of all compile-time options.  This array should 
12564 ** be sorted A-Z.
12565 **
12566 ** This array looks large, but in a typical installation actually uses
12567 ** only a handful of compile-time options, so most times this array is usually
12568 ** rather short and uses little memory space.
12569 */
12570 static const char * const azCompileOpt[] = {
12571
12572 /* These macros are provided to "stringify" the value of the define
12573 ** for those options in which the value is meaningful. */
12574 #define CTIMEOPT_VAL_(opt) #opt
12575 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12576
12577 #ifdef SQLITE_32BIT_ROWID
12578   "32BIT_ROWID",
12579 #endif
12580 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12581   "4_BYTE_ALIGNED_MALLOC",
12582 #endif
12583 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12584   "CASE_SENSITIVE_LIKE",
12585 #endif
12586 #ifdef SQLITE_CHECK_PAGES
12587   "CHECK_PAGES",
12588 #endif
12589 #ifdef SQLITE_COVERAGE_TEST
12590   "COVERAGE_TEST",
12591 #endif
12592 #ifdef SQLITE_CURDIR
12593   "CURDIR",
12594 #endif
12595 #ifdef SQLITE_DEBUG
12596   "DEBUG",
12597 #endif
12598 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12599   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12600 #endif
12601 #ifdef SQLITE_DISABLE_DIRSYNC
12602   "DISABLE_DIRSYNC",
12603 #endif
12604 #ifdef SQLITE_DISABLE_LFS
12605   "DISABLE_LFS",
12606 #endif
12607 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12608   "ENABLE_ATOMIC_WRITE",
12609 #endif
12610 #ifdef SQLITE_ENABLE_CEROD
12611   "ENABLE_CEROD",
12612 #endif
12613 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12614   "ENABLE_COLUMN_METADATA",
12615 #endif
12616 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12617   "ENABLE_EXPENSIVE_ASSERT",
12618 #endif
12619 #ifdef SQLITE_ENABLE_FTS1
12620   "ENABLE_FTS1",
12621 #endif
12622 #ifdef SQLITE_ENABLE_FTS2
12623   "ENABLE_FTS2",
12624 #endif
12625 #ifdef SQLITE_ENABLE_FTS3
12626   "ENABLE_FTS3",
12627 #endif
12628 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12629   "ENABLE_FTS3_PARENTHESIS",
12630 #endif
12631 #ifdef SQLITE_ENABLE_FTS4
12632   "ENABLE_FTS4",
12633 #endif
12634 #ifdef SQLITE_ENABLE_ICU
12635   "ENABLE_ICU",
12636 #endif
12637 #ifdef SQLITE_ENABLE_IOTRACE
12638   "ENABLE_IOTRACE",
12639 #endif
12640 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12641   "ENABLE_LOAD_EXTENSION",
12642 #endif
12643 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12644   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12645 #endif
12646 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12647   "ENABLE_MEMORY_MANAGEMENT",
12648 #endif
12649 #ifdef SQLITE_ENABLE_MEMSYS3
12650   "ENABLE_MEMSYS3",
12651 #endif
12652 #ifdef SQLITE_ENABLE_MEMSYS5
12653   "ENABLE_MEMSYS5",
12654 #endif
12655 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12656   "ENABLE_OVERSIZE_CELL_CHECK",
12657 #endif
12658 #ifdef SQLITE_ENABLE_RTREE
12659   "ENABLE_RTREE",
12660 #endif
12661 #ifdef SQLITE_ENABLE_STAT3
12662   "ENABLE_STAT3",
12663 #endif
12664 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12665   "ENABLE_UNLOCK_NOTIFY",
12666 #endif
12667 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12668   "ENABLE_UPDATE_DELETE_LIMIT",
12669 #endif
12670 #ifdef SQLITE_HAS_CODEC
12671   "HAS_CODEC",
12672 #endif
12673 #ifdef SQLITE_HAVE_ISNAN
12674   "HAVE_ISNAN",
12675 #endif
12676 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12677   "HOMEGROWN_RECURSIVE_MUTEX",
12678 #endif
12679 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12680   "IGNORE_AFP_LOCK_ERRORS",
12681 #endif
12682 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12683   "IGNORE_FLOCK_LOCK_ERRORS",
12684 #endif
12685 #ifdef SQLITE_INT64_TYPE
12686   "INT64_TYPE",
12687 #endif
12688 #ifdef SQLITE_LOCK_TRACE
12689   "LOCK_TRACE",
12690 #endif
12691 #ifdef SQLITE_MAX_SCHEMA_RETRY
12692   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12693 #endif
12694 #ifdef SQLITE_MEMDEBUG
12695   "MEMDEBUG",
12696 #endif
12697 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12698   "MIXED_ENDIAN_64BIT_FLOAT",
12699 #endif
12700 #ifdef SQLITE_NO_SYNC
12701   "NO_SYNC",
12702 #endif
12703 #ifdef SQLITE_OMIT_ALTERTABLE
12704   "OMIT_ALTERTABLE",
12705 #endif
12706 #ifdef SQLITE_OMIT_ANALYZE
12707   "OMIT_ANALYZE",
12708 #endif
12709 #ifdef SQLITE_OMIT_ATTACH
12710   "OMIT_ATTACH",
12711 #endif
12712 #ifdef SQLITE_OMIT_AUTHORIZATION
12713   "OMIT_AUTHORIZATION",
12714 #endif
12715 #ifdef SQLITE_OMIT_AUTOINCREMENT
12716   "OMIT_AUTOINCREMENT",
12717 #endif
12718 #ifdef SQLITE_OMIT_AUTOINIT
12719   "OMIT_AUTOINIT",
12720 #endif
12721 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12722   "OMIT_AUTOMATIC_INDEX",
12723 #endif
12724 #ifdef SQLITE_OMIT_AUTORESET
12725   "OMIT_AUTORESET",
12726 #endif
12727 #ifdef SQLITE_OMIT_AUTOVACUUM
12728   "OMIT_AUTOVACUUM",
12729 #endif
12730 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12731   "OMIT_BETWEEN_OPTIMIZATION",
12732 #endif
12733 #ifdef SQLITE_OMIT_BLOB_LITERAL
12734   "OMIT_BLOB_LITERAL",
12735 #endif
12736 #ifdef SQLITE_OMIT_BTREECOUNT
12737   "OMIT_BTREECOUNT",
12738 #endif
12739 #ifdef SQLITE_OMIT_BUILTIN_TEST
12740   "OMIT_BUILTIN_TEST",
12741 #endif
12742 #ifdef SQLITE_OMIT_CAST
12743   "OMIT_CAST",
12744 #endif
12745 #ifdef SQLITE_OMIT_CHECK
12746   "OMIT_CHECK",
12747 #endif
12748 /* // redundant
12749 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12750 **   "OMIT_COMPILEOPTION_DIAGS",
12751 ** #endif
12752 */
12753 #ifdef SQLITE_OMIT_COMPLETE
12754   "OMIT_COMPLETE",
12755 #endif
12756 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12757   "OMIT_COMPOUND_SELECT",
12758 #endif
12759 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12760   "OMIT_DATETIME_FUNCS",
12761 #endif
12762 #ifdef SQLITE_OMIT_DECLTYPE
12763   "OMIT_DECLTYPE",
12764 #endif
12765 #ifdef SQLITE_OMIT_DEPRECATED
12766   "OMIT_DEPRECATED",
12767 #endif
12768 #ifdef SQLITE_OMIT_DISKIO
12769   "OMIT_DISKIO",
12770 #endif
12771 #ifdef SQLITE_OMIT_EXPLAIN
12772   "OMIT_EXPLAIN",
12773 #endif
12774 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12775   "OMIT_FLAG_PRAGMAS",
12776 #endif
12777 #ifdef SQLITE_OMIT_FLOATING_POINT
12778   "OMIT_FLOATING_POINT",
12779 #endif
12780 #ifdef SQLITE_OMIT_FOREIGN_KEY
12781   "OMIT_FOREIGN_KEY",
12782 #endif
12783 #ifdef SQLITE_OMIT_GET_TABLE
12784   "OMIT_GET_TABLE",
12785 #endif
12786 #ifdef SQLITE_OMIT_INCRBLOB
12787   "OMIT_INCRBLOB",
12788 #endif
12789 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12790   "OMIT_INTEGRITY_CHECK",
12791 #endif
12792 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12793   "OMIT_LIKE_OPTIMIZATION",
12794 #endif
12795 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12796   "OMIT_LOAD_EXTENSION",
12797 #endif
12798 #ifdef SQLITE_OMIT_LOCALTIME
12799   "OMIT_LOCALTIME",
12800 #endif
12801 #ifdef SQLITE_OMIT_LOOKASIDE
12802   "OMIT_LOOKASIDE",
12803 #endif
12804 #ifdef SQLITE_OMIT_MEMORYDB
12805   "OMIT_MEMORYDB",
12806 #endif
12807 #ifdef SQLITE_OMIT_MERGE_SORT
12808   "OMIT_MERGE_SORT",
12809 #endif
12810 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12811   "OMIT_OR_OPTIMIZATION",
12812 #endif
12813 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12814   "OMIT_PAGER_PRAGMAS",
12815 #endif
12816 #ifdef SQLITE_OMIT_PRAGMA
12817   "OMIT_PRAGMA",
12818 #endif
12819 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12820   "OMIT_PROGRESS_CALLBACK",
12821 #endif
12822 #ifdef SQLITE_OMIT_QUICKBALANCE
12823   "OMIT_QUICKBALANCE",
12824 #endif
12825 #ifdef SQLITE_OMIT_REINDEX
12826   "OMIT_REINDEX",
12827 #endif
12828 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12829   "OMIT_SCHEMA_PRAGMAS",
12830 #endif
12831 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12832   "OMIT_SCHEMA_VERSION_PRAGMAS",
12833 #endif
12834 #ifdef SQLITE_OMIT_SHARED_CACHE
12835   "OMIT_SHARED_CACHE",
12836 #endif
12837 #ifdef SQLITE_OMIT_SUBQUERY
12838   "OMIT_SUBQUERY",
12839 #endif
12840 #ifdef SQLITE_OMIT_TCL_VARIABLE
12841   "OMIT_TCL_VARIABLE",
12842 #endif
12843 #ifdef SQLITE_OMIT_TEMPDB
12844   "OMIT_TEMPDB",
12845 #endif
12846 #ifdef SQLITE_OMIT_TRACE
12847   "OMIT_TRACE",
12848 #endif
12849 #ifdef SQLITE_OMIT_TRIGGER
12850   "OMIT_TRIGGER",
12851 #endif
12852 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12853   "OMIT_TRUNCATE_OPTIMIZATION",
12854 #endif
12855 #ifdef SQLITE_OMIT_UTF16
12856   "OMIT_UTF16",
12857 #endif
12858 #ifdef SQLITE_OMIT_VACUUM
12859   "OMIT_VACUUM",
12860 #endif
12861 #ifdef SQLITE_OMIT_VIEW
12862   "OMIT_VIEW",
12863 #endif
12864 #ifdef SQLITE_OMIT_VIRTUALTABLE
12865   "OMIT_VIRTUALTABLE",
12866 #endif
12867 #ifdef SQLITE_OMIT_WAL
12868   "OMIT_WAL",
12869 #endif
12870 #ifdef SQLITE_OMIT_WSD
12871   "OMIT_WSD",
12872 #endif
12873 #ifdef SQLITE_OMIT_XFER_OPT
12874   "OMIT_XFER_OPT",
12875 #endif
12876 #ifdef SQLITE_PERFORMANCE_TRACE
12877   "PERFORMANCE_TRACE",
12878 #endif
12879 #ifdef SQLITE_PROXY_DEBUG
12880   "PROXY_DEBUG",
12881 #endif
12882 #ifdef SQLITE_SECURE_DELETE
12883   "SECURE_DELETE",
12884 #endif
12885 #ifdef SQLITE_SMALL_STACK
12886   "SMALL_STACK",
12887 #endif
12888 #ifdef SQLITE_SOUNDEX
12889   "SOUNDEX",
12890 #endif
12891 #ifdef SQLITE_TCL
12892   "TCL",
12893 #endif
12894 #ifdef SQLITE_TEMP_STORE
12895   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12896 #endif
12897 #ifdef SQLITE_TEST
12898   "TEST",
12899 #endif
12900 #ifdef SQLITE_THREADSAFE
12901   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12902 #endif
12903 #ifdef SQLITE_USE_ALLOCA
12904   "USE_ALLOCA",
12905 #endif
12906 #ifdef SQLITE_ZERO_MALLOC
12907   "ZERO_MALLOC"
12908 #endif
12909 };
12910
12911 /*
12912 ** Given the name of a compile-time option, return true if that option
12913 ** was used and false if not.
12914 **
12915 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12916 ** is not required for a match.
12917 */
12918 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12919   int i, n;
12920   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12921   n = sqlite3Strlen30(zOptName);
12922
12923   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12924   ** linear search is adequate.  No need for a binary search. */
12925   for(i=0; i<ArraySize(azCompileOpt); i++){
12926     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12927        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12928   }
12929   return 0;
12930 }
12931
12932 /*
12933 ** Return the N-th compile-time option string.  If N is out of range,
12934 ** return a NULL pointer.
12935 */
12936 SQLITE_API const char *sqlite3_compileoption_get(int N){
12937   if( N>=0 && N<ArraySize(azCompileOpt) ){
12938     return azCompileOpt[N];
12939   }
12940   return 0;
12941 }
12942
12943 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12944
12945 /************** End of ctime.c ***********************************************/
12946 /************** Begin file status.c ******************************************/
12947 /*
12948 ** 2008 June 18
12949 **
12950 ** The author disclaims copyright to this source code.  In place of
12951 ** a legal notice, here is a blessing:
12952 **
12953 **    May you do good and not evil.
12954 **    May you find forgiveness for yourself and forgive others.
12955 **    May you share freely, never taking more than you give.
12956 **
12957 *************************************************************************
12958 **
12959 ** This module implements the sqlite3_status() interface and related
12960 ** functionality.
12961 */
12962 /************** Include vdbeInt.h in the middle of status.c ******************/
12963 /************** Begin file vdbeInt.h *****************************************/
12964 /*
12965 ** 2003 September 6
12966 **
12967 ** The author disclaims copyright to this source code.  In place of
12968 ** a legal notice, here is a blessing:
12969 **
12970 **    May you do good and not evil.
12971 **    May you find forgiveness for yourself and forgive others.
12972 **    May you share freely, never taking more than you give.
12973 **
12974 *************************************************************************
12975 ** This is the header file for information that is private to the
12976 ** VDBE.  This information used to all be at the top of the single
12977 ** source code file "vdbe.c".  When that file became too big (over
12978 ** 6000 lines long) it was split up into several smaller files and
12979 ** this header information was factored out.
12980 */
12981 #ifndef _VDBEINT_H_
12982 #define _VDBEINT_H_
12983
12984 /*
12985 ** SQL is translated into a sequence of instructions to be
12986 ** executed by a virtual machine.  Each instruction is an instance
12987 ** of the following structure.
12988 */
12989 typedef struct VdbeOp Op;
12990
12991 /*
12992 ** Boolean values
12993 */
12994 typedef unsigned char Bool;
12995
12996 /* Opaque type used by code in vdbesort.c */
12997 typedef struct VdbeSorter VdbeSorter;
12998
12999 /* Opaque type used by the explainer */
13000 typedef struct Explain Explain;
13001
13002 /*
13003 ** A cursor is a pointer into a single BTree within a database file.
13004 ** The cursor can seek to a BTree entry with a particular key, or
13005 ** loop over all entries of the Btree.  You can also insert new BTree
13006 ** entries or retrieve the key or data from the entry that the cursor
13007 ** is currently pointing to.
13008 ** 
13009 ** Every cursor that the virtual machine has open is represented by an
13010 ** instance of the following structure.
13011 */
13012 struct VdbeCursor {
13013   BtCursor *pCursor;    /* The cursor structure of the backend */
13014   Btree *pBt;           /* Separate file holding temporary table */
13015   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13016   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13017   int pseudoTableReg;   /* Register holding pseudotable content. */
13018   int nField;           /* Number of fields in the header */
13019   Bool zeroed;          /* True if zeroed out and ready for reuse */
13020   Bool rowidIsValid;    /* True if lastRowid is valid */
13021   Bool atFirst;         /* True if pointing to first entry */
13022   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13023   Bool nullRow;         /* True if pointing to a row with no data */
13024   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13025   Bool isTable;         /* True if a table requiring integer keys */
13026   Bool isIndex;         /* True if an index containing keys only - no data */
13027   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13028   Bool isSorter;        /* True if a new-style sorter */
13029   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13030   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13031   i64 seqCount;         /* Sequence counter */
13032   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13033   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13034   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13035
13036   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
13037   ** OP_IsUnique opcode on this cursor. */
13038   int seekResult;
13039
13040   /* Cached information about the header for the data record that the
13041   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13042   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13043   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13044   ** the cache is out of date.
13045   **
13046   ** aRow might point to (ephemeral) data for the current row, or it might
13047   ** be NULL.
13048   */
13049   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13050   int payloadSize;      /* Total number of bytes in the record */
13051   u32 *aType;           /* Type values for all entries in the record */
13052   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13053   u8 *aRow;             /* Data for the current row, if all on one page */
13054 };
13055 typedef struct VdbeCursor VdbeCursor;
13056
13057 /*
13058 ** When a sub-program is executed (OP_Program), a structure of this type
13059 ** is allocated to store the current value of the program counter, as
13060 ** well as the current memory cell array and various other frame specific
13061 ** values stored in the Vdbe struct. When the sub-program is finished, 
13062 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13063 ** restoring the state of the VM to as it was before the sub-program
13064 ** began executing.
13065 **
13066 ** The memory for a VdbeFrame object is allocated and managed by a memory
13067 ** cell in the parent (calling) frame. When the memory cell is deleted or
13068 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13069 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13070 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13071 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13072 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13073 ** child frame are released.
13074 **
13075 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13076 ** set to NULL if the currently executing frame is the main program.
13077 */
13078 typedef struct VdbeFrame VdbeFrame;
13079 struct VdbeFrame {
13080   Vdbe *v;                /* VM this frame belongs to */
13081   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13082   Op *aOp;                /* Program instructions for parent frame */
13083   Mem *aMem;              /* Array of memory cells for parent frame */
13084   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13085   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13086   void *token;            /* Copy of SubProgram.token */
13087   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13088   u16 nCursor;            /* Number of entries in apCsr */
13089   int pc;                 /* Program Counter in parent (calling) frame */
13090   int nOp;                /* Size of aOp array */
13091   int nMem;               /* Number of entries in aMem */
13092   int nOnceFlag;          /* Number of entries in aOnceFlag */
13093   int nChildMem;          /* Number of memory cells for child frame */
13094   int nChildCsr;          /* Number of cursors for child frame */
13095   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13096 };
13097
13098 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13099
13100 /*
13101 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13102 */
13103 #define CACHE_STALE 0
13104
13105 /*
13106 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13107 ** structures. Each Mem struct may cache multiple representations (string,
13108 ** integer etc.) of the same value.
13109 */
13110 struct Mem {
13111   sqlite3 *db;        /* The associated database connection */
13112   char *z;            /* String or BLOB value */
13113   double r;           /* Real value */
13114   union {
13115     i64 i;              /* Integer value used when MEM_Int is set in flags */
13116     int nZero;          /* Used when bit MEM_Zero is set in flags */
13117     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13118     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13119     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13120   } u;
13121   int n;              /* Number of characters in string value, excluding '\0' */
13122   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13123   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13124   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13125 #ifdef SQLITE_DEBUG
13126   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13127   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13128 #endif
13129   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13130   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13131 };
13132
13133 /* One or more of the following flags are set to indicate the validOK
13134 ** representations of the value stored in the Mem struct.
13135 **
13136 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13137 ** No other flags may be set in this case.
13138 **
13139 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13140 ** Usually this is encoded in the same unicode encoding as the main
13141 ** database (see below for exceptions). If the MEM_Term flag is also
13142 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13143 ** flags may coexist with the MEM_Str flag.
13144 */
13145 #define MEM_Null      0x0001   /* Value is NULL */
13146 #define MEM_Str       0x0002   /* Value is a string */
13147 #define MEM_Int       0x0004   /* Value is an integer */
13148 #define MEM_Real      0x0008   /* Value is a real number */
13149 #define MEM_Blob      0x0010   /* Value is a BLOB */
13150 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13151 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13152 #define MEM_Invalid   0x0080   /* Value is undefined */
13153 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
13154
13155 /* Whenever Mem contains a valid string or blob representation, one of
13156 ** the following flags must be set to determine the memory management
13157 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13158 ** string is \000 or \u0000 terminated
13159 */
13160 #define MEM_Term      0x0200   /* String rep is nul terminated */
13161 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13162 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13163 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13164 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13165 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13166 #ifdef SQLITE_OMIT_INCRBLOB
13167   #undef MEM_Zero
13168   #define MEM_Zero 0x0000
13169 #endif
13170
13171 /*
13172 ** Clear any existing type flags from a Mem and replace them with f
13173 */
13174 #define MemSetTypeFlag(p, f) \
13175    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13176
13177 /*
13178 ** Return true if a memory cell is not marked as invalid.  This macro
13179 ** is for use inside assert() statements only.
13180 */
13181 #ifdef SQLITE_DEBUG
13182 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13183 #endif
13184
13185
13186 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13187 ** additional information about auxiliary information bound to arguments
13188 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13189 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13190 ** that can be associated with a constant argument to a function.  This
13191 ** allows functions such as "regexp" to compile their constant regular
13192 ** expression argument once and reused the compiled code for multiple
13193 ** invocations.
13194 */
13195 struct VdbeFunc {
13196   FuncDef *pFunc;               /* The definition of the function */
13197   int nAux;                     /* Number of entries allocated for apAux[] */
13198   struct AuxData {
13199     void *pAux;                   /* Aux data for the i-th argument */
13200     void (*xDelete)(void *);      /* Destructor for the aux data */
13201   } apAux[1];                   /* One slot for each function argument */
13202 };
13203
13204 /*
13205 ** The "context" argument for a installable function.  A pointer to an
13206 ** instance of this structure is the first argument to the routines used
13207 ** implement the SQL functions.
13208 **
13209 ** There is a typedef for this structure in sqlite.h.  So all routines,
13210 ** even the public interface to SQLite, can use a pointer to this structure.
13211 ** But this file is the only place where the internal details of this
13212 ** structure are known.
13213 **
13214 ** This structure is defined inside of vdbeInt.h because it uses substructures
13215 ** (Mem) which are only defined there.
13216 */
13217 struct sqlite3_context {
13218   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13219   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13220   Mem s;                /* The return value is stored here */
13221   Mem *pMem;            /* Memory cell used to store aggregate context */
13222   CollSeq *pColl;       /* Collating sequence */
13223   int isError;          /* Error code returned by the function. */
13224   int skipFlag;         /* Skip skip accumulator loading if true */
13225 };
13226
13227 /*
13228 ** An Explain object accumulates indented output which is helpful
13229 ** in describing recursive data structures.
13230 */
13231 struct Explain {
13232   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13233   StrAccum str;      /* The string being accumulated */
13234   int nIndent;       /* Number of elements in aIndent */
13235   u16 aIndent[100];  /* Levels of indentation */
13236   char zBase[100];   /* Initial space */
13237 };
13238
13239 /*
13240 ** An instance of the virtual machine.  This structure contains the complete
13241 ** state of the virtual machine.
13242 **
13243 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13244 ** is really a pointer to an instance of this structure.
13245 **
13246 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13247 ** any virtual table method invocations made by the vdbe program. It is
13248 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13249 ** variable is used for two purposes: to allow xDestroy methods to execute
13250 ** "DROP TABLE" statements and to prevent some nasty side effects of
13251 ** malloc failure when SQLite is invoked recursively by a virtual table 
13252 ** method function.
13253 */
13254 struct Vdbe {
13255   sqlite3 *db;            /* The database connection that owns this statement */
13256   Op *aOp;                /* Space to hold the virtual machine's program */
13257   Mem *aMem;              /* The memory locations */
13258   Mem **apArg;            /* Arguments to currently executing user function */
13259   Mem *aColName;          /* Column names to return */
13260   Mem *pResultSet;        /* Pointer to an array of results */
13261   int nMem;               /* Number of memory locations currently allocated */
13262   int nOp;                /* Number of instructions in the program */
13263   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13264   int nLabel;             /* Number of labels used */
13265   int *aLabel;            /* Space to hold the labels */
13266   u16 nResColumn;         /* Number of columns in one row of the result set */
13267   u16 nCursor;            /* Number of slots in apCsr[] */
13268   u32 magic;              /* Magic number for sanity checking */
13269   char *zErrMsg;          /* Error message written here */
13270   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13271   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13272   Mem *aVar;              /* Values for the OP_Variable opcode. */
13273   char **azVar;           /* Name of variables */
13274   ynVar nVar;             /* Number of entries in aVar[] */
13275   ynVar nzVar;            /* Number of entries in azVar[] */
13276   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13277   int pc;                 /* The program counter */
13278   int rc;                 /* Value to return */
13279   u8 errorAction;         /* Recovery action to do in case of an error */
13280   u8 explain;             /* True if EXPLAIN present on SQL command */
13281   u8 changeCntOn;         /* True to update the change-counter */
13282   u8 expired;             /* True if the VM needs to be recompiled */
13283   u8 runOnlyOnce;         /* Automatically expire on reset */
13284   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13285   u8 inVtabMethod;        /* See comments above */
13286   u8 usesStmtJournal;     /* True if uses a statement journal */
13287   u8 readOnly;            /* True for read-only statements */
13288   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
13289   int nChange;            /* Number of db changes made since last reset */
13290   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13291   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13292   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13293   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13294 #ifndef SQLITE_OMIT_TRACE
13295   i64 startTime;          /* Time when query started - used for profiling */
13296 #endif
13297   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13298   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13299   char *zSql;             /* Text of the SQL statement that generated this */
13300   void *pFree;            /* Free this when deleting the vdbe */
13301 #ifdef SQLITE_DEBUG
13302   FILE *trace;            /* Write an execution trace here, if not NULL */
13303 #endif
13304 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13305   Explain *pExplain;      /* The explainer */
13306   char *zExplain;         /* Explanation of data structures */
13307 #endif
13308   VdbeFrame *pFrame;      /* Parent frame */
13309   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13310   int nFrame;             /* Number of frames in pFrame list */
13311   u32 expmask;            /* Binding to these vars invalidates VM */
13312   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13313   int nOnceFlag;          /* Size of array aOnceFlag[] */
13314   u8 *aOnceFlag;          /* Flags for OP_Once */
13315 };
13316
13317 /*
13318 ** The following are allowed values for Vdbe.magic
13319 */
13320 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13321 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13322 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13323 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13324
13325 /*
13326 ** Function prototypes
13327 */
13328 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13329 void sqliteVdbePopStack(Vdbe*,int);
13330 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13331 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13332 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13333 #endif
13334 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13335 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13336 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13337 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13338 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13339
13340 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13341 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13342 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13343 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13344 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13345 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13346 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13347 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13348 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13349 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13350 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13351 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13352 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13353 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13354 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13355 #ifdef SQLITE_OMIT_FLOATING_POINT
13356 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13357 #else
13358 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13359 #endif
13360 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13361 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13362 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13363 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13364 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13365 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13366 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13367 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13368 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13369 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13370 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13371 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13372 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13373 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13374 #define VdbeMemRelease(X)  \
13375   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13376     sqlite3VdbeMemReleaseExternal(X);
13377 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13378 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13379 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13380 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13381 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13382 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13383 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13384 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13385
13386 #ifdef SQLITE_OMIT_MERGE_SORT
13387 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
13388 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
13389 # define sqlite3VdbeSorterClose(Y,Z)
13390 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
13391 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
13392 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
13393 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13394 #else
13395 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13396 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13397 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13398 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13399 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13400 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13401 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13402 #endif
13403
13404 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13405 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13406 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13407 #else
13408 # define sqlite3VdbeEnter(X)
13409 # define sqlite3VdbeLeave(X)
13410 #endif
13411
13412 #ifdef SQLITE_DEBUG
13413 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13414 #endif
13415
13416 #ifndef SQLITE_OMIT_FOREIGN_KEY
13417 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13418 #else
13419 # define sqlite3VdbeCheckFk(p,i) 0
13420 #endif
13421
13422 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13423 #ifdef SQLITE_DEBUG
13424 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13425 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13426 #endif
13427 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13428
13429 #ifndef SQLITE_OMIT_INCRBLOB
13430 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13431   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13432 #else
13433   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13434   #define ExpandBlob(P) SQLITE_OK
13435 #endif
13436
13437 #endif /* !defined(_VDBEINT_H_) */
13438
13439 /************** End of vdbeInt.h *********************************************/
13440 /************** Continuing where we left off in status.c *********************/
13441
13442 /*
13443 ** Variables in which to record status information.
13444 */
13445 typedef struct sqlite3StatType sqlite3StatType;
13446 static SQLITE_WSD struct sqlite3StatType {
13447   int nowValue[10];         /* Current value */
13448   int mxValue[10];          /* Maximum value */
13449 } sqlite3Stat = { {0,}, {0,} };
13450
13451
13452 /* The "wsdStat" macro will resolve to the status information
13453 ** state vector.  If writable static data is unsupported on the target,
13454 ** we have to locate the state vector at run-time.  In the more common
13455 ** case where writable static data is supported, wsdStat can refer directly
13456 ** to the "sqlite3Stat" state vector declared above.
13457 */
13458 #ifdef SQLITE_OMIT_WSD
13459 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13460 # define wsdStat x[0]
13461 #else
13462 # define wsdStatInit
13463 # define wsdStat sqlite3Stat
13464 #endif
13465
13466 /*
13467 ** Return the current value of a status parameter.
13468 */
13469 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13470   wsdStatInit;
13471   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13472   return wsdStat.nowValue[op];
13473 }
13474
13475 /*
13476 ** Add N to the value of a status record.  It is assumed that the
13477 ** caller holds appropriate locks.
13478 */
13479 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13480   wsdStatInit;
13481   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13482   wsdStat.nowValue[op] += N;
13483   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13484     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13485   }
13486 }
13487
13488 /*
13489 ** Set the value of a status to X.
13490 */
13491 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13492   wsdStatInit;
13493   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13494   wsdStat.nowValue[op] = X;
13495   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13496     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13497   }
13498 }
13499
13500 /*
13501 ** Query status information.
13502 **
13503 ** This implementation assumes that reading or writing an aligned
13504 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13505 ** then this routine is not threadsafe.
13506 */
13507 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13508   wsdStatInit;
13509   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13510     return SQLITE_MISUSE_BKPT;
13511   }
13512   *pCurrent = wsdStat.nowValue[op];
13513   *pHighwater = wsdStat.mxValue[op];
13514   if( resetFlag ){
13515     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13516   }
13517   return SQLITE_OK;
13518 }
13519
13520 /*
13521 ** Query status information for a single database connection
13522 */
13523 SQLITE_API int sqlite3_db_status(
13524   sqlite3 *db,          /* The database connection whose status is desired */
13525   int op,               /* Status verb */
13526   int *pCurrent,        /* Write current value here */
13527   int *pHighwater,      /* Write high-water mark here */
13528   int resetFlag         /* Reset high-water mark if true */
13529 ){
13530   int rc = SQLITE_OK;   /* Return code */
13531   sqlite3_mutex_enter(db->mutex);
13532   switch( op ){
13533     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13534       *pCurrent = db->lookaside.nOut;
13535       *pHighwater = db->lookaside.mxOut;
13536       if( resetFlag ){
13537         db->lookaside.mxOut = db->lookaside.nOut;
13538       }
13539       break;
13540     }
13541
13542     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13543     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13544     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13545       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13546       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13547       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13548       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13549       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13550       *pCurrent = 0;
13551       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13552       if( resetFlag ){
13553         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13554       }
13555       break;
13556     }
13557
13558     /* 
13559     ** Return an approximation for the amount of memory currently used
13560     ** by all pagers associated with the given database connection.  The
13561     ** highwater mark is meaningless and is returned as zero.
13562     */
13563     case SQLITE_DBSTATUS_CACHE_USED: {
13564       int totalUsed = 0;
13565       int i;
13566       sqlite3BtreeEnterAll(db);
13567       for(i=0; i<db->nDb; i++){
13568         Btree *pBt = db->aDb[i].pBt;
13569         if( pBt ){
13570           Pager *pPager = sqlite3BtreePager(pBt);
13571           totalUsed += sqlite3PagerMemUsed(pPager);
13572         }
13573       }
13574       sqlite3BtreeLeaveAll(db);
13575       *pCurrent = totalUsed;
13576       *pHighwater = 0;
13577       break;
13578     }
13579
13580     /*
13581     ** *pCurrent gets an accurate estimate of the amount of memory used
13582     ** to store the schema for all databases (main, temp, and any ATTACHed
13583     ** databases.  *pHighwater is set to zero.
13584     */
13585     case SQLITE_DBSTATUS_SCHEMA_USED: {
13586       int i;                      /* Used to iterate through schemas */
13587       int nByte = 0;              /* Used to accumulate return value */
13588
13589       sqlite3BtreeEnterAll(db);
13590       db->pnBytesFreed = &nByte;
13591       for(i=0; i<db->nDb; i++){
13592         Schema *pSchema = db->aDb[i].pSchema;
13593         if( ALWAYS(pSchema!=0) ){
13594           HashElem *p;
13595
13596           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13597               pSchema->tblHash.count 
13598             + pSchema->trigHash.count
13599             + pSchema->idxHash.count
13600             + pSchema->fkeyHash.count
13601           );
13602           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13603           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13604           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13605           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13606
13607           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13608             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13609           }
13610           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13611             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13612           }
13613         }
13614       }
13615       db->pnBytesFreed = 0;
13616       sqlite3BtreeLeaveAll(db);
13617
13618       *pHighwater = 0;
13619       *pCurrent = nByte;
13620       break;
13621     }
13622
13623     /*
13624     ** *pCurrent gets an accurate estimate of the amount of memory used
13625     ** to store all prepared statements.
13626     ** *pHighwater is set to zero.
13627     */
13628     case SQLITE_DBSTATUS_STMT_USED: {
13629       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13630       int nByte = 0;              /* Used to accumulate return value */
13631
13632       db->pnBytesFreed = &nByte;
13633       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13634         sqlite3VdbeDeleteObject(db, pVdbe);
13635       }
13636       db->pnBytesFreed = 0;
13637
13638       *pHighwater = 0;
13639       *pCurrent = nByte;
13640
13641       break;
13642     }
13643
13644     /*
13645     ** Set *pCurrent to the total cache hits or misses encountered by all
13646     ** pagers the database handle is connected to. *pHighwater is always set 
13647     ** to zero.
13648     */
13649     case SQLITE_DBSTATUS_CACHE_HIT:
13650     case SQLITE_DBSTATUS_CACHE_MISS:
13651     case SQLITE_DBSTATUS_CACHE_WRITE:{
13652       int i;
13653       int nRet = 0;
13654       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13655       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13656
13657       for(i=0; i<db->nDb; i++){
13658         if( db->aDb[i].pBt ){
13659           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13660           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13661         }
13662       }
13663       *pHighwater = 0;
13664       *pCurrent = nRet;
13665       break;
13666     }
13667
13668     default: {
13669       rc = SQLITE_ERROR;
13670     }
13671   }
13672   sqlite3_mutex_leave(db->mutex);
13673   return rc;
13674 }
13675
13676 /************** End of status.c **********************************************/
13677 /************** Begin file date.c ********************************************/
13678 /*
13679 ** 2003 October 31
13680 **
13681 ** The author disclaims copyright to this source code.  In place of
13682 ** a legal notice, here is a blessing:
13683 **
13684 **    May you do good and not evil.
13685 **    May you find forgiveness for yourself and forgive others.
13686 **    May you share freely, never taking more than you give.
13687 **
13688 *************************************************************************
13689 ** This file contains the C functions that implement date and time
13690 ** functions for SQLite.  
13691 **
13692 ** There is only one exported symbol in this file - the function
13693 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13694 ** All other code has file scope.
13695 **
13696 ** SQLite processes all times and dates as Julian Day numbers.  The
13697 ** dates and times are stored as the number of days since noon
13698 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13699 ** calendar system. 
13700 **
13701 ** 1970-01-01 00:00:00 is JD 2440587.5
13702 ** 2000-01-01 00:00:00 is JD 2451544.5
13703 **
13704 ** This implemention requires years to be expressed as a 4-digit number
13705 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13706 ** be represented, even though julian day numbers allow a much wider
13707 ** range of dates.
13708 **
13709 ** The Gregorian calendar system is used for all dates and times,
13710 ** even those that predate the Gregorian calendar.  Historians usually
13711 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13712 ** dates afterwards, depending on locale.  Beware of this difference.
13713 **
13714 ** The conversion algorithms are implemented based on descriptions
13715 ** in the following text:
13716 **
13717 **      Jean Meeus
13718 **      Astronomical Algorithms, 2nd Edition, 1998
13719 **      ISBM 0-943396-61-1
13720 **      Willmann-Bell, Inc
13721 **      Richmond, Virginia (USA)
13722 */
13723 /* #include <stdlib.h> */
13724 /* #include <assert.h> */
13725 #include <time.h>
13726
13727 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13728
13729
13730 /*
13731 ** A structure for holding a single date and time.
13732 */
13733 typedef struct DateTime DateTime;
13734 struct DateTime {
13735   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13736   int Y, M, D;       /* Year, month, and day */
13737   int h, m;          /* Hour and minutes */
13738   int tz;            /* Timezone offset in minutes */
13739   double s;          /* Seconds */
13740   char validYMD;     /* True (1) if Y,M,D are valid */
13741   char validHMS;     /* True (1) if h,m,s are valid */
13742   char validJD;      /* True (1) if iJD is valid */
13743   char validTZ;      /* True (1) if tz is valid */
13744 };
13745
13746
13747 /*
13748 ** Convert zDate into one or more integers.  Additional arguments
13749 ** come in groups of 5 as follows:
13750 **
13751 **       N       number of digits in the integer
13752 **       min     minimum allowed value of the integer
13753 **       max     maximum allowed value of the integer
13754 **       nextC   first character after the integer
13755 **       pVal    where to write the integers value.
13756 **
13757 ** Conversions continue until one with nextC==0 is encountered.
13758 ** The function returns the number of successful conversions.
13759 */
13760 static int getDigits(const char *zDate, ...){
13761   va_list ap;
13762   int val;
13763   int N;
13764   int min;
13765   int max;
13766   int nextC;
13767   int *pVal;
13768   int cnt = 0;
13769   va_start(ap, zDate);
13770   do{
13771     N = va_arg(ap, int);
13772     min = va_arg(ap, int);
13773     max = va_arg(ap, int);
13774     nextC = va_arg(ap, int);
13775     pVal = va_arg(ap, int*);
13776     val = 0;
13777     while( N-- ){
13778       if( !sqlite3Isdigit(*zDate) ){
13779         goto end_getDigits;
13780       }
13781       val = val*10 + *zDate - '0';
13782       zDate++;
13783     }
13784     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13785       goto end_getDigits;
13786     }
13787     *pVal = val;
13788     zDate++;
13789     cnt++;
13790   }while( nextC );
13791 end_getDigits:
13792   va_end(ap);
13793   return cnt;
13794 }
13795
13796 /*
13797 ** Parse a timezone extension on the end of a date-time.
13798 ** The extension is of the form:
13799 **
13800 **        (+/-)HH:MM
13801 **
13802 ** Or the "zulu" notation:
13803 **
13804 **        Z
13805 **
13806 ** If the parse is successful, write the number of minutes
13807 ** of change in p->tz and return 0.  If a parser error occurs,
13808 ** return non-zero.
13809 **
13810 ** A missing specifier is not considered an error.
13811 */
13812 static int parseTimezone(const char *zDate, DateTime *p){
13813   int sgn = 0;
13814   int nHr, nMn;
13815   int c;
13816   while( sqlite3Isspace(*zDate) ){ zDate++; }
13817   p->tz = 0;
13818   c = *zDate;
13819   if( c=='-' ){
13820     sgn = -1;
13821   }else if( c=='+' ){
13822     sgn = +1;
13823   }else if( c=='Z' || c=='z' ){
13824     zDate++;
13825     goto zulu_time;
13826   }else{
13827     return c!=0;
13828   }
13829   zDate++;
13830   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13831     return 1;
13832   }
13833   zDate += 5;
13834   p->tz = sgn*(nMn + nHr*60);
13835 zulu_time:
13836   while( sqlite3Isspace(*zDate) ){ zDate++; }
13837   return *zDate!=0;
13838 }
13839
13840 /*
13841 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13842 ** The HH, MM, and SS must each be exactly 2 digits.  The
13843 ** fractional seconds FFFF can be one or more digits.
13844 **
13845 ** Return 1 if there is a parsing error and 0 on success.
13846 */
13847 static int parseHhMmSs(const char *zDate, DateTime *p){
13848   int h, m, s;
13849   double ms = 0.0;
13850   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13851     return 1;
13852   }
13853   zDate += 5;
13854   if( *zDate==':' ){
13855     zDate++;
13856     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13857       return 1;
13858     }
13859     zDate += 2;
13860     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13861       double rScale = 1.0;
13862       zDate++;
13863       while( sqlite3Isdigit(*zDate) ){
13864         ms = ms*10.0 + *zDate - '0';
13865         rScale *= 10.0;
13866         zDate++;
13867       }
13868       ms /= rScale;
13869     }
13870   }else{
13871     s = 0;
13872   }
13873   p->validJD = 0;
13874   p->validHMS = 1;
13875   p->h = h;
13876   p->m = m;
13877   p->s = s + ms;
13878   if( parseTimezone(zDate, p) ) return 1;
13879   p->validTZ = (p->tz!=0)?1:0;
13880   return 0;
13881 }
13882
13883 /*
13884 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13885 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13886 **
13887 ** Reference:  Meeus page 61
13888 */
13889 static void computeJD(DateTime *p){
13890   int Y, M, D, A, B, X1, X2;
13891
13892   if( p->validJD ) return;
13893   if( p->validYMD ){
13894     Y = p->Y;
13895     M = p->M;
13896     D = p->D;
13897   }else{
13898     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13899     M = 1;
13900     D = 1;
13901   }
13902   if( M<=2 ){
13903     Y--;
13904     M += 12;
13905   }
13906   A = Y/100;
13907   B = 2 - A + (A/4);
13908   X1 = 36525*(Y+4716)/100;
13909   X2 = 306001*(M+1)/10000;
13910   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13911   p->validJD = 1;
13912   if( p->validHMS ){
13913     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13914     if( p->validTZ ){
13915       p->iJD -= p->tz*60000;
13916       p->validYMD = 0;
13917       p->validHMS = 0;
13918       p->validTZ = 0;
13919     }
13920   }
13921 }
13922
13923 /*
13924 ** Parse dates of the form
13925 **
13926 **     YYYY-MM-DD HH:MM:SS.FFF
13927 **     YYYY-MM-DD HH:MM:SS
13928 **     YYYY-MM-DD HH:MM
13929 **     YYYY-MM-DD
13930 **
13931 ** Write the result into the DateTime structure and return 0
13932 ** on success and 1 if the input string is not a well-formed
13933 ** date.
13934 */
13935 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13936   int Y, M, D, neg;
13937
13938   if( zDate[0]=='-' ){
13939     zDate++;
13940     neg = 1;
13941   }else{
13942     neg = 0;
13943   }
13944   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13945     return 1;
13946   }
13947   zDate += 10;
13948   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13949   if( parseHhMmSs(zDate, p)==0 ){
13950     /* We got the time */
13951   }else if( *zDate==0 ){
13952     p->validHMS = 0;
13953   }else{
13954     return 1;
13955   }
13956   p->validJD = 0;
13957   p->validYMD = 1;
13958   p->Y = neg ? -Y : Y;
13959   p->M = M;
13960   p->D = D;
13961   if( p->validTZ ){
13962     computeJD(p);
13963   }
13964   return 0;
13965 }
13966
13967 /*
13968 ** Set the time to the current time reported by the VFS.
13969 **
13970 ** Return the number of errors.
13971 */
13972 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13973   sqlite3 *db = sqlite3_context_db_handle(context);
13974   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
13975     p->validJD = 1;
13976     return 0;
13977   }else{
13978     return 1;
13979   }
13980 }
13981
13982 /*
13983 ** Attempt to parse the given string into a Julian Day Number.  Return
13984 ** the number of errors.
13985 **
13986 ** The following are acceptable forms for the input string:
13987 **
13988 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13989 **      DDDD.DD 
13990 **      now
13991 **
13992 ** In the first form, the +/-HH:MM is always optional.  The fractional
13993 ** seconds extension (the ".FFF") is optional.  The seconds portion
13994 ** (":SS.FFF") is option.  The year and date can be omitted as long
13995 ** as there is a time string.  The time string can be omitted as long
13996 ** as there is a year and date.
13997 */
13998 static int parseDateOrTime(
13999   sqlite3_context *context, 
14000   const char *zDate, 
14001   DateTime *p
14002 ){
14003   double r;
14004   if( parseYyyyMmDd(zDate,p)==0 ){
14005     return 0;
14006   }else if( parseHhMmSs(zDate, p)==0 ){
14007     return 0;
14008   }else if( sqlite3StrICmp(zDate,"now")==0){
14009     return setDateTimeToCurrent(context, p);
14010   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14011     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14012     p->validJD = 1;
14013     return 0;
14014   }
14015   return 1;
14016 }
14017
14018 /*
14019 ** Compute the Year, Month, and Day from the julian day number.
14020 */
14021 static void computeYMD(DateTime *p){
14022   int Z, A, B, C, D, E, X1;
14023   if( p->validYMD ) return;
14024   if( !p->validJD ){
14025     p->Y = 2000;
14026     p->M = 1;
14027     p->D = 1;
14028   }else{
14029     Z = (int)((p->iJD + 43200000)/86400000);
14030     A = (int)((Z - 1867216.25)/36524.25);
14031     A = Z + 1 + A - (A/4);
14032     B = A + 1524;
14033     C = (int)((B - 122.1)/365.25);
14034     D = (36525*C)/100;
14035     E = (int)((B-D)/30.6001);
14036     X1 = (int)(30.6001*E);
14037     p->D = B - D - X1;
14038     p->M = E<14 ? E-1 : E-13;
14039     p->Y = p->M>2 ? C - 4716 : C - 4715;
14040   }
14041   p->validYMD = 1;
14042 }
14043
14044 /*
14045 ** Compute the Hour, Minute, and Seconds from the julian day number.
14046 */
14047 static void computeHMS(DateTime *p){
14048   int s;
14049   if( p->validHMS ) return;
14050   computeJD(p);
14051   s = (int)((p->iJD + 43200000) % 86400000);
14052   p->s = s/1000.0;
14053   s = (int)p->s;
14054   p->s -= s;
14055   p->h = s/3600;
14056   s -= p->h*3600;
14057   p->m = s/60;
14058   p->s += s - p->m*60;
14059   p->validHMS = 1;
14060 }
14061
14062 /*
14063 ** Compute both YMD and HMS
14064 */
14065 static void computeYMD_HMS(DateTime *p){
14066   computeYMD(p);
14067   computeHMS(p);
14068 }
14069
14070 /*
14071 ** Clear the YMD and HMS and the TZ
14072 */
14073 static void clearYMD_HMS_TZ(DateTime *p){
14074   p->validYMD = 0;
14075   p->validHMS = 0;
14076   p->validTZ = 0;
14077 }
14078
14079 /*
14080 ** On recent Windows platforms, the localtime_s() function is available
14081 ** as part of the "Secure CRT". It is essentially equivalent to 
14082 ** localtime_r() available under most POSIX platforms, except that the 
14083 ** order of the parameters is reversed.
14084 **
14085 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14086 **
14087 ** If the user has not indicated to use localtime_r() or localtime_s()
14088 ** already, check for an MSVC build environment that provides 
14089 ** localtime_s().
14090 */
14091 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14092      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14093 #define HAVE_LOCALTIME_S 1
14094 #endif
14095
14096 #ifndef SQLITE_OMIT_LOCALTIME
14097 /*
14098 ** The following routine implements the rough equivalent of localtime_r()
14099 ** using whatever operating-system specific localtime facility that
14100 ** is available.  This routine returns 0 on success and
14101 ** non-zero on any kind of error.
14102 **
14103 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14104 ** routine will always fail.
14105 */
14106 static int osLocaltime(time_t *t, struct tm *pTm){
14107   int rc;
14108 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14109       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14110   struct tm *pX;
14111 #if SQLITE_THREADSAFE>0
14112   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14113 #endif
14114   sqlite3_mutex_enter(mutex);
14115   pX = localtime(t);
14116 #ifndef SQLITE_OMIT_BUILTIN_TEST
14117   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14118 #endif
14119   if( pX ) *pTm = *pX;
14120   sqlite3_mutex_leave(mutex);
14121   rc = pX==0;
14122 #else
14123 #ifndef SQLITE_OMIT_BUILTIN_TEST
14124   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14125 #endif
14126 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14127   rc = localtime_r(t, pTm)==0;
14128 #else
14129   rc = localtime_s(pTm, t);
14130 #endif /* HAVE_LOCALTIME_R */
14131 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14132   return rc;
14133 }
14134 #endif /* SQLITE_OMIT_LOCALTIME */
14135
14136
14137 #ifndef SQLITE_OMIT_LOCALTIME
14138 /*
14139 ** Compute the difference (in milliseconds) between localtime and UTC
14140 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14141 ** return this value and set *pRc to SQLITE_OK. 
14142 **
14143 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14144 ** is undefined in this case.
14145 */
14146 static sqlite3_int64 localtimeOffset(
14147   DateTime *p,                    /* Date at which to calculate offset */
14148   sqlite3_context *pCtx,          /* Write error here if one occurs */
14149   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14150 ){
14151   DateTime x, y;
14152   time_t t;
14153   struct tm sLocal;
14154
14155   /* Initialize the contents of sLocal to avoid a compiler warning. */
14156   memset(&sLocal, 0, sizeof(sLocal));
14157
14158   x = *p;
14159   computeYMD_HMS(&x);
14160   if( x.Y<1971 || x.Y>=2038 ){
14161     x.Y = 2000;
14162     x.M = 1;
14163     x.D = 1;
14164     x.h = 0;
14165     x.m = 0;
14166     x.s = 0.0;
14167   } else {
14168     int s = (int)(x.s + 0.5);
14169     x.s = s;
14170   }
14171   x.tz = 0;
14172   x.validJD = 0;
14173   computeJD(&x);
14174   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14175   if( osLocaltime(&t, &sLocal) ){
14176     sqlite3_result_error(pCtx, "local time unavailable", -1);
14177     *pRc = SQLITE_ERROR;
14178     return 0;
14179   }
14180   y.Y = sLocal.tm_year + 1900;
14181   y.M = sLocal.tm_mon + 1;
14182   y.D = sLocal.tm_mday;
14183   y.h = sLocal.tm_hour;
14184   y.m = sLocal.tm_min;
14185   y.s = sLocal.tm_sec;
14186   y.validYMD = 1;
14187   y.validHMS = 1;
14188   y.validJD = 0;
14189   y.validTZ = 0;
14190   computeJD(&y);
14191   *pRc = SQLITE_OK;
14192   return y.iJD - x.iJD;
14193 }
14194 #endif /* SQLITE_OMIT_LOCALTIME */
14195
14196 /*
14197 ** Process a modifier to a date-time stamp.  The modifiers are
14198 ** as follows:
14199 **
14200 **     NNN days
14201 **     NNN hours
14202 **     NNN minutes
14203 **     NNN.NNNN seconds
14204 **     NNN months
14205 **     NNN years
14206 **     start of month
14207 **     start of year
14208 **     start of week
14209 **     start of day
14210 **     weekday N
14211 **     unixepoch
14212 **     localtime
14213 **     utc
14214 **
14215 ** Return 0 on success and 1 if there is any kind of error. If the error
14216 ** is in a system call (i.e. localtime()), then an error message is written
14217 ** to context pCtx. If the error is an unrecognized modifier, no error is
14218 ** written to pCtx.
14219 */
14220 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14221   int rc = 1;
14222   int n;
14223   double r;
14224   char *z, zBuf[30];
14225   z = zBuf;
14226   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14227     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14228   }
14229   z[n] = 0;
14230   switch( z[0] ){
14231 #ifndef SQLITE_OMIT_LOCALTIME
14232     case 'l': {
14233       /*    localtime
14234       **
14235       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14236       ** show local time.
14237       */
14238       if( strcmp(z, "localtime")==0 ){
14239         computeJD(p);
14240         p->iJD += localtimeOffset(p, pCtx, &rc);
14241         clearYMD_HMS_TZ(p);
14242       }
14243       break;
14244     }
14245 #endif
14246     case 'u': {
14247       /*
14248       **    unixepoch
14249       **
14250       ** Treat the current value of p->iJD as the number of
14251       ** seconds since 1970.  Convert to a real julian day number.
14252       */
14253       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14254         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14255         clearYMD_HMS_TZ(p);
14256         rc = 0;
14257       }
14258 #ifndef SQLITE_OMIT_LOCALTIME
14259       else if( strcmp(z, "utc")==0 ){
14260         sqlite3_int64 c1;
14261         computeJD(p);
14262         c1 = localtimeOffset(p, pCtx, &rc);
14263         if( rc==SQLITE_OK ){
14264           p->iJD -= c1;
14265           clearYMD_HMS_TZ(p);
14266           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14267         }
14268       }
14269 #endif
14270       break;
14271     }
14272     case 'w': {
14273       /*
14274       **    weekday N
14275       **
14276       ** Move the date to the same time on the next occurrence of
14277       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14278       ** date is already on the appropriate weekday, this is a no-op.
14279       */
14280       if( strncmp(z, "weekday ", 8)==0
14281                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14282                && (n=(int)r)==r && n>=0 && r<7 ){
14283         sqlite3_int64 Z;
14284         computeYMD_HMS(p);
14285         p->validTZ = 0;
14286         p->validJD = 0;
14287         computeJD(p);
14288         Z = ((p->iJD + 129600000)/86400000) % 7;
14289         if( Z>n ) Z -= 7;
14290         p->iJD += (n - Z)*86400000;
14291         clearYMD_HMS_TZ(p);
14292         rc = 0;
14293       }
14294       break;
14295     }
14296     case 's': {
14297       /*
14298       **    start of TTTTT
14299       **
14300       ** Move the date backwards to the beginning of the current day,
14301       ** or month or year.
14302       */
14303       if( strncmp(z, "start of ", 9)!=0 ) break;
14304       z += 9;
14305       computeYMD(p);
14306       p->validHMS = 1;
14307       p->h = p->m = 0;
14308       p->s = 0.0;
14309       p->validTZ = 0;
14310       p->validJD = 0;
14311       if( strcmp(z,"month")==0 ){
14312         p->D = 1;
14313         rc = 0;
14314       }else if( strcmp(z,"year")==0 ){
14315         computeYMD(p);
14316         p->M = 1;
14317         p->D = 1;
14318         rc = 0;
14319       }else if( strcmp(z,"day")==0 ){
14320         rc = 0;
14321       }
14322       break;
14323     }
14324     case '+':
14325     case '-':
14326     case '0':
14327     case '1':
14328     case '2':
14329     case '3':
14330     case '4':
14331     case '5':
14332     case '6':
14333     case '7':
14334     case '8':
14335     case '9': {
14336       double rRounder;
14337       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14338       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14339         rc = 1;
14340         break;
14341       }
14342       if( z[n]==':' ){
14343         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14344         ** specified number of hours, minutes, seconds, and fractional seconds
14345         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14346         ** omitted.
14347         */
14348         const char *z2 = z;
14349         DateTime tx;
14350         sqlite3_int64 day;
14351         if( !sqlite3Isdigit(*z2) ) z2++;
14352         memset(&tx, 0, sizeof(tx));
14353         if( parseHhMmSs(z2, &tx) ) break;
14354         computeJD(&tx);
14355         tx.iJD -= 43200000;
14356         day = tx.iJD/86400000;
14357         tx.iJD -= day*86400000;
14358         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14359         computeJD(p);
14360         clearYMD_HMS_TZ(p);
14361         p->iJD += tx.iJD;
14362         rc = 0;
14363         break;
14364       }
14365       z += n;
14366       while( sqlite3Isspace(*z) ) z++;
14367       n = sqlite3Strlen30(z);
14368       if( n>10 || n<3 ) break;
14369       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14370       computeJD(p);
14371       rc = 0;
14372       rRounder = r<0 ? -0.5 : +0.5;
14373       if( n==3 && strcmp(z,"day")==0 ){
14374         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14375       }else if( n==4 && strcmp(z,"hour")==0 ){
14376         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14377       }else if( n==6 && strcmp(z,"minute")==0 ){
14378         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14379       }else if( n==6 && strcmp(z,"second")==0 ){
14380         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14381       }else if( n==5 && strcmp(z,"month")==0 ){
14382         int x, y;
14383         computeYMD_HMS(p);
14384         p->M += (int)r;
14385         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14386         p->Y += x;
14387         p->M -= x*12;
14388         p->validJD = 0;
14389         computeJD(p);
14390         y = (int)r;
14391         if( y!=r ){
14392           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14393         }
14394       }else if( n==4 && strcmp(z,"year")==0 ){
14395         int y = (int)r;
14396         computeYMD_HMS(p);
14397         p->Y += y;
14398         p->validJD = 0;
14399         computeJD(p);
14400         if( y!=r ){
14401           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14402         }
14403       }else{
14404         rc = 1;
14405       }
14406       clearYMD_HMS_TZ(p);
14407       break;
14408     }
14409     default: {
14410       break;
14411     }
14412   }
14413   return rc;
14414 }
14415
14416 /*
14417 ** Process time function arguments.  argv[0] is a date-time stamp.
14418 ** argv[1] and following are modifiers.  Parse them all and write
14419 ** the resulting time into the DateTime structure p.  Return 0
14420 ** on success and 1 if there are any errors.
14421 **
14422 ** If there are zero parameters (if even argv[0] is undefined)
14423 ** then assume a default value of "now" for argv[0].
14424 */
14425 static int isDate(
14426   sqlite3_context *context, 
14427   int argc, 
14428   sqlite3_value **argv, 
14429   DateTime *p
14430 ){
14431   int i;
14432   const unsigned char *z;
14433   int eType;
14434   memset(p, 0, sizeof(*p));
14435   if( argc==0 ){
14436     return setDateTimeToCurrent(context, p);
14437   }
14438   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14439                    || eType==SQLITE_INTEGER ){
14440     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14441     p->validJD = 1;
14442   }else{
14443     z = sqlite3_value_text(argv[0]);
14444     if( !z || parseDateOrTime(context, (char*)z, p) ){
14445       return 1;
14446     }
14447   }
14448   for(i=1; i<argc; i++){
14449     z = sqlite3_value_text(argv[i]);
14450     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14451   }
14452   return 0;
14453 }
14454
14455
14456 /*
14457 ** The following routines implement the various date and time functions
14458 ** of SQLite.
14459 */
14460
14461 /*
14462 **    julianday( TIMESTRING, MOD, MOD, ...)
14463 **
14464 ** Return the julian day number of the date specified in the arguments
14465 */
14466 static void juliandayFunc(
14467   sqlite3_context *context,
14468   int argc,
14469   sqlite3_value **argv
14470 ){
14471   DateTime x;
14472   if( isDate(context, argc, argv, &x)==0 ){
14473     computeJD(&x);
14474     sqlite3_result_double(context, x.iJD/86400000.0);
14475   }
14476 }
14477
14478 /*
14479 **    datetime( TIMESTRING, MOD, MOD, ...)
14480 **
14481 ** Return YYYY-MM-DD HH:MM:SS
14482 */
14483 static void datetimeFunc(
14484   sqlite3_context *context,
14485   int argc,
14486   sqlite3_value **argv
14487 ){
14488   DateTime x;
14489   if( isDate(context, argc, argv, &x)==0 ){
14490     char zBuf[100];
14491     computeYMD_HMS(&x);
14492     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14493                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14494     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14495   }
14496 }
14497
14498 /*
14499 **    time( TIMESTRING, MOD, MOD, ...)
14500 **
14501 ** Return HH:MM:SS
14502 */
14503 static void timeFunc(
14504   sqlite3_context *context,
14505   int argc,
14506   sqlite3_value **argv
14507 ){
14508   DateTime x;
14509   if( isDate(context, argc, argv, &x)==0 ){
14510     char zBuf[100];
14511     computeHMS(&x);
14512     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14513     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14514   }
14515 }
14516
14517 /*
14518 **    date( TIMESTRING, MOD, MOD, ...)
14519 **
14520 ** Return YYYY-MM-DD
14521 */
14522 static void dateFunc(
14523   sqlite3_context *context,
14524   int argc,
14525   sqlite3_value **argv
14526 ){
14527   DateTime x;
14528   if( isDate(context, argc, argv, &x)==0 ){
14529     char zBuf[100];
14530     computeYMD(&x);
14531     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14532     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14533   }
14534 }
14535
14536 /*
14537 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14538 **
14539 ** Return a string described by FORMAT.  Conversions as follows:
14540 **
14541 **   %d  day of month
14542 **   %f  ** fractional seconds  SS.SSS
14543 **   %H  hour 00-24
14544 **   %j  day of year 000-366
14545 **   %J  ** Julian day number
14546 **   %m  month 01-12
14547 **   %M  minute 00-59
14548 **   %s  seconds since 1970-01-01
14549 **   %S  seconds 00-59
14550 **   %w  day of week 0-6  sunday==0
14551 **   %W  week of year 00-53
14552 **   %Y  year 0000-9999
14553 **   %%  %
14554 */
14555 static void strftimeFunc(
14556   sqlite3_context *context,
14557   int argc,
14558   sqlite3_value **argv
14559 ){
14560   DateTime x;
14561   u64 n;
14562   size_t i,j;
14563   char *z;
14564   sqlite3 *db;
14565   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14566   char zBuf[100];
14567   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14568   db = sqlite3_context_db_handle(context);
14569   for(i=0, n=1; zFmt[i]; i++, n++){
14570     if( zFmt[i]=='%' ){
14571       switch( zFmt[i+1] ){
14572         case 'd':
14573         case 'H':
14574         case 'm':
14575         case 'M':
14576         case 'S':
14577         case 'W':
14578           n++;
14579           /* fall thru */
14580         case 'w':
14581         case '%':
14582           break;
14583         case 'f':
14584           n += 8;
14585           break;
14586         case 'j':
14587           n += 3;
14588           break;
14589         case 'Y':
14590           n += 8;
14591           break;
14592         case 's':
14593         case 'J':
14594           n += 50;
14595           break;
14596         default:
14597           return;  /* ERROR.  return a NULL */
14598       }
14599       i++;
14600     }
14601   }
14602   testcase( n==sizeof(zBuf)-1 );
14603   testcase( n==sizeof(zBuf) );
14604   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14605   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14606   if( n<sizeof(zBuf) ){
14607     z = zBuf;
14608   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14609     sqlite3_result_error_toobig(context);
14610     return;
14611   }else{
14612     z = sqlite3DbMallocRaw(db, (int)n);
14613     if( z==0 ){
14614       sqlite3_result_error_nomem(context);
14615       return;
14616     }
14617   }
14618   computeJD(&x);
14619   computeYMD_HMS(&x);
14620   for(i=j=0; zFmt[i]; i++){
14621     if( zFmt[i]!='%' ){
14622       z[j++] = zFmt[i];
14623     }else{
14624       i++;
14625       switch( zFmt[i] ){
14626         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14627         case 'f': {
14628           double s = x.s;
14629           if( s>59.999 ) s = 59.999;
14630           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14631           j += sqlite3Strlen30(&z[j]);
14632           break;
14633         }
14634         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14635         case 'W': /* Fall thru */
14636         case 'j': {
14637           int nDay;             /* Number of days since 1st day of year */
14638           DateTime y = x;
14639           y.validJD = 0;
14640           y.M = 1;
14641           y.D = 1;
14642           computeJD(&y);
14643           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14644           if( zFmt[i]=='W' ){
14645             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14646             wd = (int)(((x.iJD+43200000)/86400000)%7);
14647             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14648             j += 2;
14649           }else{
14650             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14651             j += 3;
14652           }
14653           break;
14654         }
14655         case 'J': {
14656           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14657           j+=sqlite3Strlen30(&z[j]);
14658           break;
14659         }
14660         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14661         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14662         case 's': {
14663           sqlite3_snprintf(30,&z[j],"%lld",
14664                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14665           j += sqlite3Strlen30(&z[j]);
14666           break;
14667         }
14668         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14669         case 'w': {
14670           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14671           break;
14672         }
14673         case 'Y': {
14674           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14675           break;
14676         }
14677         default:   z[j++] = '%'; break;
14678       }
14679     }
14680   }
14681   z[j] = 0;
14682   sqlite3_result_text(context, z, -1,
14683                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14684 }
14685
14686 /*
14687 ** current_time()
14688 **
14689 ** This function returns the same value as time('now').
14690 */
14691 static void ctimeFunc(
14692   sqlite3_context *context,
14693   int NotUsed,
14694   sqlite3_value **NotUsed2
14695 ){
14696   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14697   timeFunc(context, 0, 0);
14698 }
14699
14700 /*
14701 ** current_date()
14702 **
14703 ** This function returns the same value as date('now').
14704 */
14705 static void cdateFunc(
14706   sqlite3_context *context,
14707   int NotUsed,
14708   sqlite3_value **NotUsed2
14709 ){
14710   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14711   dateFunc(context, 0, 0);
14712 }
14713
14714 /*
14715 ** current_timestamp()
14716 **
14717 ** This function returns the same value as datetime('now').
14718 */
14719 static void ctimestampFunc(
14720   sqlite3_context *context,
14721   int NotUsed,
14722   sqlite3_value **NotUsed2
14723 ){
14724   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14725   datetimeFunc(context, 0, 0);
14726 }
14727 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14728
14729 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14730 /*
14731 ** If the library is compiled to omit the full-scale date and time
14732 ** handling (to get a smaller binary), the following minimal version
14733 ** of the functions current_time(), current_date() and current_timestamp()
14734 ** are included instead. This is to support column declarations that
14735 ** include "DEFAULT CURRENT_TIME" etc.
14736 **
14737 ** This function uses the C-library functions time(), gmtime()
14738 ** and strftime(). The format string to pass to strftime() is supplied
14739 ** as the user-data for the function.
14740 */
14741 static void currentTimeFunc(
14742   sqlite3_context *context,
14743   int argc,
14744   sqlite3_value **argv
14745 ){
14746   time_t t;
14747   char *zFormat = (char *)sqlite3_user_data(context);
14748   sqlite3 *db;
14749   sqlite3_int64 iT;
14750   struct tm *pTm;
14751   struct tm sNow;
14752   char zBuf[20];
14753
14754   UNUSED_PARAMETER(argc);
14755   UNUSED_PARAMETER(argv);
14756
14757   db = sqlite3_context_db_handle(context);
14758   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14759   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14760 #ifdef HAVE_GMTIME_R
14761   pTm = gmtime_r(&t, &sNow);
14762 #else
14763   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14764   pTm = gmtime(&t);
14765   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14766   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14767 #endif
14768   if( pTm ){
14769     strftime(zBuf, 20, zFormat, &sNow);
14770     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14771   }
14772 }
14773 #endif
14774
14775 /*
14776 ** This function registered all of the above C functions as SQL
14777 ** functions.  This should be the only routine in this file with
14778 ** external linkage.
14779 */
14780 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14781   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14782 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14783     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14784     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14785     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14786     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14787     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14788     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14789     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14790     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14791 #else
14792     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14793     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14794     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14795 #endif
14796   };
14797   int i;
14798   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14799   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14800
14801   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14802     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14803   }
14804 }
14805
14806 /************** End of date.c ************************************************/
14807 /************** Begin file os.c **********************************************/
14808 /*
14809 ** 2005 November 29
14810 **
14811 ** The author disclaims copyright to this source code.  In place of
14812 ** a legal notice, here is a blessing:
14813 **
14814 **    May you do good and not evil.
14815 **    May you find forgiveness for yourself and forgive others.
14816 **    May you share freely, never taking more than you give.
14817 **
14818 ******************************************************************************
14819 **
14820 ** This file contains OS interface code that is common to all
14821 ** architectures.
14822 */
14823 #define _SQLITE_OS_C_ 1
14824 #undef _SQLITE_OS_C_
14825
14826 /*
14827 ** The default SQLite sqlite3_vfs implementations do not allocate
14828 ** memory (actually, os_unix.c allocates a small amount of memory
14829 ** from within OsOpen()), but some third-party implementations may.
14830 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14831 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14832 **
14833 ** The following functions are instrumented for malloc() failure 
14834 ** testing:
14835 **
14836 **     sqlite3OsRead()
14837 **     sqlite3OsWrite()
14838 **     sqlite3OsSync()
14839 **     sqlite3OsFileSize()
14840 **     sqlite3OsLock()
14841 **     sqlite3OsCheckReservedLock()
14842 **     sqlite3OsFileControl()
14843 **     sqlite3OsShmMap()
14844 **     sqlite3OsOpen()
14845 **     sqlite3OsDelete()
14846 **     sqlite3OsAccess()
14847 **     sqlite3OsFullPathname()
14848 **
14849 */
14850 #if defined(SQLITE_TEST)
14851 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14852   #define DO_OS_MALLOC_TEST(x)                                       \
14853   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14854     void *pTstAlloc = sqlite3Malloc(10);                             \
14855     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14856     sqlite3_free(pTstAlloc);                                         \
14857   }
14858 #else
14859   #define DO_OS_MALLOC_TEST(x)
14860 #endif
14861
14862 /*
14863 ** The following routines are convenience wrappers around methods
14864 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14865 ** of this would be completely automatic if SQLite were coded using
14866 ** C++ instead of plain old C.
14867 */
14868 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14869   int rc = SQLITE_OK;
14870   if( pId->pMethods ){
14871     rc = pId->pMethods->xClose(pId);
14872     pId->pMethods = 0;
14873   }
14874   return rc;
14875 }
14876 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14877   DO_OS_MALLOC_TEST(id);
14878   return id->pMethods->xRead(id, pBuf, amt, offset);
14879 }
14880 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14881   DO_OS_MALLOC_TEST(id);
14882   return id->pMethods->xWrite(id, pBuf, amt, offset);
14883 }
14884 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14885   return id->pMethods->xTruncate(id, size);
14886 }
14887 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14888   DO_OS_MALLOC_TEST(id);
14889   return id->pMethods->xSync(id, flags);
14890 }
14891 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14892   DO_OS_MALLOC_TEST(id);
14893   return id->pMethods->xFileSize(id, pSize);
14894 }
14895 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14896   DO_OS_MALLOC_TEST(id);
14897   return id->pMethods->xLock(id, lockType);
14898 }
14899 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14900   return id->pMethods->xUnlock(id, lockType);
14901 }
14902 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14903   DO_OS_MALLOC_TEST(id);
14904   return id->pMethods->xCheckReservedLock(id, pResOut);
14905 }
14906
14907 /*
14908 ** Use sqlite3OsFileControl() when we are doing something that might fail
14909 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
14910 ** when simply tossing information over the wall to the VFS and we do not
14911 ** really care if the VFS receives and understands the information since it
14912 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
14913 ** routine has no return value since the return value would be meaningless.
14914 */
14915 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14916   DO_OS_MALLOC_TEST(id);
14917   return id->pMethods->xFileControl(id, op, pArg);
14918 }
14919 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
14920   (void)id->pMethods->xFileControl(id, op, pArg);
14921 }
14922
14923 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14924   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14925   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14926 }
14927 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14928   return id->pMethods->xDeviceCharacteristics(id);
14929 }
14930 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14931   return id->pMethods->xShmLock(id, offset, n, flags);
14932 }
14933 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14934   id->pMethods->xShmBarrier(id);
14935 }
14936 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14937   return id->pMethods->xShmUnmap(id, deleteFlag);
14938 }
14939 SQLITE_PRIVATE int sqlite3OsShmMap(
14940   sqlite3_file *id,               /* Database file handle */
14941   int iPage,
14942   int pgsz,
14943   int bExtend,                    /* True to extend file if necessary */
14944   void volatile **pp              /* OUT: Pointer to mapping */
14945 ){
14946   DO_OS_MALLOC_TEST(id);
14947   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14948 }
14949
14950 /*
14951 ** The next group of routines are convenience wrappers around the
14952 ** VFS methods.
14953 */
14954 SQLITE_PRIVATE int sqlite3OsOpen(
14955   sqlite3_vfs *pVfs, 
14956   const char *zPath, 
14957   sqlite3_file *pFile, 
14958   int flags, 
14959   int *pFlagsOut
14960 ){
14961   int rc;
14962   DO_OS_MALLOC_TEST(0);
14963   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14964   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14965   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14966   ** reaching the VFS. */
14967   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14968   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14969   return rc;
14970 }
14971 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14972   DO_OS_MALLOC_TEST(0);
14973   assert( dirSync==0 || dirSync==1 );
14974   return pVfs->xDelete(pVfs, zPath, dirSync);
14975 }
14976 SQLITE_PRIVATE int sqlite3OsAccess(
14977   sqlite3_vfs *pVfs, 
14978   const char *zPath, 
14979   int flags, 
14980   int *pResOut
14981 ){
14982   DO_OS_MALLOC_TEST(0);
14983   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14984 }
14985 SQLITE_PRIVATE int sqlite3OsFullPathname(
14986   sqlite3_vfs *pVfs, 
14987   const char *zPath, 
14988   int nPathOut, 
14989   char *zPathOut
14990 ){
14991   DO_OS_MALLOC_TEST(0);
14992   zPathOut[0] = 0;
14993   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14994 }
14995 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14996 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14997   return pVfs->xDlOpen(pVfs, zPath);
14998 }
14999 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15000   pVfs->xDlError(pVfs, nByte, zBufOut);
15001 }
15002 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15003   return pVfs->xDlSym(pVfs, pHdle, zSym);
15004 }
15005 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15006   pVfs->xDlClose(pVfs, pHandle);
15007 }
15008 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15009 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15010   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15011 }
15012 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15013   return pVfs->xSleep(pVfs, nMicro);
15014 }
15015 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15016   int rc;
15017   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15018   ** method to get the current date and time if that method is available
15019   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15020   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15021   ** unavailable.
15022   */
15023   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15024     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15025   }else{
15026     double r;
15027     rc = pVfs->xCurrentTime(pVfs, &r);
15028     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15029   }
15030   return rc;
15031 }
15032
15033 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15034   sqlite3_vfs *pVfs, 
15035   const char *zFile, 
15036   sqlite3_file **ppFile, 
15037   int flags,
15038   int *pOutFlags
15039 ){
15040   int rc = SQLITE_NOMEM;
15041   sqlite3_file *pFile;
15042   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15043   if( pFile ){
15044     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15045     if( rc!=SQLITE_OK ){
15046       sqlite3_free(pFile);
15047     }else{
15048       *ppFile = pFile;
15049     }
15050   }
15051   return rc;
15052 }
15053 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15054   int rc = SQLITE_OK;
15055   assert( pFile );
15056   rc = sqlite3OsClose(pFile);
15057   sqlite3_free(pFile);
15058   return rc;
15059 }
15060
15061 /*
15062 ** This function is a wrapper around the OS specific implementation of
15063 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15064 ** ability to simulate a malloc failure, so that the handling of an
15065 ** error in sqlite3_os_init() by the upper layers can be tested.
15066 */
15067 SQLITE_PRIVATE int sqlite3OsInit(void){
15068   void *p = sqlite3_malloc(10);
15069   if( p==0 ) return SQLITE_NOMEM;
15070   sqlite3_free(p);
15071   return sqlite3_os_init();
15072 }
15073
15074 /*
15075 ** The list of all registered VFS implementations.
15076 */
15077 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15078 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15079
15080 /*
15081 ** Locate a VFS by name.  If no name is given, simply return the
15082 ** first VFS on the list.
15083 */
15084 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15085   sqlite3_vfs *pVfs = 0;
15086 #if SQLITE_THREADSAFE
15087   sqlite3_mutex *mutex;
15088 #endif
15089 #ifndef SQLITE_OMIT_AUTOINIT
15090   int rc = sqlite3_initialize();
15091   if( rc ) return 0;
15092 #endif
15093 #if SQLITE_THREADSAFE
15094   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15095 #endif
15096   sqlite3_mutex_enter(mutex);
15097   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15098     if( zVfs==0 ) break;
15099     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15100   }
15101   sqlite3_mutex_leave(mutex);
15102   return pVfs;
15103 }
15104
15105 /*
15106 ** Unlink a VFS from the linked list
15107 */
15108 static void vfsUnlink(sqlite3_vfs *pVfs){
15109   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15110   if( pVfs==0 ){
15111     /* No-op */
15112   }else if( vfsList==pVfs ){
15113     vfsList = pVfs->pNext;
15114   }else if( vfsList ){
15115     sqlite3_vfs *p = vfsList;
15116     while( p->pNext && p->pNext!=pVfs ){
15117       p = p->pNext;
15118     }
15119     if( p->pNext==pVfs ){
15120       p->pNext = pVfs->pNext;
15121     }
15122   }
15123 }
15124
15125 /*
15126 ** Register a VFS with the system.  It is harmless to register the same
15127 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15128 ** true.
15129 */
15130 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15131   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15132 #ifndef SQLITE_OMIT_AUTOINIT
15133   int rc = sqlite3_initialize();
15134   if( rc ) return rc;
15135 #endif
15136   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15137   sqlite3_mutex_enter(mutex);
15138   vfsUnlink(pVfs);
15139   if( makeDflt || vfsList==0 ){
15140     pVfs->pNext = vfsList;
15141     vfsList = pVfs;
15142   }else{
15143     pVfs->pNext = vfsList->pNext;
15144     vfsList->pNext = pVfs;
15145   }
15146   assert(vfsList);
15147   sqlite3_mutex_leave(mutex);
15148   return SQLITE_OK;
15149 }
15150
15151 /*
15152 ** Unregister a VFS so that it is no longer accessible.
15153 */
15154 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15155 #if SQLITE_THREADSAFE
15156   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15157 #endif
15158   sqlite3_mutex_enter(mutex);
15159   vfsUnlink(pVfs);
15160   sqlite3_mutex_leave(mutex);
15161   return SQLITE_OK;
15162 }
15163
15164 /************** End of os.c **************************************************/
15165 /************** Begin file fault.c *******************************************/
15166 /*
15167 ** 2008 Jan 22
15168 **
15169 ** The author disclaims copyright to this source code.  In place of
15170 ** a legal notice, here is a blessing:
15171 **
15172 **    May you do good and not evil.
15173 **    May you find forgiveness for yourself and forgive others.
15174 **    May you share freely, never taking more than you give.
15175 **
15176 *************************************************************************
15177 **
15178 ** This file contains code to support the concept of "benign" 
15179 ** malloc failures (when the xMalloc() or xRealloc() method of the
15180 ** sqlite3_mem_methods structure fails to allocate a block of memory
15181 ** and returns 0). 
15182 **
15183 ** Most malloc failures are non-benign. After they occur, SQLite
15184 ** abandons the current operation and returns an error code (usually
15185 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15186 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15187 ** is completely recoverable simply by not carrying out the resize. The 
15188 ** hash table will continue to function normally.  So a malloc failure 
15189 ** during a hash table resize is a benign fault.
15190 */
15191
15192
15193 #ifndef SQLITE_OMIT_BUILTIN_TEST
15194
15195 /*
15196 ** Global variables.
15197 */
15198 typedef struct BenignMallocHooks BenignMallocHooks;
15199 static SQLITE_WSD struct BenignMallocHooks {
15200   void (*xBenignBegin)(void);
15201   void (*xBenignEnd)(void);
15202 } sqlite3Hooks = { 0, 0 };
15203
15204 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15205 ** structure.  If writable static data is unsupported on the target,
15206 ** we have to locate the state vector at run-time.  In the more common
15207 ** case where writable static data is supported, wsdHooks can refer directly
15208 ** to the "sqlite3Hooks" state vector declared above.
15209 */
15210 #ifdef SQLITE_OMIT_WSD
15211 # define wsdHooksInit \
15212   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15213 # define wsdHooks x[0]
15214 #else
15215 # define wsdHooksInit
15216 # define wsdHooks sqlite3Hooks
15217 #endif
15218
15219
15220 /*
15221 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15222 ** sqlite3EndBenignMalloc() are called, respectively.
15223 */
15224 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15225   void (*xBenignBegin)(void),
15226   void (*xBenignEnd)(void)
15227 ){
15228   wsdHooksInit;
15229   wsdHooks.xBenignBegin = xBenignBegin;
15230   wsdHooks.xBenignEnd = xBenignEnd;
15231 }
15232
15233 /*
15234 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15235 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15236 ** indicates that subsequent malloc failures are non-benign.
15237 */
15238 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15239   wsdHooksInit;
15240   if( wsdHooks.xBenignBegin ){
15241     wsdHooks.xBenignBegin();
15242   }
15243 }
15244 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15245   wsdHooksInit;
15246   if( wsdHooks.xBenignEnd ){
15247     wsdHooks.xBenignEnd();
15248   }
15249 }
15250
15251 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15252
15253 /************** End of fault.c ***********************************************/
15254 /************** Begin file mem0.c ********************************************/
15255 /*
15256 ** 2008 October 28
15257 **
15258 ** The author disclaims copyright to this source code.  In place of
15259 ** a legal notice, here is a blessing:
15260 **
15261 **    May you do good and not evil.
15262 **    May you find forgiveness for yourself and forgive others.
15263 **    May you share freely, never taking more than you give.
15264 **
15265 *************************************************************************
15266 **
15267 ** This file contains a no-op memory allocation drivers for use when
15268 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15269 ** here always fail.  SQLite will not operate with these drivers.  These
15270 ** are merely placeholders.  Real drivers must be substituted using
15271 ** sqlite3_config() before SQLite will operate.
15272 */
15273
15274 /*
15275 ** This version of the memory allocator is the default.  It is
15276 ** used when no other memory allocator is specified using compile-time
15277 ** macros.
15278 */
15279 #ifdef SQLITE_ZERO_MALLOC
15280
15281 /*
15282 ** No-op versions of all memory allocation routines
15283 */
15284 static void *sqlite3MemMalloc(int nByte){ return 0; }
15285 static void sqlite3MemFree(void *pPrior){ return; }
15286 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15287 static int sqlite3MemSize(void *pPrior){ return 0; }
15288 static int sqlite3MemRoundup(int n){ return n; }
15289 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15290 static void sqlite3MemShutdown(void *NotUsed){ return; }
15291
15292 /*
15293 ** This routine is the only routine in this file with external linkage.
15294 **
15295 ** Populate the low-level memory allocation function pointers in
15296 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15297 */
15298 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15299   static const sqlite3_mem_methods defaultMethods = {
15300      sqlite3MemMalloc,
15301      sqlite3MemFree,
15302      sqlite3MemRealloc,
15303      sqlite3MemSize,
15304      sqlite3MemRoundup,
15305      sqlite3MemInit,
15306      sqlite3MemShutdown,
15307      0
15308   };
15309   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15310 }
15311
15312 #endif /* SQLITE_ZERO_MALLOC */
15313
15314 /************** End of mem0.c ************************************************/
15315 /************** Begin file mem1.c ********************************************/
15316 /*
15317 ** 2007 August 14
15318 **
15319 ** The author disclaims copyright to this source code.  In place of
15320 ** a legal notice, here is a blessing:
15321 **
15322 **    May you do good and not evil.
15323 **    May you find forgiveness for yourself and forgive others.
15324 **    May you share freely, never taking more than you give.
15325 **
15326 *************************************************************************
15327 **
15328 ** This file contains low-level memory allocation drivers for when
15329 ** SQLite will use the standard C-library malloc/realloc/free interface
15330 ** to obtain the memory it needs.
15331 **
15332 ** This file contains implementations of the low-level memory allocation
15333 ** routines specified in the sqlite3_mem_methods object.  The content of
15334 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15335 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15336 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15337 ** default configuration is to use memory allocation routines in this
15338 ** file.
15339 **
15340 ** C-preprocessor macro summary:
15341 **
15342 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15343 **                                the malloc_usable_size() interface exists
15344 **                                on the target platform.  Or, this symbol
15345 **                                can be set manually, if desired.
15346 **                                If an equivalent interface exists by
15347 **                                a different name, using a separate -D
15348 **                                option to rename it.
15349 **
15350 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15351 **                                memory allocator.  Set this symbol to enable
15352 **                                building on older macs.
15353 **
15354 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15355 **                                _msize() on windows systems.  This might
15356 **                                be necessary when compiling for Delphi,
15357 **                                for example.
15358 */
15359
15360 /*
15361 ** This version of the memory allocator is the default.  It is
15362 ** used when no other memory allocator is specified using compile-time
15363 ** macros.
15364 */
15365 #ifdef SQLITE_SYSTEM_MALLOC
15366
15367 /*
15368 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15369 ** The use of _msize() is automatic, but can be disabled by compiling
15370 ** with -DSQLITE_WITHOUT_MSIZE
15371 */
15372 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15373 # define SQLITE_MALLOCSIZE _msize
15374 #endif
15375
15376 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15377
15378 /*
15379 ** Use the zone allocator available on apple products unless the
15380 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15381 */
15382 #include <sys/sysctl.h>
15383 #include <malloc/malloc.h>
15384 #include <libkern/OSAtomic.h>
15385 static malloc_zone_t* _sqliteZone_;
15386 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15387 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15388 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15389 #define SQLITE_MALLOCSIZE(x) \
15390         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15391
15392 #else /* if not __APPLE__ */
15393
15394 /*
15395 ** Use standard C library malloc and free on non-Apple systems.  
15396 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15397 */
15398 #define SQLITE_MALLOC(x)    malloc(x)
15399 #define SQLITE_FREE(x)      free(x)
15400 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15401
15402 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15403       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15404 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15405 #endif
15406 #ifdef HAVE_MALLOC_USABLE_SIZE
15407 # ifndef SQLITE_MALLOCSIZE
15408 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15409 # endif
15410 #else
15411 # undef SQLITE_MALLOCSIZE
15412 #endif
15413
15414 #endif /* __APPLE__ or not __APPLE__ */
15415
15416 /*
15417 ** Like malloc(), but remember the size of the allocation
15418 ** so that we can find it later using sqlite3MemSize().
15419 **
15420 ** For this low-level routine, we are guaranteed that nByte>0 because
15421 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15422 ** routines.
15423 */
15424 static void *sqlite3MemMalloc(int nByte){
15425 #ifdef SQLITE_MALLOCSIZE
15426   void *p = SQLITE_MALLOC( nByte );
15427   if( p==0 ){
15428     testcase( sqlite3GlobalConfig.xLog!=0 );
15429     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15430   }
15431   return p;
15432 #else
15433   sqlite3_int64 *p;
15434   assert( nByte>0 );
15435   nByte = ROUND8(nByte);
15436   p = SQLITE_MALLOC( nByte+8 );
15437   if( p ){
15438     p[0] = nByte;
15439     p++;
15440   }else{
15441     testcase( sqlite3GlobalConfig.xLog!=0 );
15442     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15443   }
15444   return (void *)p;
15445 #endif
15446 }
15447
15448 /*
15449 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15450 ** or sqlite3MemRealloc().
15451 **
15452 ** For this low-level routine, we already know that pPrior!=0 since
15453 ** cases where pPrior==0 will have been intecepted and dealt with
15454 ** by higher-level routines.
15455 */
15456 static void sqlite3MemFree(void *pPrior){
15457 #ifdef SQLITE_MALLOCSIZE
15458   SQLITE_FREE(pPrior);
15459 #else
15460   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15461   assert( pPrior!=0 );
15462   p--;
15463   SQLITE_FREE(p);
15464 #endif
15465 }
15466
15467 /*
15468 ** Report the allocated size of a prior return from xMalloc()
15469 ** or xRealloc().
15470 */
15471 static int sqlite3MemSize(void *pPrior){
15472 #ifdef SQLITE_MALLOCSIZE
15473   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15474 #else
15475   sqlite3_int64 *p;
15476   if( pPrior==0 ) return 0;
15477   p = (sqlite3_int64*)pPrior;
15478   p--;
15479   return (int)p[0];
15480 #endif
15481 }
15482
15483 /*
15484 ** Like realloc().  Resize an allocation previously obtained from
15485 ** sqlite3MemMalloc().
15486 **
15487 ** For this low-level interface, we know that pPrior!=0.  Cases where
15488 ** pPrior==0 while have been intercepted by higher-level routine and
15489 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15490 ** cases where nByte<=0 will have been intercepted by higher-level
15491 ** routines and redirected to xFree.
15492 */
15493 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15494 #ifdef SQLITE_MALLOCSIZE
15495   void *p = SQLITE_REALLOC(pPrior, nByte);
15496   if( p==0 ){
15497     testcase( sqlite3GlobalConfig.xLog!=0 );
15498     sqlite3_log(SQLITE_NOMEM,
15499       "failed memory resize %u to %u bytes",
15500       SQLITE_MALLOCSIZE(pPrior), nByte);
15501   }
15502   return p;
15503 #else
15504   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15505   assert( pPrior!=0 && nByte>0 );
15506   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15507   p--;
15508   p = SQLITE_REALLOC(p, nByte+8 );
15509   if( p ){
15510     p[0] = nByte;
15511     p++;
15512   }else{
15513     testcase( sqlite3GlobalConfig.xLog!=0 );
15514     sqlite3_log(SQLITE_NOMEM,
15515       "failed memory resize %u to %u bytes",
15516       sqlite3MemSize(pPrior), nByte);
15517   }
15518   return (void*)p;
15519 #endif
15520 }
15521
15522 /*
15523 ** Round up a request size to the next valid allocation size.
15524 */
15525 static int sqlite3MemRoundup(int n){
15526   return ROUND8(n);
15527 }
15528
15529 /*
15530 ** Initialize this module.
15531 */
15532 static int sqlite3MemInit(void *NotUsed){
15533 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15534   int cpuCount;
15535   size_t len;
15536   if( _sqliteZone_ ){
15537     return SQLITE_OK;
15538   }
15539   len = sizeof(cpuCount);
15540   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15541   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15542   if( cpuCount>1 ){
15543     /* defer MT decisions to system malloc */
15544     _sqliteZone_ = malloc_default_zone();
15545   }else{
15546     /* only 1 core, use our own zone to contention over global locks, 
15547     ** e.g. we have our own dedicated locks */
15548     bool success;
15549     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15550     malloc_set_zone_name(newzone, "Sqlite_Heap");
15551     do{
15552       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
15553                                  (void * volatile *)&_sqliteZone_);
15554     }while(!_sqliteZone_);
15555     if( !success ){
15556       /* somebody registered a zone first */
15557       malloc_destroy_zone(newzone);
15558     }
15559   }
15560 #endif
15561   UNUSED_PARAMETER(NotUsed);
15562   return SQLITE_OK;
15563 }
15564
15565 /*
15566 ** Deinitialize this module.
15567 */
15568 static void sqlite3MemShutdown(void *NotUsed){
15569   UNUSED_PARAMETER(NotUsed);
15570   return;
15571 }
15572
15573 /*
15574 ** This routine is the only routine in this file with external linkage.
15575 **
15576 ** Populate the low-level memory allocation function pointers in
15577 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15578 */
15579 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15580   static const sqlite3_mem_methods defaultMethods = {
15581      sqlite3MemMalloc,
15582      sqlite3MemFree,
15583      sqlite3MemRealloc,
15584      sqlite3MemSize,
15585      sqlite3MemRoundup,
15586      sqlite3MemInit,
15587      sqlite3MemShutdown,
15588      0
15589   };
15590   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15591 }
15592
15593 #endif /* SQLITE_SYSTEM_MALLOC */
15594
15595 /************** End of mem1.c ************************************************/
15596 /************** Begin file mem2.c ********************************************/
15597 /*
15598 ** 2007 August 15
15599 **
15600 ** The author disclaims copyright to this source code.  In place of
15601 ** a legal notice, here is a blessing:
15602 **
15603 **    May you do good and not evil.
15604 **    May you find forgiveness for yourself and forgive others.
15605 **    May you share freely, never taking more than you give.
15606 **
15607 *************************************************************************
15608 **
15609 ** This file contains low-level memory allocation drivers for when
15610 ** SQLite will use the standard C-library malloc/realloc/free interface
15611 ** to obtain the memory it needs while adding lots of additional debugging
15612 ** information to each allocation in order to help detect and fix memory
15613 ** leaks and memory usage errors.
15614 **
15615 ** This file contains implementations of the low-level memory allocation
15616 ** routines specified in the sqlite3_mem_methods object.
15617 */
15618
15619 /*
15620 ** This version of the memory allocator is used only if the
15621 ** SQLITE_MEMDEBUG macro is defined
15622 */
15623 #ifdef SQLITE_MEMDEBUG
15624
15625 /*
15626 ** The backtrace functionality is only available with GLIBC
15627 */
15628 #ifdef __GLIBC__
15629   extern int backtrace(void**,int);
15630   extern void backtrace_symbols_fd(void*const*,int,int);
15631 #else
15632 # define backtrace(A,B) 1
15633 # define backtrace_symbols_fd(A,B,C)
15634 #endif
15635 /* #include <stdio.h> */
15636
15637 /*
15638 ** Each memory allocation looks like this:
15639 **
15640 **  ------------------------------------------------------------------------
15641 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15642 **  ------------------------------------------------------------------------
15643 **
15644 ** The application code sees only a pointer to the allocation.  We have
15645 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15646 ** MemBlockHdr tells us the size of the allocation and the number of
15647 ** backtrace pointers.  There is also a guard word at the end of the
15648 ** MemBlockHdr.
15649 */
15650 struct MemBlockHdr {
15651   i64 iSize;                          /* Size of this allocation */
15652   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15653   char nBacktrace;                    /* Number of backtraces on this alloc */
15654   char nBacktraceSlots;               /* Available backtrace slots */
15655   u8 nTitle;                          /* Bytes of title; includes '\0' */
15656   u8 eType;                           /* Allocation type code */
15657   int iForeGuard;                     /* Guard word for sanity */
15658 };
15659
15660 /*
15661 ** Guard words
15662 */
15663 #define FOREGUARD 0x80F5E153
15664 #define REARGUARD 0xE4676B53
15665
15666 /*
15667 ** Number of malloc size increments to track.
15668 */
15669 #define NCSIZE  1000
15670
15671 /*
15672 ** All of the static variables used by this module are collected
15673 ** into a single structure named "mem".  This is to keep the
15674 ** static variables organized and to reduce namespace pollution
15675 ** when this module is combined with other in the amalgamation.
15676 */
15677 static struct {
15678   
15679   /*
15680   ** Mutex to control access to the memory allocation subsystem.
15681   */
15682   sqlite3_mutex *mutex;
15683
15684   /*
15685   ** Head and tail of a linked list of all outstanding allocations
15686   */
15687   struct MemBlockHdr *pFirst;
15688   struct MemBlockHdr *pLast;
15689   
15690   /*
15691   ** The number of levels of backtrace to save in new allocations.
15692   */
15693   int nBacktrace;
15694   void (*xBacktrace)(int, int, void **);
15695
15696   /*
15697   ** Title text to insert in front of each block
15698   */
15699   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15700   char zTitle[100];  /* The title text */
15701
15702   /* 
15703   ** sqlite3MallocDisallow() increments the following counter.
15704   ** sqlite3MallocAllow() decrements it.
15705   */
15706   int disallow; /* Do not allow memory allocation */
15707
15708   /*
15709   ** Gather statistics on the sizes of memory allocations.
15710   ** nAlloc[i] is the number of allocation attempts of i*8
15711   ** bytes.  i==NCSIZE is the number of allocation attempts for
15712   ** sizes more than NCSIZE*8 bytes.
15713   */
15714   int nAlloc[NCSIZE];      /* Total number of allocations */
15715   int nCurrent[NCSIZE];    /* Current number of allocations */
15716   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15717
15718 } mem;
15719
15720
15721 /*
15722 ** Adjust memory usage statistics
15723 */
15724 static void adjustStats(int iSize, int increment){
15725   int i = ROUND8(iSize)/8;
15726   if( i>NCSIZE-1 ){
15727     i = NCSIZE - 1;
15728   }
15729   if( increment>0 ){
15730     mem.nAlloc[i]++;
15731     mem.nCurrent[i]++;
15732     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15733       mem.mxCurrent[i] = mem.nCurrent[i];
15734     }
15735   }else{
15736     mem.nCurrent[i]--;
15737     assert( mem.nCurrent[i]>=0 );
15738   }
15739 }
15740
15741 /*
15742 ** Given an allocation, find the MemBlockHdr for that allocation.
15743 **
15744 ** This routine checks the guards at either end of the allocation and
15745 ** if they are incorrect it asserts.
15746 */
15747 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15748   struct MemBlockHdr *p;
15749   int *pInt;
15750   u8 *pU8;
15751   int nReserve;
15752
15753   p = (struct MemBlockHdr*)pAllocation;
15754   p--;
15755   assert( p->iForeGuard==(int)FOREGUARD );
15756   nReserve = ROUND8(p->iSize);
15757   pInt = (int*)pAllocation;
15758   pU8 = (u8*)pAllocation;
15759   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15760   /* This checks any of the "extra" bytes allocated due
15761   ** to rounding up to an 8 byte boundary to ensure 
15762   ** they haven't been overwritten.
15763   */
15764   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15765   return p;
15766 }
15767
15768 /*
15769 ** Return the number of bytes currently allocated at address p.
15770 */
15771 static int sqlite3MemSize(void *p){
15772   struct MemBlockHdr *pHdr;
15773   if( !p ){
15774     return 0;
15775   }
15776   pHdr = sqlite3MemsysGetHeader(p);
15777   return pHdr->iSize;
15778 }
15779
15780 /*
15781 ** Initialize the memory allocation subsystem.
15782 */
15783 static int sqlite3MemInit(void *NotUsed){
15784   UNUSED_PARAMETER(NotUsed);
15785   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15786   if( !sqlite3GlobalConfig.bMemstat ){
15787     /* If memory status is enabled, then the malloc.c wrapper will already
15788     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15789     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15790   }
15791   return SQLITE_OK;
15792 }
15793
15794 /*
15795 ** Deinitialize the memory allocation subsystem.
15796 */
15797 static void sqlite3MemShutdown(void *NotUsed){
15798   UNUSED_PARAMETER(NotUsed);
15799   mem.mutex = 0;
15800 }
15801
15802 /*
15803 ** Round up a request size to the next valid allocation size.
15804 */
15805 static int sqlite3MemRoundup(int n){
15806   return ROUND8(n);
15807 }
15808
15809 /*
15810 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15811 ** the content of a new memory allocation to unpredictable values and
15812 ** to clear the content of a freed allocation to unpredictable values.
15813 */
15814 static void randomFill(char *pBuf, int nByte){
15815   unsigned int x, y, r;
15816   x = SQLITE_PTR_TO_INT(pBuf);
15817   y = nByte | 1;
15818   while( nByte >= 4 ){
15819     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15820     y = y*1103515245 + 12345;
15821     r = x ^ y;
15822     *(int*)pBuf = r;
15823     pBuf += 4;
15824     nByte -= 4;
15825   }
15826   while( nByte-- > 0 ){
15827     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15828     y = y*1103515245 + 12345;
15829     r = x ^ y;
15830     *(pBuf++) = r & 0xff;
15831   }
15832 }
15833
15834 /*
15835 ** Allocate nByte bytes of memory.
15836 */
15837 static void *sqlite3MemMalloc(int nByte){
15838   struct MemBlockHdr *pHdr;
15839   void **pBt;
15840   char *z;
15841   int *pInt;
15842   void *p = 0;
15843   int totalSize;
15844   int nReserve;
15845   sqlite3_mutex_enter(mem.mutex);
15846   assert( mem.disallow==0 );
15847   nReserve = ROUND8(nByte);
15848   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15849                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15850   p = malloc(totalSize);
15851   if( p ){
15852     z = p;
15853     pBt = (void**)&z[mem.nTitle];
15854     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15855     pHdr->pNext = 0;
15856     pHdr->pPrev = mem.pLast;
15857     if( mem.pLast ){
15858       mem.pLast->pNext = pHdr;
15859     }else{
15860       mem.pFirst = pHdr;
15861     }
15862     mem.pLast = pHdr;
15863     pHdr->iForeGuard = FOREGUARD;
15864     pHdr->eType = MEMTYPE_HEAP;
15865     pHdr->nBacktraceSlots = mem.nBacktrace;
15866     pHdr->nTitle = mem.nTitle;
15867     if( mem.nBacktrace ){
15868       void *aAddr[40];
15869       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15870       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15871       assert(pBt[0]);
15872       if( mem.xBacktrace ){
15873         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15874       }
15875     }else{
15876       pHdr->nBacktrace = 0;
15877     }
15878     if( mem.nTitle ){
15879       memcpy(z, mem.zTitle, mem.nTitle);
15880     }
15881     pHdr->iSize = nByte;
15882     adjustStats(nByte, +1);
15883     pInt = (int*)&pHdr[1];
15884     pInt[nReserve/sizeof(int)] = REARGUARD;
15885     randomFill((char*)pInt, nByte);
15886     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15887     p = (void*)pInt;
15888   }
15889   sqlite3_mutex_leave(mem.mutex);
15890   return p; 
15891 }
15892
15893 /*
15894 ** Free memory.
15895 */
15896 static void sqlite3MemFree(void *pPrior){
15897   struct MemBlockHdr *pHdr;
15898   void **pBt;
15899   char *z;
15900   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
15901        || mem.mutex!=0 );
15902   pHdr = sqlite3MemsysGetHeader(pPrior);
15903   pBt = (void**)pHdr;
15904   pBt -= pHdr->nBacktraceSlots;
15905   sqlite3_mutex_enter(mem.mutex);
15906   if( pHdr->pPrev ){
15907     assert( pHdr->pPrev->pNext==pHdr );
15908     pHdr->pPrev->pNext = pHdr->pNext;
15909   }else{
15910     assert( mem.pFirst==pHdr );
15911     mem.pFirst = pHdr->pNext;
15912   }
15913   if( pHdr->pNext ){
15914     assert( pHdr->pNext->pPrev==pHdr );
15915     pHdr->pNext->pPrev = pHdr->pPrev;
15916   }else{
15917     assert( mem.pLast==pHdr );
15918     mem.pLast = pHdr->pPrev;
15919   }
15920   z = (char*)pBt;
15921   z -= pHdr->nTitle;
15922   adjustStats(pHdr->iSize, -1);
15923   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15924                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
15925   free(z);
15926   sqlite3_mutex_leave(mem.mutex);  
15927 }
15928
15929 /*
15930 ** Change the size of an existing memory allocation.
15931 **
15932 ** For this debugging implementation, we *always* make a copy of the
15933 ** allocation into a new place in memory.  In this way, if the 
15934 ** higher level code is using pointer to the old allocation, it is 
15935 ** much more likely to break and we are much more liking to find
15936 ** the error.
15937 */
15938 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15939   struct MemBlockHdr *pOldHdr;
15940   void *pNew;
15941   assert( mem.disallow==0 );
15942   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15943   pOldHdr = sqlite3MemsysGetHeader(pPrior);
15944   pNew = sqlite3MemMalloc(nByte);
15945   if( pNew ){
15946     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15947     if( nByte>pOldHdr->iSize ){
15948       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15949     }
15950     sqlite3MemFree(pPrior);
15951   }
15952   return pNew;
15953 }
15954
15955 /*
15956 ** Populate the low-level memory allocation function pointers in
15957 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15958 */
15959 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15960   static const sqlite3_mem_methods defaultMethods = {
15961      sqlite3MemMalloc,
15962      sqlite3MemFree,
15963      sqlite3MemRealloc,
15964      sqlite3MemSize,
15965      sqlite3MemRoundup,
15966      sqlite3MemInit,
15967      sqlite3MemShutdown,
15968      0
15969   };
15970   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15971 }
15972
15973 /*
15974 ** Set the "type" of an allocation.
15975 */
15976 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15977   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15978     struct MemBlockHdr *pHdr;
15979     pHdr = sqlite3MemsysGetHeader(p);
15980     assert( pHdr->iForeGuard==FOREGUARD );
15981     pHdr->eType = eType;
15982   }
15983 }
15984
15985 /*
15986 ** Return TRUE if the mask of type in eType matches the type of the
15987 ** allocation p.  Also return true if p==NULL.
15988 **
15989 ** This routine is designed for use within an assert() statement, to
15990 ** verify the type of an allocation.  For example:
15991 **
15992 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15993 */
15994 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15995   int rc = 1;
15996   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15997     struct MemBlockHdr *pHdr;
15998     pHdr = sqlite3MemsysGetHeader(p);
15999     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16000     if( (pHdr->eType&eType)==0 ){
16001       rc = 0;
16002     }
16003   }
16004   return rc;
16005 }
16006
16007 /*
16008 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16009 ** allocation p.  Also return true if p==NULL.
16010 **
16011 ** This routine is designed for use within an assert() statement, to
16012 ** verify the type of an allocation.  For example:
16013 **
16014 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16015 */
16016 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16017   int rc = 1;
16018   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16019     struct MemBlockHdr *pHdr;
16020     pHdr = sqlite3MemsysGetHeader(p);
16021     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16022     if( (pHdr->eType&eType)!=0 ){
16023       rc = 0;
16024     }
16025   }
16026   return rc;
16027 }
16028
16029 /*
16030 ** Set the number of backtrace levels kept for each allocation.
16031 ** A value of zero turns off backtracing.  The number is always rounded
16032 ** up to a multiple of 2.
16033 */
16034 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16035   if( depth<0 ){ depth = 0; }
16036   if( depth>20 ){ depth = 20; }
16037   depth = (depth+1)&0xfe;
16038   mem.nBacktrace = depth;
16039 }
16040
16041 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16042   mem.xBacktrace = xBacktrace;
16043 }
16044
16045 /*
16046 ** Set the title string for subsequent allocations.
16047 */
16048 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16049   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16050   sqlite3_mutex_enter(mem.mutex);
16051   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16052   memcpy(mem.zTitle, zTitle, n);
16053   mem.zTitle[n] = 0;
16054   mem.nTitle = ROUND8(n);
16055   sqlite3_mutex_leave(mem.mutex);
16056 }
16057
16058 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16059   struct MemBlockHdr *pHdr;
16060   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16061     void **pBt = (void**)pHdr;
16062     pBt -= pHdr->nBacktraceSlots;
16063     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16064   }
16065 }
16066
16067 /*
16068 ** Open the file indicated and write a log of all unfreed memory 
16069 ** allocations into that log.
16070 */
16071 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16072   FILE *out;
16073   struct MemBlockHdr *pHdr;
16074   void **pBt;
16075   int i;
16076   out = fopen(zFilename, "w");
16077   if( out==0 ){
16078     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16079                     zFilename);
16080     return;
16081   }
16082   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16083     char *z = (char*)pHdr;
16084     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16085     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16086             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16087     if( pHdr->nBacktrace ){
16088       fflush(out);
16089       pBt = (void**)pHdr;
16090       pBt -= pHdr->nBacktraceSlots;
16091       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16092       fprintf(out, "\n");
16093     }
16094   }
16095   fprintf(out, "COUNTS:\n");
16096   for(i=0; i<NCSIZE-1; i++){
16097     if( mem.nAlloc[i] ){
16098       fprintf(out, "   %5d: %10d %10d %10d\n", 
16099             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16100     }
16101   }
16102   if( mem.nAlloc[NCSIZE-1] ){
16103     fprintf(out, "   %5d: %10d %10d %10d\n",
16104              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16105              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16106   }
16107   fclose(out);
16108 }
16109
16110 /*
16111 ** Return the number of times sqlite3MemMalloc() has been called.
16112 */
16113 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16114   int i;
16115   int nTotal = 0;
16116   for(i=0; i<NCSIZE; i++){
16117     nTotal += mem.nAlloc[i];
16118   }
16119   return nTotal;
16120 }
16121
16122
16123 #endif /* SQLITE_MEMDEBUG */
16124
16125 /************** End of mem2.c ************************************************/
16126 /************** Begin file mem3.c ********************************************/
16127 /*
16128 ** 2007 October 14
16129 **
16130 ** The author disclaims copyright to this source code.  In place of
16131 ** a legal notice, here is a blessing:
16132 **
16133 **    May you do good and not evil.
16134 **    May you find forgiveness for yourself and forgive others.
16135 **    May you share freely, never taking more than you give.
16136 **
16137 *************************************************************************
16138 ** This file contains the C functions that implement a memory
16139 ** allocation subsystem for use by SQLite. 
16140 **
16141 ** This version of the memory allocation subsystem omits all
16142 ** use of malloc(). The SQLite user supplies a block of memory
16143 ** before calling sqlite3_initialize() from which allocations
16144 ** are made and returned by the xMalloc() and xRealloc() 
16145 ** implementations. Once sqlite3_initialize() has been called,
16146 ** the amount of memory available to SQLite is fixed and cannot
16147 ** be changed.
16148 **
16149 ** This version of the memory allocation subsystem is included
16150 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16151 */
16152
16153 /*
16154 ** This version of the memory allocator is only built into the library
16155 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16156 ** mean that the library will use a memory-pool by default, just that
16157 ** it is available. The mempool allocator is activated by calling
16158 ** sqlite3_config().
16159 */
16160 #ifdef SQLITE_ENABLE_MEMSYS3
16161
16162 /*
16163 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16164 */
16165 #define MX_SMALL 10
16166
16167
16168 /*
16169 ** Number of freelist hash slots
16170 */
16171 #define N_HASH  61
16172
16173 /*
16174 ** A memory allocation (also called a "chunk") consists of two or 
16175 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16176 ** a header that is not returned to the user.
16177 **
16178 ** A chunk is two or more blocks that is either checked out or
16179 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16180 ** size of the allocation in blocks if the allocation is free.
16181 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16182 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16183 ** is true if the previous chunk is checked out and false if the
16184 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16185 ** the previous chunk in blocks if the previous chunk is on the
16186 ** freelist. If the previous chunk is checked out, then
16187 ** u.hdr.prevSize can be part of the data for that chunk and should
16188 ** not be read or written.
16189 **
16190 ** We often identify a chunk by its index in mem3.aPool[].  When
16191 ** this is done, the chunk index refers to the second block of
16192 ** the chunk.  In this way, the first chunk has an index of 1.
16193 ** A chunk index of 0 means "no such chunk" and is the equivalent
16194 ** of a NULL pointer.
16195 **
16196 ** The second block of free chunks is of the form u.list.  The
16197 ** two fields form a double-linked list of chunks of related sizes.
16198 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16199 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16200 **
16201 ** The second block of a chunk is user data if the chunk is checked 
16202 ** out.  If a chunk is checked out, the user data may extend into
16203 ** the u.hdr.prevSize value of the following chunk.
16204 */
16205 typedef struct Mem3Block Mem3Block;
16206 struct Mem3Block {
16207   union {
16208     struct {
16209       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16210       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16211     } hdr;
16212     struct {
16213       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16214       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16215     } list;
16216   } u;
16217 };
16218
16219 /*
16220 ** All of the static variables used by this module are collected
16221 ** into a single structure named "mem3".  This is to keep the
16222 ** static variables organized and to reduce namespace pollution
16223 ** when this module is combined with other in the amalgamation.
16224 */
16225 static SQLITE_WSD struct Mem3Global {
16226   /*
16227   ** Memory available for allocation. nPool is the size of the array
16228   ** (in Mem3Blocks) pointed to by aPool less 2.
16229   */
16230   u32 nPool;
16231   Mem3Block *aPool;
16232
16233   /*
16234   ** True if we are evaluating an out-of-memory callback.
16235   */
16236   int alarmBusy;
16237   
16238   /*
16239   ** Mutex to control access to the memory allocation subsystem.
16240   */
16241   sqlite3_mutex *mutex;
16242   
16243   /*
16244   ** The minimum amount of free space that we have seen.
16245   */
16246   u32 mnMaster;
16247
16248   /*
16249   ** iMaster is the index of the master chunk.  Most new allocations
16250   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16251   ** of the current master.  iMaster is 0 if there is not master chunk.
16252   ** The master chunk is not in either the aiHash[] or aiSmall[].
16253   */
16254   u32 iMaster;
16255   u32 szMaster;
16256
16257   /*
16258   ** Array of lists of free blocks according to the block size 
16259   ** for smaller chunks, or a hash on the block size for larger
16260   ** chunks.
16261   */
16262   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16263   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16264 } mem3 = { 97535575 };
16265
16266 #define mem3 GLOBAL(struct Mem3Global, mem3)
16267
16268 /*
16269 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16270 ** on.  *pRoot is the list that i is a member of.
16271 */
16272 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16273   u32 next = mem3.aPool[i].u.list.next;
16274   u32 prev = mem3.aPool[i].u.list.prev;
16275   assert( sqlite3_mutex_held(mem3.mutex) );
16276   if( prev==0 ){
16277     *pRoot = next;
16278   }else{
16279     mem3.aPool[prev].u.list.next = next;
16280   }
16281   if( next ){
16282     mem3.aPool[next].u.list.prev = prev;
16283   }
16284   mem3.aPool[i].u.list.next = 0;
16285   mem3.aPool[i].u.list.prev = 0;
16286 }
16287
16288 /*
16289 ** Unlink the chunk at index i from 
16290 ** whatever list is currently a member of.
16291 */
16292 static void memsys3Unlink(u32 i){
16293   u32 size, hash;
16294   assert( sqlite3_mutex_held(mem3.mutex) );
16295   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16296   assert( i>=1 );
16297   size = mem3.aPool[i-1].u.hdr.size4x/4;
16298   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16299   assert( size>=2 );
16300   if( size <= MX_SMALL ){
16301     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16302   }else{
16303     hash = size % N_HASH;
16304     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16305   }
16306 }
16307
16308 /*
16309 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16310 ** at *pRoot.
16311 */
16312 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16313   assert( sqlite3_mutex_held(mem3.mutex) );
16314   mem3.aPool[i].u.list.next = *pRoot;
16315   mem3.aPool[i].u.list.prev = 0;
16316   if( *pRoot ){
16317     mem3.aPool[*pRoot].u.list.prev = i;
16318   }
16319   *pRoot = i;
16320 }
16321
16322 /*
16323 ** Link the chunk at index i into either the appropriate
16324 ** small chunk list, or into the large chunk hash table.
16325 */
16326 static void memsys3Link(u32 i){
16327   u32 size, hash;
16328   assert( sqlite3_mutex_held(mem3.mutex) );
16329   assert( i>=1 );
16330   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16331   size = mem3.aPool[i-1].u.hdr.size4x/4;
16332   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16333   assert( size>=2 );
16334   if( size <= MX_SMALL ){
16335     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16336   }else{
16337     hash = size % N_HASH;
16338     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16339   }
16340 }
16341
16342 /*
16343 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16344 ** will already be held (obtained by code in malloc.c) if
16345 ** sqlite3GlobalConfig.bMemStat is true.
16346 */
16347 static void memsys3Enter(void){
16348   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16349     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16350   }
16351   sqlite3_mutex_enter(mem3.mutex);
16352 }
16353 static void memsys3Leave(void){
16354   sqlite3_mutex_leave(mem3.mutex);
16355 }
16356
16357 /*
16358 ** Called when we are unable to satisfy an allocation of nBytes.
16359 */
16360 static void memsys3OutOfMemory(int nByte){
16361   if( !mem3.alarmBusy ){
16362     mem3.alarmBusy = 1;
16363     assert( sqlite3_mutex_held(mem3.mutex) );
16364     sqlite3_mutex_leave(mem3.mutex);
16365     sqlite3_release_memory(nByte);
16366     sqlite3_mutex_enter(mem3.mutex);
16367     mem3.alarmBusy = 0;
16368   }
16369 }
16370
16371
16372 /*
16373 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16374 ** size parameters for check-out and return a pointer to the 
16375 ** user portion of the chunk.
16376 */
16377 static void *memsys3Checkout(u32 i, u32 nBlock){
16378   u32 x;
16379   assert( sqlite3_mutex_held(mem3.mutex) );
16380   assert( i>=1 );
16381   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16382   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16383   x = mem3.aPool[i-1].u.hdr.size4x;
16384   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16385   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16386   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16387   return &mem3.aPool[i];
16388 }
16389
16390 /*
16391 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16392 ** Return a pointer to the new allocation.  Or, if the master chunk
16393 ** is not large enough, return 0.
16394 */
16395 static void *memsys3FromMaster(u32 nBlock){
16396   assert( sqlite3_mutex_held(mem3.mutex) );
16397   assert( mem3.szMaster>=nBlock );
16398   if( nBlock>=mem3.szMaster-1 ){
16399     /* Use the entire master */
16400     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16401     mem3.iMaster = 0;
16402     mem3.szMaster = 0;
16403     mem3.mnMaster = 0;
16404     return p;
16405   }else{
16406     /* Split the master block.  Return the tail. */
16407     u32 newi, x;
16408     newi = mem3.iMaster + mem3.szMaster - nBlock;
16409     assert( newi > mem3.iMaster+1 );
16410     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16411     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16412     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16413     mem3.szMaster -= nBlock;
16414     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16415     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16416     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16417     if( mem3.szMaster < mem3.mnMaster ){
16418       mem3.mnMaster = mem3.szMaster;
16419     }
16420     return (void*)&mem3.aPool[newi];
16421   }
16422 }
16423
16424 /*
16425 ** *pRoot is the head of a list of free chunks of the same size
16426 ** or same size hash.  In other words, *pRoot is an entry in either
16427 ** mem3.aiSmall[] or mem3.aiHash[].  
16428 **
16429 ** This routine examines all entries on the given list and tries
16430 ** to coalesce each entries with adjacent free chunks.  
16431 **
16432 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16433 ** the current mem3.iMaster with the new larger chunk.  In order for
16434 ** this mem3.iMaster replacement to work, the master chunk must be
16435 ** linked into the hash tables.  That is not the normal state of
16436 ** affairs, of course.  The calling routine must link the master
16437 ** chunk before invoking this routine, then must unlink the (possibly
16438 ** changed) master chunk once this routine has finished.
16439 */
16440 static void memsys3Merge(u32 *pRoot){
16441   u32 iNext, prev, size, i, x;
16442
16443   assert( sqlite3_mutex_held(mem3.mutex) );
16444   for(i=*pRoot; i>0; i=iNext){
16445     iNext = mem3.aPool[i].u.list.next;
16446     size = mem3.aPool[i-1].u.hdr.size4x;
16447     assert( (size&1)==0 );
16448     if( (size&2)==0 ){
16449       memsys3UnlinkFromList(i, pRoot);
16450       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16451       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16452       if( prev==iNext ){
16453         iNext = mem3.aPool[prev].u.list.next;
16454       }
16455       memsys3Unlink(prev);
16456       size = i + size/4 - prev;
16457       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16458       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16459       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16460       memsys3Link(prev);
16461       i = prev;
16462     }else{
16463       size /= 4;
16464     }
16465     if( size>mem3.szMaster ){
16466       mem3.iMaster = i;
16467       mem3.szMaster = size;
16468     }
16469   }
16470 }
16471
16472 /*
16473 ** Return a block of memory of at least nBytes in size.
16474 ** Return NULL if unable.
16475 **
16476 ** This function assumes that the necessary mutexes, if any, are
16477 ** already held by the caller. Hence "Unsafe".
16478 */
16479 static void *memsys3MallocUnsafe(int nByte){
16480   u32 i;
16481   u32 nBlock;
16482   u32 toFree;
16483
16484   assert( sqlite3_mutex_held(mem3.mutex) );
16485   assert( sizeof(Mem3Block)==8 );
16486   if( nByte<=12 ){
16487     nBlock = 2;
16488   }else{
16489     nBlock = (nByte + 11)/8;
16490   }
16491   assert( nBlock>=2 );
16492
16493   /* STEP 1:
16494   ** Look for an entry of the correct size in either the small
16495   ** chunk table or in the large chunk hash table.  This is
16496   ** successful most of the time (about 9 times out of 10).
16497   */
16498   if( nBlock <= MX_SMALL ){
16499     i = mem3.aiSmall[nBlock-2];
16500     if( i>0 ){
16501       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16502       return memsys3Checkout(i, nBlock);
16503     }
16504   }else{
16505     int hash = nBlock % N_HASH;
16506     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16507       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16508         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16509         return memsys3Checkout(i, nBlock);
16510       }
16511     }
16512   }
16513
16514   /* STEP 2:
16515   ** Try to satisfy the allocation by carving a piece off of the end
16516   ** of the master chunk.  This step usually works if step 1 fails.
16517   */
16518   if( mem3.szMaster>=nBlock ){
16519     return memsys3FromMaster(nBlock);
16520   }
16521
16522
16523   /* STEP 3:  
16524   ** Loop through the entire memory pool.  Coalesce adjacent free
16525   ** chunks.  Recompute the master chunk as the largest free chunk.
16526   ** Then try again to satisfy the allocation by carving a piece off
16527   ** of the end of the master chunk.  This step happens very
16528   ** rarely (we hope!)
16529   */
16530   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16531     memsys3OutOfMemory(toFree);
16532     if( mem3.iMaster ){
16533       memsys3Link(mem3.iMaster);
16534       mem3.iMaster = 0;
16535       mem3.szMaster = 0;
16536     }
16537     for(i=0; i<N_HASH; i++){
16538       memsys3Merge(&mem3.aiHash[i]);
16539     }
16540     for(i=0; i<MX_SMALL-1; i++){
16541       memsys3Merge(&mem3.aiSmall[i]);
16542     }
16543     if( mem3.szMaster ){
16544       memsys3Unlink(mem3.iMaster);
16545       if( mem3.szMaster>=nBlock ){
16546         return memsys3FromMaster(nBlock);
16547       }
16548     }
16549   }
16550
16551   /* If none of the above worked, then we fail. */
16552   return 0;
16553 }
16554
16555 /*
16556 ** Free an outstanding memory allocation.
16557 **
16558 ** This function assumes that the necessary mutexes, if any, are
16559 ** already held by the caller. Hence "Unsafe".
16560 */
16561 static void memsys3FreeUnsafe(void *pOld){
16562   Mem3Block *p = (Mem3Block*)pOld;
16563   int i;
16564   u32 size, x;
16565   assert( sqlite3_mutex_held(mem3.mutex) );
16566   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16567   i = p - mem3.aPool;
16568   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16569   size = mem3.aPool[i-1].u.hdr.size4x/4;
16570   assert( i+size<=mem3.nPool+1 );
16571   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16572   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16573   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16574   memsys3Link(i);
16575
16576   /* Try to expand the master using the newly freed chunk */
16577   if( mem3.iMaster ){
16578     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16579       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16580       mem3.iMaster -= size;
16581       mem3.szMaster += size;
16582       memsys3Unlink(mem3.iMaster);
16583       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16584       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16585       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16586     }
16587     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16588     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16589       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16590       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16591       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16592       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16593     }
16594   }
16595 }
16596
16597 /*
16598 ** Return the size of an outstanding allocation, in bytes.  The
16599 ** size returned omits the 8-byte header overhead.  This only
16600 ** works for chunks that are currently checked out.
16601 */
16602 static int memsys3Size(void *p){
16603   Mem3Block *pBlock;
16604   if( p==0 ) return 0;
16605   pBlock = (Mem3Block*)p;
16606   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16607   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16608 }
16609
16610 /*
16611 ** Round up a request size to the next valid allocation size.
16612 */
16613 static int memsys3Roundup(int n){
16614   if( n<=12 ){
16615     return 12;
16616   }else{
16617     return ((n+11)&~7) - 4;
16618   }
16619 }
16620
16621 /*
16622 ** Allocate nBytes of memory.
16623 */
16624 static void *memsys3Malloc(int nBytes){
16625   sqlite3_int64 *p;
16626   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16627   memsys3Enter();
16628   p = memsys3MallocUnsafe(nBytes);
16629   memsys3Leave();
16630   return (void*)p; 
16631 }
16632
16633 /*
16634 ** Free memory.
16635 */
16636 static void memsys3Free(void *pPrior){
16637   assert( pPrior );
16638   memsys3Enter();
16639   memsys3FreeUnsafe(pPrior);
16640   memsys3Leave();
16641 }
16642
16643 /*
16644 ** Change the size of an existing memory allocation
16645 */
16646 static void *memsys3Realloc(void *pPrior, int nBytes){
16647   int nOld;
16648   void *p;
16649   if( pPrior==0 ){
16650     return sqlite3_malloc(nBytes);
16651   }
16652   if( nBytes<=0 ){
16653     sqlite3_free(pPrior);
16654     return 0;
16655   }
16656   nOld = memsys3Size(pPrior);
16657   if( nBytes<=nOld && nBytes>=nOld-128 ){
16658     return pPrior;
16659   }
16660   memsys3Enter();
16661   p = memsys3MallocUnsafe(nBytes);
16662   if( p ){
16663     if( nOld<nBytes ){
16664       memcpy(p, pPrior, nOld);
16665     }else{
16666       memcpy(p, pPrior, nBytes);
16667     }
16668     memsys3FreeUnsafe(pPrior);
16669   }
16670   memsys3Leave();
16671   return p;
16672 }
16673
16674 /*
16675 ** Initialize this module.
16676 */
16677 static int memsys3Init(void *NotUsed){
16678   UNUSED_PARAMETER(NotUsed);
16679   if( !sqlite3GlobalConfig.pHeap ){
16680     return SQLITE_ERROR;
16681   }
16682
16683   /* Store a pointer to the memory block in global structure mem3. */
16684   assert( sizeof(Mem3Block)==8 );
16685   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16686   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16687
16688   /* Initialize the master block. */
16689   mem3.szMaster = mem3.nPool;
16690   mem3.mnMaster = mem3.szMaster;
16691   mem3.iMaster = 1;
16692   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16693   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16694   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16695
16696   return SQLITE_OK;
16697 }
16698
16699 /*
16700 ** Deinitialize this module.
16701 */
16702 static void memsys3Shutdown(void *NotUsed){
16703   UNUSED_PARAMETER(NotUsed);
16704   mem3.mutex = 0;
16705   return;
16706 }
16707
16708
16709
16710 /*
16711 ** Open the file indicated and write a log of all unfreed memory 
16712 ** allocations into that log.
16713 */
16714 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16715 #ifdef SQLITE_DEBUG
16716   FILE *out;
16717   u32 i, j;
16718   u32 size;
16719   if( zFilename==0 || zFilename[0]==0 ){
16720     out = stdout;
16721   }else{
16722     out = fopen(zFilename, "w");
16723     if( out==0 ){
16724       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16725                       zFilename);
16726       return;
16727     }
16728   }
16729   memsys3Enter();
16730   fprintf(out, "CHUNKS:\n");
16731   for(i=1; i<=mem3.nPool; i+=size/4){
16732     size = mem3.aPool[i-1].u.hdr.size4x;
16733     if( size/4<=1 ){
16734       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16735       assert( 0 );
16736       break;
16737     }
16738     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16739       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16740       assert( 0 );
16741       break;
16742     }
16743     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16744       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16745       assert( 0 );
16746       break;
16747     }
16748     if( size&1 ){
16749       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16750     }else{
16751       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16752                   i==mem3.iMaster ? " **master**" : "");
16753     }
16754   }
16755   for(i=0; i<MX_SMALL-1; i++){
16756     if( mem3.aiSmall[i]==0 ) continue;
16757     fprintf(out, "small(%2d):", i);
16758     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16759       fprintf(out, " %p(%d)", &mem3.aPool[j],
16760               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16761     }
16762     fprintf(out, "\n"); 
16763   }
16764   for(i=0; i<N_HASH; i++){
16765     if( mem3.aiHash[i]==0 ) continue;
16766     fprintf(out, "hash(%2d):", i);
16767     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16768       fprintf(out, " %p(%d)", &mem3.aPool[j],
16769               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16770     }
16771     fprintf(out, "\n"); 
16772   }
16773   fprintf(out, "master=%d\n", mem3.iMaster);
16774   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16775   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16776   sqlite3_mutex_leave(mem3.mutex);
16777   if( out==stdout ){
16778     fflush(stdout);
16779   }else{
16780     fclose(out);
16781   }
16782 #else
16783   UNUSED_PARAMETER(zFilename);
16784 #endif
16785 }
16786
16787 /*
16788 ** This routine is the only routine in this file with external 
16789 ** linkage.
16790 **
16791 ** Populate the low-level memory allocation function pointers in
16792 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16793 ** arguments specify the block of memory to manage.
16794 **
16795 ** This routine is only called by sqlite3_config(), and therefore
16796 ** is not required to be threadsafe (it is not).
16797 */
16798 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16799   static const sqlite3_mem_methods mempoolMethods = {
16800      memsys3Malloc,
16801      memsys3Free,
16802      memsys3Realloc,
16803      memsys3Size,
16804      memsys3Roundup,
16805      memsys3Init,
16806      memsys3Shutdown,
16807      0
16808   };
16809   return &mempoolMethods;
16810 }
16811
16812 #endif /* SQLITE_ENABLE_MEMSYS3 */
16813
16814 /************** End of mem3.c ************************************************/
16815 /************** Begin file mem5.c ********************************************/
16816 /*
16817 ** 2007 October 14
16818 **
16819 ** The author disclaims copyright to this source code.  In place of
16820 ** a legal notice, here is a blessing:
16821 **
16822 **    May you do good and not evil.
16823 **    May you find forgiveness for yourself and forgive others.
16824 **    May you share freely, never taking more than you give.
16825 **
16826 *************************************************************************
16827 ** This file contains the C functions that implement a memory
16828 ** allocation subsystem for use by SQLite. 
16829 **
16830 ** This version of the memory allocation subsystem omits all
16831 ** use of malloc(). The application gives SQLite a block of memory
16832 ** before calling sqlite3_initialize() from which allocations
16833 ** are made and returned by the xMalloc() and xRealloc() 
16834 ** implementations. Once sqlite3_initialize() has been called,
16835 ** the amount of memory available to SQLite is fixed and cannot
16836 ** be changed.
16837 **
16838 ** This version of the memory allocation subsystem is included
16839 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16840 **
16841 ** This memory allocator uses the following algorithm:
16842 **
16843 **   1.  All memory allocations sizes are rounded up to a power of 2.
16844 **
16845 **   2.  If two adjacent free blocks are the halves of a larger block,
16846 **       then the two blocks are coalesed into the single larger block.
16847 **
16848 **   3.  New memory is allocated from the first available free block.
16849 **
16850 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16851 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16852 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16853 ** 
16854 ** Let n be the size of the largest allocation divided by the minimum
16855 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
16856 ** be the maximum amount of memory ever outstanding at one time.  Let
16857 ** N be the total amount of memory available for allocation.  Robson
16858 ** proved that this memory allocator will never breakdown due to 
16859 ** fragmentation as long as the following constraint holds:
16860 **
16861 **      N >=  M*(1 + log2(n)/2) - n + 1
16862 **
16863 ** The sqlite3_status() logic tracks the maximum values of n and M so
16864 ** that an application can, at any time, verify this constraint.
16865 */
16866
16867 /*
16868 ** This version of the memory allocator is used only when 
16869 ** SQLITE_ENABLE_MEMSYS5 is defined.
16870 */
16871 #ifdef SQLITE_ENABLE_MEMSYS5
16872
16873 /*
16874 ** A minimum allocation is an instance of the following structure.
16875 ** Larger allocations are an array of these structures where the
16876 ** size of the array is a power of 2.
16877 **
16878 ** The size of this object must be a power of two.  That fact is
16879 ** verified in memsys5Init().
16880 */
16881 typedef struct Mem5Link Mem5Link;
16882 struct Mem5Link {
16883   int next;       /* Index of next free chunk */
16884   int prev;       /* Index of previous free chunk */
16885 };
16886
16887 /*
16888 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16889 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
16890 ** it is not actually possible to reach this limit.
16891 */
16892 #define LOGMAX 30
16893
16894 /*
16895 ** Masks used for mem5.aCtrl[] elements.
16896 */
16897 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16898 #define CTRL_FREE     0x20    /* True if not checked out */
16899
16900 /*
16901 ** All of the static variables used by this module are collected
16902 ** into a single structure named "mem5".  This is to keep the
16903 ** static variables organized and to reduce namespace pollution
16904 ** when this module is combined with other in the amalgamation.
16905 */
16906 static SQLITE_WSD struct Mem5Global {
16907   /*
16908   ** Memory available for allocation
16909   */
16910   int szAtom;      /* Smallest possible allocation in bytes */
16911   int nBlock;      /* Number of szAtom sized blocks in zPool */
16912   u8 *zPool;       /* Memory available to be allocated */
16913   
16914   /*
16915   ** Mutex to control access to the memory allocation subsystem.
16916   */
16917   sqlite3_mutex *mutex;
16918
16919   /*
16920   ** Performance statistics
16921   */
16922   u64 nAlloc;         /* Total number of calls to malloc */
16923   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16924   u64 totalExcess;    /* Total internal fragmentation */
16925   u32 currentOut;     /* Current checkout, including internal fragmentation */
16926   u32 currentCount;   /* Current number of distinct checkouts */
16927   u32 maxOut;         /* Maximum instantaneous currentOut */
16928   u32 maxCount;       /* Maximum instantaneous currentCount */
16929   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16930   
16931   /*
16932   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16933   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16934   ** and so forth.
16935   */
16936   int aiFreelist[LOGMAX+1];
16937
16938   /*
16939   ** Space for tracking which blocks are checked out and the size
16940   ** of each block.  One byte per block.
16941   */
16942   u8 *aCtrl;
16943
16944 } mem5;
16945
16946 /*
16947 ** Access the static variable through a macro for SQLITE_OMIT_WSD
16948 */
16949 #define mem5 GLOBAL(struct Mem5Global, mem5)
16950
16951 /*
16952 ** Assuming mem5.zPool is divided up into an array of Mem5Link
16953 ** structures, return a pointer to the idx-th such lik.
16954 */
16955 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16956
16957 /*
16958 ** Unlink the chunk at mem5.aPool[i] from list it is currently
16959 ** on.  It should be found on mem5.aiFreelist[iLogsize].
16960 */
16961 static void memsys5Unlink(int i, int iLogsize){
16962   int next, prev;
16963   assert( i>=0 && i<mem5.nBlock );
16964   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16965   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16966
16967   next = MEM5LINK(i)->next;
16968   prev = MEM5LINK(i)->prev;
16969   if( prev<0 ){
16970     mem5.aiFreelist[iLogsize] = next;
16971   }else{
16972     MEM5LINK(prev)->next = next;
16973   }
16974   if( next>=0 ){
16975     MEM5LINK(next)->prev = prev;
16976   }
16977 }
16978
16979 /*
16980 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16981 ** free list.
16982 */
16983 static void memsys5Link(int i, int iLogsize){
16984   int x;
16985   assert( sqlite3_mutex_held(mem5.mutex) );
16986   assert( i>=0 && i<mem5.nBlock );
16987   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16988   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16989
16990   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16991   MEM5LINK(i)->prev = -1;
16992   if( x>=0 ){
16993     assert( x<mem5.nBlock );
16994     MEM5LINK(x)->prev = i;
16995   }
16996   mem5.aiFreelist[iLogsize] = i;
16997 }
16998
16999 /*
17000 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17001 ** will already be held (obtained by code in malloc.c) if
17002 ** sqlite3GlobalConfig.bMemStat is true.
17003 */
17004 static void memsys5Enter(void){
17005   sqlite3_mutex_enter(mem5.mutex);
17006 }
17007 static void memsys5Leave(void){
17008   sqlite3_mutex_leave(mem5.mutex);
17009 }
17010
17011 /*
17012 ** Return the size of an outstanding allocation, in bytes.  The
17013 ** size returned omits the 8-byte header overhead.  This only
17014 ** works for chunks that are currently checked out.
17015 */
17016 static int memsys5Size(void *p){
17017   int iSize = 0;
17018   if( p ){
17019     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17020     assert( i>=0 && i<mem5.nBlock );
17021     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17022   }
17023   return iSize;
17024 }
17025
17026 /*
17027 ** Find the first entry on the freelist iLogsize.  Unlink that
17028 ** entry and return its index. 
17029 */
17030 static int memsys5UnlinkFirst(int iLogsize){
17031   int i;
17032   int iFirst;
17033
17034   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17035   i = iFirst = mem5.aiFreelist[iLogsize];
17036   assert( iFirst>=0 );
17037   while( i>0 ){
17038     if( i<iFirst ) iFirst = i;
17039     i = MEM5LINK(i)->next;
17040   }
17041   memsys5Unlink(iFirst, iLogsize);
17042   return iFirst;
17043 }
17044
17045 /*
17046 ** Return a block of memory of at least nBytes in size.
17047 ** Return NULL if unable.  Return NULL if nBytes==0.
17048 **
17049 ** The caller guarantees that nByte positive.
17050 **
17051 ** The caller has obtained a mutex prior to invoking this
17052 ** routine so there is never any chance that two or more
17053 ** threads can be in this routine at the same time.
17054 */
17055 static void *memsys5MallocUnsafe(int nByte){
17056   int i;           /* Index of a mem5.aPool[] slot */
17057   int iBin;        /* Index into mem5.aiFreelist[] */
17058   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17059   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17060
17061   /* nByte must be a positive */
17062   assert( nByte>0 );
17063
17064   /* Keep track of the maximum allocation request.  Even unfulfilled
17065   ** requests are counted */
17066   if( (u32)nByte>mem5.maxRequest ){
17067     mem5.maxRequest = nByte;
17068   }
17069
17070   /* Abort if the requested allocation size is larger than the largest
17071   ** power of two that we can represent using 32-bit signed integers.
17072   */
17073   if( nByte > 0x40000000 ){
17074     return 0;
17075   }
17076
17077   /* Round nByte up to the next valid power of two */
17078   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17079
17080   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17081   ** block.  If not, then split a block of the next larger power of
17082   ** two in order to create a new free block of size iLogsize.
17083   */
17084   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17085   if( iBin>LOGMAX ){
17086     testcase( sqlite3GlobalConfig.xLog!=0 );
17087     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17088     return 0;
17089   }
17090   i = memsys5UnlinkFirst(iBin);
17091   while( iBin>iLogsize ){
17092     int newSize;
17093
17094     iBin--;
17095     newSize = 1 << iBin;
17096     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17097     memsys5Link(i+newSize, iBin);
17098   }
17099   mem5.aCtrl[i] = iLogsize;
17100
17101   /* Update allocator performance statistics. */
17102   mem5.nAlloc++;
17103   mem5.totalAlloc += iFullSz;
17104   mem5.totalExcess += iFullSz - nByte;
17105   mem5.currentCount++;
17106   mem5.currentOut += iFullSz;
17107   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17108   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17109
17110   /* Return a pointer to the allocated memory. */
17111   return (void*)&mem5.zPool[i*mem5.szAtom];
17112 }
17113
17114 /*
17115 ** Free an outstanding memory allocation.
17116 */
17117 static void memsys5FreeUnsafe(void *pOld){
17118   u32 size, iLogsize;
17119   int iBlock;
17120
17121   /* Set iBlock to the index of the block pointed to by pOld in 
17122   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17123   */
17124   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17125
17126   /* Check that the pointer pOld points to a valid, non-free block. */
17127   assert( iBlock>=0 && iBlock<mem5.nBlock );
17128   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17129   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17130
17131   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17132   size = 1<<iLogsize;
17133   assert( iBlock+size-1<(u32)mem5.nBlock );
17134
17135   mem5.aCtrl[iBlock] |= CTRL_FREE;
17136   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17137   assert( mem5.currentCount>0 );
17138   assert( mem5.currentOut>=(size*mem5.szAtom) );
17139   mem5.currentCount--;
17140   mem5.currentOut -= size*mem5.szAtom;
17141   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17142   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17143
17144   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17145   while( ALWAYS(iLogsize<LOGMAX) ){
17146     int iBuddy;
17147     if( (iBlock>>iLogsize) & 1 ){
17148       iBuddy = iBlock - size;
17149     }else{
17150       iBuddy = iBlock + size;
17151     }
17152     assert( iBuddy>=0 );
17153     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17154     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17155     memsys5Unlink(iBuddy, iLogsize);
17156     iLogsize++;
17157     if( iBuddy<iBlock ){
17158       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17159       mem5.aCtrl[iBlock] = 0;
17160       iBlock = iBuddy;
17161     }else{
17162       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17163       mem5.aCtrl[iBuddy] = 0;
17164     }
17165     size *= 2;
17166   }
17167   memsys5Link(iBlock, iLogsize);
17168 }
17169
17170 /*
17171 ** Allocate nBytes of memory
17172 */
17173 static void *memsys5Malloc(int nBytes){
17174   sqlite3_int64 *p = 0;
17175   if( nBytes>0 ){
17176     memsys5Enter();
17177     p = memsys5MallocUnsafe(nBytes);
17178     memsys5Leave();
17179   }
17180   return (void*)p; 
17181 }
17182
17183 /*
17184 ** Free memory.
17185 **
17186 ** The outer layer memory allocator prevents this routine from
17187 ** being called with pPrior==0.
17188 */
17189 static void memsys5Free(void *pPrior){
17190   assert( pPrior!=0 );
17191   memsys5Enter();
17192   memsys5FreeUnsafe(pPrior);
17193   memsys5Leave();  
17194 }
17195
17196 /*
17197 ** Change the size of an existing memory allocation.
17198 **
17199 ** The outer layer memory allocator prevents this routine from
17200 ** being called with pPrior==0.  
17201 **
17202 ** nBytes is always a value obtained from a prior call to
17203 ** memsys5Round().  Hence nBytes is always a non-negative power
17204 ** of two.  If nBytes==0 that means that an oversize allocation
17205 ** (an allocation larger than 0x40000000) was requested and this
17206 ** routine should return 0 without freeing pPrior.
17207 */
17208 static void *memsys5Realloc(void *pPrior, int nBytes){
17209   int nOld;
17210   void *p;
17211   assert( pPrior!=0 );
17212   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17213   assert( nBytes>=0 );
17214   if( nBytes==0 ){
17215     return 0;
17216   }
17217   nOld = memsys5Size(pPrior);
17218   if( nBytes<=nOld ){
17219     return pPrior;
17220   }
17221   memsys5Enter();
17222   p = memsys5MallocUnsafe(nBytes);
17223   if( p ){
17224     memcpy(p, pPrior, nOld);
17225     memsys5FreeUnsafe(pPrior);
17226   }
17227   memsys5Leave();
17228   return p;
17229 }
17230
17231 /*
17232 ** Round up a request size to the next valid allocation size.  If
17233 ** the allocation is too large to be handled by this allocation system,
17234 ** return 0.
17235 **
17236 ** All allocations must be a power of two and must be expressed by a
17237 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17238 ** or 1073741824 bytes.
17239 */
17240 static int memsys5Roundup(int n){
17241   int iFullSz;
17242   if( n > 0x40000000 ) return 0;
17243   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17244   return iFullSz;
17245 }
17246
17247 /*
17248 ** Return the ceiling of the logarithm base 2 of iValue.
17249 **
17250 ** Examples:   memsys5Log(1) -> 0
17251 **             memsys5Log(2) -> 1
17252 **             memsys5Log(4) -> 2
17253 **             memsys5Log(5) -> 3
17254 **             memsys5Log(8) -> 3
17255 **             memsys5Log(9) -> 4
17256 */
17257 static int memsys5Log(int iValue){
17258   int iLog;
17259   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17260   return iLog;
17261 }
17262
17263 /*
17264 ** Initialize the memory allocator.
17265 **
17266 ** This routine is not threadsafe.  The caller must be holding a mutex
17267 ** to prevent multiple threads from entering at the same time.
17268 */
17269 static int memsys5Init(void *NotUsed){
17270   int ii;            /* Loop counter */
17271   int nByte;         /* Number of bytes of memory available to this allocator */
17272   u8 *zByte;         /* Memory usable by this allocator */
17273   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17274   int iOffset;       /* An offset into mem5.aCtrl[] */
17275
17276   UNUSED_PARAMETER(NotUsed);
17277
17278   /* For the purposes of this routine, disable the mutex */
17279   mem5.mutex = 0;
17280
17281   /* The size of a Mem5Link object must be a power of two.  Verify that
17282   ** this is case.
17283   */
17284   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17285
17286   nByte = sqlite3GlobalConfig.nHeap;
17287   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17288   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17289
17290   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17291   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17292   mem5.szAtom = (1<<nMinLog);
17293   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17294     mem5.szAtom = mem5.szAtom << 1;
17295   }
17296
17297   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17298   mem5.zPool = zByte;
17299   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17300
17301   for(ii=0; ii<=LOGMAX; ii++){
17302     mem5.aiFreelist[ii] = -1;
17303   }
17304
17305   iOffset = 0;
17306   for(ii=LOGMAX; ii>=0; ii--){
17307     int nAlloc = (1<<ii);
17308     if( (iOffset+nAlloc)<=mem5.nBlock ){
17309       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17310       memsys5Link(iOffset, ii);
17311       iOffset += nAlloc;
17312     }
17313     assert((iOffset+nAlloc)>mem5.nBlock);
17314   }
17315
17316   /* If a mutex is required for normal operation, allocate one */
17317   if( sqlite3GlobalConfig.bMemstat==0 ){
17318     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17319   }
17320
17321   return SQLITE_OK;
17322 }
17323
17324 /*
17325 ** Deinitialize this module.
17326 */
17327 static void memsys5Shutdown(void *NotUsed){
17328   UNUSED_PARAMETER(NotUsed);
17329   mem5.mutex = 0;
17330   return;
17331 }
17332
17333 #ifdef SQLITE_TEST
17334 /*
17335 ** Open the file indicated and write a log of all unfreed memory 
17336 ** allocations into that log.
17337 */
17338 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17339   FILE *out;
17340   int i, j, n;
17341   int nMinLog;
17342
17343   if( zFilename==0 || zFilename[0]==0 ){
17344     out = stdout;
17345   }else{
17346     out = fopen(zFilename, "w");
17347     if( out==0 ){
17348       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17349                       zFilename);
17350       return;
17351     }
17352   }
17353   memsys5Enter();
17354   nMinLog = memsys5Log(mem5.szAtom);
17355   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17356     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17357     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17358   }
17359   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17360   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17361   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17362   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17363   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17364   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17365   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17366   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17367   memsys5Leave();
17368   if( out==stdout ){
17369     fflush(stdout);
17370   }else{
17371     fclose(out);
17372   }
17373 }
17374 #endif
17375
17376 /*
17377 ** This routine is the only routine in this file with external 
17378 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17379 ** struct populated with the memsys5 methods.
17380 */
17381 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17382   static const sqlite3_mem_methods memsys5Methods = {
17383      memsys5Malloc,
17384      memsys5Free,
17385      memsys5Realloc,
17386      memsys5Size,
17387      memsys5Roundup,
17388      memsys5Init,
17389      memsys5Shutdown,
17390      0
17391   };
17392   return &memsys5Methods;
17393 }
17394
17395 #endif /* SQLITE_ENABLE_MEMSYS5 */
17396
17397 /************** End of mem5.c ************************************************/
17398 /************** Begin file mutex.c *******************************************/
17399 /*
17400 ** 2007 August 14
17401 **
17402 ** The author disclaims copyright to this source code.  In place of
17403 ** a legal notice, here is a blessing:
17404 **
17405 **    May you do good and not evil.
17406 **    May you find forgiveness for yourself and forgive others.
17407 **    May you share freely, never taking more than you give.
17408 **
17409 *************************************************************************
17410 ** This file contains the C functions that implement mutexes.
17411 **
17412 ** This file contains code that is common across all mutex implementations.
17413 */
17414
17415 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17416 /*
17417 ** For debugging purposes, record when the mutex subsystem is initialized
17418 ** and uninitialized so that we can assert() if there is an attempt to
17419 ** allocate a mutex while the system is uninitialized.
17420 */
17421 static SQLITE_WSD int mutexIsInit = 0;
17422 #endif /* SQLITE_DEBUG */
17423
17424
17425 #ifndef SQLITE_MUTEX_OMIT
17426 /*
17427 ** Initialize the mutex system.
17428 */
17429 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17430   int rc = SQLITE_OK;
17431   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17432     /* If the xMutexAlloc method has not been set, then the user did not
17433     ** install a mutex implementation via sqlite3_config() prior to 
17434     ** sqlite3_initialize() being called. This block copies pointers to
17435     ** the default implementation into the sqlite3GlobalConfig structure.
17436     */
17437     sqlite3_mutex_methods const *pFrom;
17438     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17439
17440     if( sqlite3GlobalConfig.bCoreMutex ){
17441       pFrom = sqlite3DefaultMutex();
17442     }else{
17443       pFrom = sqlite3NoopMutex();
17444     }
17445     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17446     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17447            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17448     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17449   }
17450   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17451
17452 #ifdef SQLITE_DEBUG
17453   GLOBAL(int, mutexIsInit) = 1;
17454 #endif
17455
17456   return rc;
17457 }
17458
17459 /*
17460 ** Shutdown the mutex system. This call frees resources allocated by
17461 ** sqlite3MutexInit().
17462 */
17463 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17464   int rc = SQLITE_OK;
17465   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17466     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17467   }
17468
17469 #ifdef SQLITE_DEBUG
17470   GLOBAL(int, mutexIsInit) = 0;
17471 #endif
17472
17473   return rc;
17474 }
17475
17476 /*
17477 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17478 */
17479 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17480 #ifndef SQLITE_OMIT_AUTOINIT
17481   if( sqlite3_initialize() ) return 0;
17482 #endif
17483   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17484 }
17485
17486 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17487   if( !sqlite3GlobalConfig.bCoreMutex ){
17488     return 0;
17489   }
17490   assert( GLOBAL(int, mutexIsInit) );
17491   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17492 }
17493
17494 /*
17495 ** Free a dynamic mutex.
17496 */
17497 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17498   if( p ){
17499     sqlite3GlobalConfig.mutex.xMutexFree(p);
17500   }
17501 }
17502
17503 /*
17504 ** Obtain the mutex p. If some other thread already has the mutex, block
17505 ** until it can be obtained.
17506 */
17507 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17508   if( p ){
17509     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17510   }
17511 }
17512
17513 /*
17514 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17515 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17516 */
17517 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17518   int rc = SQLITE_OK;
17519   if( p ){
17520     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17521   }
17522   return rc;
17523 }
17524
17525 /*
17526 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17527 ** entered by the same thread.  The behavior is undefined if the mutex 
17528 ** is not currently entered. If a NULL pointer is passed as an argument
17529 ** this function is a no-op.
17530 */
17531 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17532   if( p ){
17533     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17534   }
17535 }
17536
17537 #ifndef NDEBUG
17538 /*
17539 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17540 ** intended for use inside assert() statements.
17541 */
17542 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17543   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17544 }
17545 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17546   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17547 }
17548 #endif
17549
17550 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17551
17552 /************** End of mutex.c ***********************************************/
17553 /************** Begin file mutex_noop.c **************************************/
17554 /*
17555 ** 2008 October 07
17556 **
17557 ** The author disclaims copyright to this source code.  In place of
17558 ** a legal notice, here is a blessing:
17559 **
17560 **    May you do good and not evil.
17561 **    May you find forgiveness for yourself and forgive others.
17562 **    May you share freely, never taking more than you give.
17563 **
17564 *************************************************************************
17565 ** This file contains the C functions that implement mutexes.
17566 **
17567 ** This implementation in this file does not provide any mutual
17568 ** exclusion and is thus suitable for use only in applications
17569 ** that use SQLite in a single thread.  The routines defined
17570 ** here are place-holders.  Applications can substitute working
17571 ** mutex routines at start-time using the
17572 **
17573 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17574 **
17575 ** interface.
17576 **
17577 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17578 ** that does error checking on mutexes to make sure they are being
17579 ** called correctly.
17580 */
17581
17582 #ifndef SQLITE_MUTEX_OMIT
17583
17584 #ifndef SQLITE_DEBUG
17585 /*
17586 ** Stub routines for all mutex methods.
17587 **
17588 ** This routines provide no mutual exclusion or error checking.
17589 */
17590 static int noopMutexInit(void){ return SQLITE_OK; }
17591 static int noopMutexEnd(void){ return SQLITE_OK; }
17592 static sqlite3_mutex *noopMutexAlloc(int id){ 
17593   UNUSED_PARAMETER(id);
17594   return (sqlite3_mutex*)8; 
17595 }
17596 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17597 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17598 static int noopMutexTry(sqlite3_mutex *p){
17599   UNUSED_PARAMETER(p);
17600   return SQLITE_OK;
17601 }
17602 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17603
17604 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17605   static const sqlite3_mutex_methods sMutex = {
17606     noopMutexInit,
17607     noopMutexEnd,
17608     noopMutexAlloc,
17609     noopMutexFree,
17610     noopMutexEnter,
17611     noopMutexTry,
17612     noopMutexLeave,
17613
17614     0,
17615     0,
17616   };
17617
17618   return &sMutex;
17619 }
17620 #endif /* !SQLITE_DEBUG */
17621
17622 #ifdef SQLITE_DEBUG
17623 /*
17624 ** In this implementation, error checking is provided for testing
17625 ** and debugging purposes.  The mutexes still do not provide any
17626 ** mutual exclusion.
17627 */
17628
17629 /*
17630 ** The mutex object
17631 */
17632 typedef struct sqlite3_debug_mutex {
17633   int id;     /* The mutex type */
17634   int cnt;    /* Number of entries without a matching leave */
17635 } sqlite3_debug_mutex;
17636
17637 /*
17638 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17639 ** intended for use inside assert() statements.
17640 */
17641 static int debugMutexHeld(sqlite3_mutex *pX){
17642   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17643   return p==0 || p->cnt>0;
17644 }
17645 static int debugMutexNotheld(sqlite3_mutex *pX){
17646   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17647   return p==0 || p->cnt==0;
17648 }
17649
17650 /*
17651 ** Initialize and deinitialize the mutex subsystem.
17652 */
17653 static int debugMutexInit(void){ return SQLITE_OK; }
17654 static int debugMutexEnd(void){ return SQLITE_OK; }
17655
17656 /*
17657 ** The sqlite3_mutex_alloc() routine allocates a new
17658 ** mutex and returns a pointer to it.  If it returns NULL
17659 ** that means that a mutex could not be allocated. 
17660 */
17661 static sqlite3_mutex *debugMutexAlloc(int id){
17662   static sqlite3_debug_mutex aStatic[6];
17663   sqlite3_debug_mutex *pNew = 0;
17664   switch( id ){
17665     case SQLITE_MUTEX_FAST:
17666     case SQLITE_MUTEX_RECURSIVE: {
17667       pNew = sqlite3Malloc(sizeof(*pNew));
17668       if( pNew ){
17669         pNew->id = id;
17670         pNew->cnt = 0;
17671       }
17672       break;
17673     }
17674     default: {
17675       assert( id-2 >= 0 );
17676       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17677       pNew = &aStatic[id-2];
17678       pNew->id = id;
17679       break;
17680     }
17681   }
17682   return (sqlite3_mutex*)pNew;
17683 }
17684
17685 /*
17686 ** This routine deallocates a previously allocated mutex.
17687 */
17688 static void debugMutexFree(sqlite3_mutex *pX){
17689   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17690   assert( p->cnt==0 );
17691   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17692   sqlite3_free(p);
17693 }
17694
17695 /*
17696 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17697 ** to enter a mutex.  If another thread is already within the mutex,
17698 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17699 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17700 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17701 ** be entered multiple times by the same thread.  In such cases the,
17702 ** mutex must be exited an equal number of times before another thread
17703 ** can enter.  If the same thread tries to enter any other kind of mutex
17704 ** more than once, the behavior is undefined.
17705 */
17706 static void debugMutexEnter(sqlite3_mutex *pX){
17707   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17708   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17709   p->cnt++;
17710 }
17711 static int debugMutexTry(sqlite3_mutex *pX){
17712   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17713   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17714   p->cnt++;
17715   return SQLITE_OK;
17716 }
17717
17718 /*
17719 ** The sqlite3_mutex_leave() routine exits a mutex that was
17720 ** previously entered by the same thread.  The behavior
17721 ** is undefined if the mutex is not currently entered or
17722 ** is not currently allocated.  SQLite will never do either.
17723 */
17724 static void debugMutexLeave(sqlite3_mutex *pX){
17725   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17726   assert( debugMutexHeld(pX) );
17727   p->cnt--;
17728   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17729 }
17730
17731 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17732   static const sqlite3_mutex_methods sMutex = {
17733     debugMutexInit,
17734     debugMutexEnd,
17735     debugMutexAlloc,
17736     debugMutexFree,
17737     debugMutexEnter,
17738     debugMutexTry,
17739     debugMutexLeave,
17740
17741     debugMutexHeld,
17742     debugMutexNotheld
17743   };
17744
17745   return &sMutex;
17746 }
17747 #endif /* SQLITE_DEBUG */
17748
17749 /*
17750 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17751 ** is used regardless of the run-time threadsafety setting.
17752 */
17753 #ifdef SQLITE_MUTEX_NOOP
17754 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17755   return sqlite3NoopMutex();
17756 }
17757 #endif /* defined(SQLITE_MUTEX_NOOP) */
17758 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17759
17760 /************** End of mutex_noop.c ******************************************/
17761 /************** Begin file mutex_unix.c **************************************/
17762 /*
17763 ** 2007 August 28
17764 **
17765 ** The author disclaims copyright to this source code.  In place of
17766 ** a legal notice, here is a blessing:
17767 **
17768 **    May you do good and not evil.
17769 **    May you find forgiveness for yourself and forgive others.
17770 **    May you share freely, never taking more than you give.
17771 **
17772 *************************************************************************
17773 ** This file contains the C functions that implement mutexes for pthreads
17774 */
17775
17776 /*
17777 ** The code in this file is only used if we are compiling threadsafe
17778 ** under unix with pthreads.
17779 **
17780 ** Note that this implementation requires a version of pthreads that
17781 ** supports recursive mutexes.
17782 */
17783 #ifdef SQLITE_MUTEX_PTHREADS
17784
17785 #include <pthread.h>
17786
17787 /*
17788 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17789 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17790 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17791 */
17792 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17793 # define SQLITE_MUTEX_NREF 1
17794 #else
17795 # define SQLITE_MUTEX_NREF 0
17796 #endif
17797
17798 /*
17799 ** Each recursive mutex is an instance of the following structure.
17800 */
17801 struct sqlite3_mutex {
17802   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17803 #if SQLITE_MUTEX_NREF
17804   int id;                    /* Mutex type */
17805   volatile int nRef;         /* Number of entrances */
17806   volatile pthread_t owner;  /* Thread that is within this mutex */
17807   int trace;                 /* True to trace changes */
17808 #endif
17809 };
17810 #if SQLITE_MUTEX_NREF
17811 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17812 #else
17813 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17814 #endif
17815
17816 /*
17817 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17818 ** intended for use only inside assert() statements.  On some platforms,
17819 ** there might be race conditions that can cause these routines to
17820 ** deliver incorrect results.  In particular, if pthread_equal() is
17821 ** not an atomic operation, then these routines might delivery
17822 ** incorrect results.  On most platforms, pthread_equal() is a 
17823 ** comparison of two integers and is therefore atomic.  But we are
17824 ** told that HPUX is not such a platform.  If so, then these routines
17825 ** will not always work correctly on HPUX.
17826 **
17827 ** On those platforms where pthread_equal() is not atomic, SQLite
17828 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17829 ** make sure no assert() statements are evaluated and hence these
17830 ** routines are never called.
17831 */
17832 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17833 static int pthreadMutexHeld(sqlite3_mutex *p){
17834   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17835 }
17836 static int pthreadMutexNotheld(sqlite3_mutex *p){
17837   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17838 }
17839 #endif
17840
17841 /*
17842 ** Initialize and deinitialize the mutex subsystem.
17843 */
17844 static int pthreadMutexInit(void){ return SQLITE_OK; }
17845 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17846
17847 /*
17848 ** The sqlite3_mutex_alloc() routine allocates a new
17849 ** mutex and returns a pointer to it.  If it returns NULL
17850 ** that means that a mutex could not be allocated.  SQLite
17851 ** will unwind its stack and return an error.  The argument
17852 ** to sqlite3_mutex_alloc() is one of these integer constants:
17853 **
17854 ** <ul>
17855 ** <li>  SQLITE_MUTEX_FAST
17856 ** <li>  SQLITE_MUTEX_RECURSIVE
17857 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17858 ** <li>  SQLITE_MUTEX_STATIC_MEM
17859 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17860 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17861 ** <li>  SQLITE_MUTEX_STATIC_LRU
17862 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17863 ** </ul>
17864 **
17865 ** The first two constants cause sqlite3_mutex_alloc() to create
17866 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17867 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17868 ** The mutex implementation does not need to make a distinction
17869 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17870 ** not want to.  But SQLite will only request a recursive mutex in
17871 ** cases where it really needs one.  If a faster non-recursive mutex
17872 ** implementation is available on the host platform, the mutex subsystem
17873 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17874 **
17875 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17876 ** a pointer to a static preexisting mutex.  Six static mutexes are
17877 ** used by the current version of SQLite.  Future versions of SQLite
17878 ** may add additional static mutexes.  Static mutexes are for internal
17879 ** use by SQLite only.  Applications that use SQLite mutexes should
17880 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17881 ** SQLITE_MUTEX_RECURSIVE.
17882 **
17883 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17884 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17885 ** returns a different mutex on every call.  But for the static 
17886 ** mutex types, the same mutex is returned on every call that has
17887 ** the same type number.
17888 */
17889 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17890   static sqlite3_mutex staticMutexes[] = {
17891     SQLITE3_MUTEX_INITIALIZER,
17892     SQLITE3_MUTEX_INITIALIZER,
17893     SQLITE3_MUTEX_INITIALIZER,
17894     SQLITE3_MUTEX_INITIALIZER,
17895     SQLITE3_MUTEX_INITIALIZER,
17896     SQLITE3_MUTEX_INITIALIZER
17897   };
17898   sqlite3_mutex *p;
17899   switch( iType ){
17900     case SQLITE_MUTEX_RECURSIVE: {
17901       p = sqlite3MallocZero( sizeof(*p) );
17902       if( p ){
17903 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17904         /* If recursive mutexes are not available, we will have to
17905         ** build our own.  See below. */
17906         pthread_mutex_init(&p->mutex, 0);
17907 #else
17908         /* Use a recursive mutex if it is available */
17909         pthread_mutexattr_t recursiveAttr;
17910         pthread_mutexattr_init(&recursiveAttr);
17911         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17912         pthread_mutex_init(&p->mutex, &recursiveAttr);
17913         pthread_mutexattr_destroy(&recursiveAttr);
17914 #endif
17915 #if SQLITE_MUTEX_NREF
17916         p->id = iType;
17917 #endif
17918       }
17919       break;
17920     }
17921     case SQLITE_MUTEX_FAST: {
17922       p = sqlite3MallocZero( sizeof(*p) );
17923       if( p ){
17924 #if SQLITE_MUTEX_NREF
17925         p->id = iType;
17926 #endif
17927         pthread_mutex_init(&p->mutex, 0);
17928       }
17929       break;
17930     }
17931     default: {
17932       assert( iType-2 >= 0 );
17933       assert( iType-2 < ArraySize(staticMutexes) );
17934       p = &staticMutexes[iType-2];
17935 #if SQLITE_MUTEX_NREF
17936       p->id = iType;
17937 #endif
17938       break;
17939     }
17940   }
17941   return p;
17942 }
17943
17944
17945 /*
17946 ** This routine deallocates a previously
17947 ** allocated mutex.  SQLite is careful to deallocate every
17948 ** mutex that it allocates.
17949 */
17950 static void pthreadMutexFree(sqlite3_mutex *p){
17951   assert( p->nRef==0 );
17952   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17953   pthread_mutex_destroy(&p->mutex);
17954   sqlite3_free(p);
17955 }
17956
17957 /*
17958 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17959 ** to enter a mutex.  If another thread is already within the mutex,
17960 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17961 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17962 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17963 ** be entered multiple times by the same thread.  In such cases the,
17964 ** mutex must be exited an equal number of times before another thread
17965 ** can enter.  If the same thread tries to enter any other kind of mutex
17966 ** more than once, the behavior is undefined.
17967 */
17968 static void pthreadMutexEnter(sqlite3_mutex *p){
17969   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17970
17971 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17972   /* If recursive mutexes are not available, then we have to grow
17973   ** our own.  This implementation assumes that pthread_equal()
17974   ** is atomic - that it cannot be deceived into thinking self
17975   ** and p->owner are equal if p->owner changes between two values
17976   ** that are not equal to self while the comparison is taking place.
17977   ** This implementation also assumes a coherent cache - that 
17978   ** separate processes cannot read different values from the same
17979   ** address at the same time.  If either of these two conditions
17980   ** are not met, then the mutexes will fail and problems will result.
17981   */
17982   {
17983     pthread_t self = pthread_self();
17984     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17985       p->nRef++;
17986     }else{
17987       pthread_mutex_lock(&p->mutex);
17988       assert( p->nRef==0 );
17989       p->owner = self;
17990       p->nRef = 1;
17991     }
17992   }
17993 #else
17994   /* Use the built-in recursive mutexes if they are available.
17995   */
17996   pthread_mutex_lock(&p->mutex);
17997 #if SQLITE_MUTEX_NREF
17998   assert( p->nRef>0 || p->owner==0 );
17999   p->owner = pthread_self();
18000   p->nRef++;
18001 #endif
18002 #endif
18003
18004 #ifdef SQLITE_DEBUG
18005   if( p->trace ){
18006     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18007   }
18008 #endif
18009 }
18010 static int pthreadMutexTry(sqlite3_mutex *p){
18011   int rc;
18012   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18013
18014 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18015   /* If recursive mutexes are not available, then we have to grow
18016   ** our own.  This implementation assumes that pthread_equal()
18017   ** is atomic - that it cannot be deceived into thinking self
18018   ** and p->owner are equal if p->owner changes between two values
18019   ** that are not equal to self while the comparison is taking place.
18020   ** This implementation also assumes a coherent cache - that 
18021   ** separate processes cannot read different values from the same
18022   ** address at the same time.  If either of these two conditions
18023   ** are not met, then the mutexes will fail and problems will result.
18024   */
18025   {
18026     pthread_t self = pthread_self();
18027     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18028       p->nRef++;
18029       rc = SQLITE_OK;
18030     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18031       assert( p->nRef==0 );
18032       p->owner = self;
18033       p->nRef = 1;
18034       rc = SQLITE_OK;
18035     }else{
18036       rc = SQLITE_BUSY;
18037     }
18038   }
18039 #else
18040   /* Use the built-in recursive mutexes if they are available.
18041   */
18042   if( pthread_mutex_trylock(&p->mutex)==0 ){
18043 #if SQLITE_MUTEX_NREF
18044     p->owner = pthread_self();
18045     p->nRef++;
18046 #endif
18047     rc = SQLITE_OK;
18048   }else{
18049     rc = SQLITE_BUSY;
18050   }
18051 #endif
18052
18053 #ifdef SQLITE_DEBUG
18054   if( rc==SQLITE_OK && p->trace ){
18055     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18056   }
18057 #endif
18058   return rc;
18059 }
18060
18061 /*
18062 ** The sqlite3_mutex_leave() routine exits a mutex that was
18063 ** previously entered by the same thread.  The behavior
18064 ** is undefined if the mutex is not currently entered or
18065 ** is not currently allocated.  SQLite will never do either.
18066 */
18067 static void pthreadMutexLeave(sqlite3_mutex *p){
18068   assert( pthreadMutexHeld(p) );
18069 #if SQLITE_MUTEX_NREF
18070   p->nRef--;
18071   if( p->nRef==0 ) p->owner = 0;
18072 #endif
18073   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18074
18075 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18076   if( p->nRef==0 ){
18077     pthread_mutex_unlock(&p->mutex);
18078   }
18079 #else
18080   pthread_mutex_unlock(&p->mutex);
18081 #endif
18082
18083 #ifdef SQLITE_DEBUG
18084   if( p->trace ){
18085     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18086   }
18087 #endif
18088 }
18089
18090 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18091   static const sqlite3_mutex_methods sMutex = {
18092     pthreadMutexInit,
18093     pthreadMutexEnd,
18094     pthreadMutexAlloc,
18095     pthreadMutexFree,
18096     pthreadMutexEnter,
18097     pthreadMutexTry,
18098     pthreadMutexLeave,
18099 #ifdef SQLITE_DEBUG
18100     pthreadMutexHeld,
18101     pthreadMutexNotheld
18102 #else
18103     0,
18104     0
18105 #endif
18106   };
18107
18108   return &sMutex;
18109 }
18110
18111 #endif /* SQLITE_MUTEX_PTHREADS */
18112
18113 /************** End of mutex_unix.c ******************************************/
18114 /************** Begin file mutex_w32.c ***************************************/
18115 /*
18116 ** 2007 August 14
18117 **
18118 ** The author disclaims copyright to this source code.  In place of
18119 ** a legal notice, here is a blessing:
18120 **
18121 **    May you do good and not evil.
18122 **    May you find forgiveness for yourself and forgive others.
18123 **    May you share freely, never taking more than you give.
18124 **
18125 *************************************************************************
18126 ** This file contains the C functions that implement mutexes for win32
18127 */
18128
18129 /*
18130 ** The code in this file is only used if we are compiling multithreaded
18131 ** on a win32 system.
18132 */
18133 #ifdef SQLITE_MUTEX_W32
18134
18135 /*
18136 ** Each recursive mutex is an instance of the following structure.
18137 */
18138 struct sqlite3_mutex {
18139   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18140   int id;                    /* Mutex type */
18141 #ifdef SQLITE_DEBUG
18142   volatile int nRef;         /* Number of enterances */
18143   volatile DWORD owner;      /* Thread holding this mutex */
18144   int trace;                 /* True to trace changes */
18145 #endif
18146 };
18147 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18148 #ifdef SQLITE_DEBUG
18149 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18150 #else
18151 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18152 #endif
18153
18154 /*
18155 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18156 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18157 **
18158 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18159 ** the LockFileEx() API.  But we can still statically link against that
18160 ** API as long as we don't call it win running Win95/98/ME.  A call to
18161 ** this routine is used to determine if the host is Win95/98/ME or
18162 ** WinNT/2K/XP so that we will know whether or not we can safely call
18163 ** the LockFileEx() API.
18164 **
18165 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18166 ** which is only available if your application was compiled with 
18167 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18168 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18169 ** this out as well.
18170 */
18171 #if 0
18172 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18173 # define mutexIsNT()  (1)
18174 #else
18175   static int mutexIsNT(void){
18176     static int osType = 0;
18177     if( osType==0 ){
18178       OSVERSIONINFO sInfo;
18179       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18180       GetVersionEx(&sInfo);
18181       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18182     }
18183     return osType==2;
18184   }
18185 #endif /* SQLITE_OS_WINCE */
18186 #endif
18187
18188 #ifdef SQLITE_DEBUG
18189 /*
18190 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18191 ** intended for use only inside assert() statements.
18192 */
18193 static int winMutexHeld(sqlite3_mutex *p){
18194   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18195 }
18196 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18197   return p->nRef==0 || p->owner!=tid;
18198 }
18199 static int winMutexNotheld(sqlite3_mutex *p){
18200   DWORD tid = GetCurrentThreadId(); 
18201   return winMutexNotheld2(p, tid);
18202 }
18203 #endif
18204
18205
18206 /*
18207 ** Initialize and deinitialize the mutex subsystem.
18208 */
18209 static sqlite3_mutex winMutex_staticMutexes[6] = {
18210   SQLITE3_MUTEX_INITIALIZER,
18211   SQLITE3_MUTEX_INITIALIZER,
18212   SQLITE3_MUTEX_INITIALIZER,
18213   SQLITE3_MUTEX_INITIALIZER,
18214   SQLITE3_MUTEX_INITIALIZER,
18215   SQLITE3_MUTEX_INITIALIZER
18216 };
18217 static int winMutex_isInit = 0;
18218 /* As winMutexInit() and winMutexEnd() are called as part
18219 ** of the sqlite3_initialize and sqlite3_shutdown()
18220 ** processing, the "interlocked" magic is probably not
18221 ** strictly necessary.
18222 */
18223 static long winMutex_lock = 0;
18224
18225 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18226
18227 static int winMutexInit(void){ 
18228   /* The first to increment to 1 does actual initialization */
18229   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18230     int i;
18231     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18232 #if SQLITE_OS_WINRT
18233       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18234 #else
18235       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18236 #endif
18237     }
18238     winMutex_isInit = 1;
18239   }else{
18240     /* Someone else is in the process of initing the static mutexes */
18241     while( !winMutex_isInit ){
18242       sqlite3_win32_sleep(1);
18243     }
18244   }
18245   return SQLITE_OK; 
18246 }
18247
18248 static int winMutexEnd(void){ 
18249   /* The first to decrement to 0 does actual shutdown 
18250   ** (which should be the last to shutdown.) */
18251   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18252     if( winMutex_isInit==1 ){
18253       int i;
18254       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18255         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18256       }
18257       winMutex_isInit = 0;
18258     }
18259   }
18260   return SQLITE_OK; 
18261 }
18262
18263 /*
18264 ** The sqlite3_mutex_alloc() routine allocates a new
18265 ** mutex and returns a pointer to it.  If it returns NULL
18266 ** that means that a mutex could not be allocated.  SQLite
18267 ** will unwind its stack and return an error.  The argument
18268 ** to sqlite3_mutex_alloc() is one of these integer constants:
18269 **
18270 ** <ul>
18271 ** <li>  SQLITE_MUTEX_FAST
18272 ** <li>  SQLITE_MUTEX_RECURSIVE
18273 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18274 ** <li>  SQLITE_MUTEX_STATIC_MEM
18275 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18276 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18277 ** <li>  SQLITE_MUTEX_STATIC_LRU
18278 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18279 ** </ul>
18280 **
18281 ** The first two constants cause sqlite3_mutex_alloc() to create
18282 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18283 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18284 ** The mutex implementation does not need to make a distinction
18285 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18286 ** not want to.  But SQLite will only request a recursive mutex in
18287 ** cases where it really needs one.  If a faster non-recursive mutex
18288 ** implementation is available on the host platform, the mutex subsystem
18289 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18290 **
18291 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18292 ** a pointer to a static preexisting mutex.  Six static mutexes are
18293 ** used by the current version of SQLite.  Future versions of SQLite
18294 ** may add additional static mutexes.  Static mutexes are for internal
18295 ** use by SQLite only.  Applications that use SQLite mutexes should
18296 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18297 ** SQLITE_MUTEX_RECURSIVE.
18298 **
18299 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18300 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18301 ** returns a different mutex on every call.  But for the static 
18302 ** mutex types, the same mutex is returned on every call that has
18303 ** the same type number.
18304 */
18305 static sqlite3_mutex *winMutexAlloc(int iType){
18306   sqlite3_mutex *p;
18307
18308   switch( iType ){
18309     case SQLITE_MUTEX_FAST:
18310     case SQLITE_MUTEX_RECURSIVE: {
18311       p = sqlite3MallocZero( sizeof(*p) );
18312       if( p ){  
18313 #ifdef SQLITE_DEBUG
18314         p->id = iType;
18315 #endif
18316 #if SQLITE_OS_WINRT
18317         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18318 #else
18319         InitializeCriticalSection(&p->mutex);
18320 #endif
18321       }
18322       break;
18323     }
18324     default: {
18325       assert( winMutex_isInit==1 );
18326       assert( iType-2 >= 0 );
18327       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18328       p = &winMutex_staticMutexes[iType-2];
18329 #ifdef SQLITE_DEBUG
18330       p->id = iType;
18331 #endif
18332       break;
18333     }
18334   }
18335   return p;
18336 }
18337
18338
18339 /*
18340 ** This routine deallocates a previously
18341 ** allocated mutex.  SQLite is careful to deallocate every
18342 ** mutex that it allocates.
18343 */
18344 static void winMutexFree(sqlite3_mutex *p){
18345   assert( p );
18346   assert( p->nRef==0 && p->owner==0 );
18347   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18348   DeleteCriticalSection(&p->mutex);
18349   sqlite3_free(p);
18350 }
18351
18352 /*
18353 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18354 ** to enter a mutex.  If another thread is already within the mutex,
18355 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18356 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18357 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18358 ** be entered multiple times by the same thread.  In such cases the,
18359 ** mutex must be exited an equal number of times before another thread
18360 ** can enter.  If the same thread tries to enter any other kind of mutex
18361 ** more than once, the behavior is undefined.
18362 */
18363 static void winMutexEnter(sqlite3_mutex *p){
18364 #ifdef SQLITE_DEBUG
18365   DWORD tid = GetCurrentThreadId(); 
18366   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18367 #endif
18368   EnterCriticalSection(&p->mutex);
18369 #ifdef SQLITE_DEBUG
18370   assert( p->nRef>0 || p->owner==0 );
18371   p->owner = tid; 
18372   p->nRef++;
18373   if( p->trace ){
18374     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18375   }
18376 #endif
18377 }
18378 static int winMutexTry(sqlite3_mutex *p){
18379 #ifndef NDEBUG
18380   DWORD tid = GetCurrentThreadId(); 
18381 #endif
18382   int rc = SQLITE_BUSY;
18383   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18384   /*
18385   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18386   ** is used it is merely an optimization.  So it is OK for it to always
18387   ** fail.  
18388   **
18389   ** The TryEnterCriticalSection() interface is only available on WinNT.
18390   ** And some windows compilers complain if you try to use it without
18391   ** first doing some #defines that prevent SQLite from building on Win98.
18392   ** For that reason, we will omit this optimization for now.  See
18393   ** ticket #2685.
18394   */
18395 #if 0
18396   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18397     p->owner = tid;
18398     p->nRef++;
18399     rc = SQLITE_OK;
18400   }
18401 #else
18402   UNUSED_PARAMETER(p);
18403 #endif
18404 #ifdef SQLITE_DEBUG
18405   if( rc==SQLITE_OK && p->trace ){
18406     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18407   }
18408 #endif
18409   return rc;
18410 }
18411
18412 /*
18413 ** The sqlite3_mutex_leave() routine exits a mutex that was
18414 ** previously entered by the same thread.  The behavior
18415 ** is undefined if the mutex is not currently entered or
18416 ** is not currently allocated.  SQLite will never do either.
18417 */
18418 static void winMutexLeave(sqlite3_mutex *p){
18419 #ifndef NDEBUG
18420   DWORD tid = GetCurrentThreadId();
18421   assert( p->nRef>0 );
18422   assert( p->owner==tid );
18423   p->nRef--;
18424   if( p->nRef==0 ) p->owner = 0;
18425   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18426 #endif
18427   LeaveCriticalSection(&p->mutex);
18428 #ifdef SQLITE_DEBUG
18429   if( p->trace ){
18430     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18431   }
18432 #endif
18433 }
18434
18435 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18436   static const sqlite3_mutex_methods sMutex = {
18437     winMutexInit,
18438     winMutexEnd,
18439     winMutexAlloc,
18440     winMutexFree,
18441     winMutexEnter,
18442     winMutexTry,
18443     winMutexLeave,
18444 #ifdef SQLITE_DEBUG
18445     winMutexHeld,
18446     winMutexNotheld
18447 #else
18448     0,
18449     0
18450 #endif
18451   };
18452
18453   return &sMutex;
18454 }
18455 #endif /* SQLITE_MUTEX_W32 */
18456
18457 /************** End of mutex_w32.c *******************************************/
18458 /************** Begin file malloc.c ******************************************/
18459 /*
18460 ** 2001 September 15
18461 **
18462 ** The author disclaims copyright to this source code.  In place of
18463 ** a legal notice, here is a blessing:
18464 **
18465 **    May you do good and not evil.
18466 **    May you find forgiveness for yourself and forgive others.
18467 **    May you share freely, never taking more than you give.
18468 **
18469 *************************************************************************
18470 **
18471 ** Memory allocation functions used throughout sqlite.
18472 */
18473 /* #include <stdarg.h> */
18474
18475 /*
18476 ** Attempt to release up to n bytes of non-essential memory currently
18477 ** held by SQLite. An example of non-essential memory is memory used to
18478 ** cache database pages that are not currently in use.
18479 */
18480 SQLITE_API int sqlite3_release_memory(int n){
18481 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18482   return sqlite3PcacheReleaseMemory(n);
18483 #else
18484   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18485   ** is a no-op returning zero if SQLite is not compiled with
18486   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18487   UNUSED_PARAMETER(n);
18488   return 0;
18489 #endif
18490 }
18491
18492 /*
18493 ** An instance of the following object records the location of
18494 ** each unused scratch buffer.
18495 */
18496 typedef struct ScratchFreeslot {
18497   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18498 } ScratchFreeslot;
18499
18500 /*
18501 ** State information local to the memory allocation subsystem.
18502 */
18503 static SQLITE_WSD struct Mem0Global {
18504   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18505
18506   /*
18507   ** The alarm callback and its arguments.  The mem0.mutex lock will
18508   ** be held while the callback is running.  Recursive calls into
18509   ** the memory subsystem are allowed, but no new callbacks will be
18510   ** issued.
18511   */
18512   sqlite3_int64 alarmThreshold;
18513   void (*alarmCallback)(void*, sqlite3_int64,int);
18514   void *alarmArg;
18515
18516   /*
18517   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18518   ** (so that a range test can be used to determine if an allocation
18519   ** being freed came from pScratch) and a pointer to the list of
18520   ** unused scratch allocations.
18521   */
18522   void *pScratchEnd;
18523   ScratchFreeslot *pScratchFree;
18524   u32 nScratchFree;
18525
18526   /*
18527   ** True if heap is nearly "full" where "full" is defined by the
18528   ** sqlite3_soft_heap_limit() setting.
18529   */
18530   int nearlyFull;
18531 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18532
18533 #define mem0 GLOBAL(struct Mem0Global, mem0)
18534
18535 /*
18536 ** This routine runs when the memory allocator sees that the
18537 ** total memory allocation is about to exceed the soft heap
18538 ** limit.
18539 */
18540 static void softHeapLimitEnforcer(
18541   void *NotUsed, 
18542   sqlite3_int64 NotUsed2,
18543   int allocSize
18544 ){
18545   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18546   sqlite3_release_memory(allocSize);
18547 }
18548
18549 /*
18550 ** Change the alarm callback
18551 */
18552 static int sqlite3MemoryAlarm(
18553   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18554   void *pArg,
18555   sqlite3_int64 iThreshold
18556 ){
18557   int nUsed;
18558   sqlite3_mutex_enter(mem0.mutex);
18559   mem0.alarmCallback = xCallback;
18560   mem0.alarmArg = pArg;
18561   mem0.alarmThreshold = iThreshold;
18562   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18563   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18564   sqlite3_mutex_leave(mem0.mutex);
18565   return SQLITE_OK;
18566 }
18567
18568 #ifndef SQLITE_OMIT_DEPRECATED
18569 /*
18570 ** Deprecated external interface.  Internal/core SQLite code
18571 ** should call sqlite3MemoryAlarm.
18572 */
18573 SQLITE_API int sqlite3_memory_alarm(
18574   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18575   void *pArg,
18576   sqlite3_int64 iThreshold
18577 ){
18578   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18579 }
18580 #endif
18581
18582 /*
18583 ** Set the soft heap-size limit for the library. Passing a zero or 
18584 ** negative value indicates no limit.
18585 */
18586 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18587   sqlite3_int64 priorLimit;
18588   sqlite3_int64 excess;
18589 #ifndef SQLITE_OMIT_AUTOINIT
18590   int rc = sqlite3_initialize();
18591   if( rc ) return -1;
18592 #endif
18593   sqlite3_mutex_enter(mem0.mutex);
18594   priorLimit = mem0.alarmThreshold;
18595   sqlite3_mutex_leave(mem0.mutex);
18596   if( n<0 ) return priorLimit;
18597   if( n>0 ){
18598     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18599   }else{
18600     sqlite3MemoryAlarm(0, 0, 0);
18601   }
18602   excess = sqlite3_memory_used() - n;
18603   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18604   return priorLimit;
18605 }
18606 SQLITE_API void sqlite3_soft_heap_limit(int n){
18607   if( n<0 ) n = 0;
18608   sqlite3_soft_heap_limit64(n);
18609 }
18610
18611 /*
18612 ** Initialize the memory allocation subsystem.
18613 */
18614 SQLITE_PRIVATE int sqlite3MallocInit(void){
18615   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18616     sqlite3MemSetDefault();
18617   }
18618   memset(&mem0, 0, sizeof(mem0));
18619   if( sqlite3GlobalConfig.bCoreMutex ){
18620     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18621   }
18622   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18623       && sqlite3GlobalConfig.nScratch>0 ){
18624     int i, n, sz;
18625     ScratchFreeslot *pSlot;
18626     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18627     sqlite3GlobalConfig.szScratch = sz;
18628     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18629     n = sqlite3GlobalConfig.nScratch;
18630     mem0.pScratchFree = pSlot;
18631     mem0.nScratchFree = n;
18632     for(i=0; i<n-1; i++){
18633       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18634       pSlot = pSlot->pNext;
18635     }
18636     pSlot->pNext = 0;
18637     mem0.pScratchEnd = (void*)&pSlot[1];
18638   }else{
18639     mem0.pScratchEnd = 0;
18640     sqlite3GlobalConfig.pScratch = 0;
18641     sqlite3GlobalConfig.szScratch = 0;
18642     sqlite3GlobalConfig.nScratch = 0;
18643   }
18644   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18645       || sqlite3GlobalConfig.nPage<1 ){
18646     sqlite3GlobalConfig.pPage = 0;
18647     sqlite3GlobalConfig.szPage = 0;
18648     sqlite3GlobalConfig.nPage = 0;
18649   }
18650   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18651 }
18652
18653 /*
18654 ** Return true if the heap is currently under memory pressure - in other
18655 ** words if the amount of heap used is close to the limit set by
18656 ** sqlite3_soft_heap_limit().
18657 */
18658 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18659   return mem0.nearlyFull;
18660 }
18661
18662 /*
18663 ** Deinitialize the memory allocation subsystem.
18664 */
18665 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18666   if( sqlite3GlobalConfig.m.xShutdown ){
18667     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18668   }
18669   memset(&mem0, 0, sizeof(mem0));
18670 }
18671
18672 /*
18673 ** Return the amount of memory currently checked out.
18674 */
18675 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18676   int n, mx;
18677   sqlite3_int64 res;
18678   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18679   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18680   return res;
18681 }
18682
18683 /*
18684 ** Return the maximum amount of memory that has ever been
18685 ** checked out since either the beginning of this process
18686 ** or since the most recent reset.
18687 */
18688 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18689   int n, mx;
18690   sqlite3_int64 res;
18691   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18692   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18693   return res;
18694 }
18695
18696 /*
18697 ** Trigger the alarm 
18698 */
18699 static void sqlite3MallocAlarm(int nByte){
18700   void (*xCallback)(void*,sqlite3_int64,int);
18701   sqlite3_int64 nowUsed;
18702   void *pArg;
18703   if( mem0.alarmCallback==0 ) return;
18704   xCallback = mem0.alarmCallback;
18705   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18706   pArg = mem0.alarmArg;
18707   mem0.alarmCallback = 0;
18708   sqlite3_mutex_leave(mem0.mutex);
18709   xCallback(pArg, nowUsed, nByte);
18710   sqlite3_mutex_enter(mem0.mutex);
18711   mem0.alarmCallback = xCallback;
18712   mem0.alarmArg = pArg;
18713 }
18714
18715 /*
18716 ** Do a memory allocation with statistics and alarms.  Assume the
18717 ** lock is already held.
18718 */
18719 static int mallocWithAlarm(int n, void **pp){
18720   int nFull;
18721   void *p;
18722   assert( sqlite3_mutex_held(mem0.mutex) );
18723   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18724   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18725   if( mem0.alarmCallback!=0 ){
18726     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18727     if( nUsed >= mem0.alarmThreshold - nFull ){
18728       mem0.nearlyFull = 1;
18729       sqlite3MallocAlarm(nFull);
18730     }else{
18731       mem0.nearlyFull = 0;
18732     }
18733   }
18734   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18735 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18736   if( p==0 && mem0.alarmCallback ){
18737     sqlite3MallocAlarm(nFull);
18738     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18739   }
18740 #endif
18741   if( p ){
18742     nFull = sqlite3MallocSize(p);
18743     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18744     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18745   }
18746   *pp = p;
18747   return nFull;
18748 }
18749
18750 /*
18751 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18752 ** assumes the memory subsystem has already been initialized.
18753 */
18754 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18755   void *p;
18756   if( n<=0               /* IMP: R-65312-04917 */ 
18757    || n>=0x7fffff00
18758   ){
18759     /* A memory allocation of a number of bytes which is near the maximum
18760     ** signed integer value might cause an integer overflow inside of the
18761     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18762     ** 255 bytes of overhead.  SQLite itself will never use anything near
18763     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18764     p = 0;
18765   }else if( sqlite3GlobalConfig.bMemstat ){
18766     sqlite3_mutex_enter(mem0.mutex);
18767     mallocWithAlarm(n, &p);
18768     sqlite3_mutex_leave(mem0.mutex);
18769   }else{
18770     p = sqlite3GlobalConfig.m.xMalloc(n);
18771   }
18772   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18773   return p;
18774 }
18775
18776 /*
18777 ** This version of the memory allocation is for use by the application.
18778 ** First make sure the memory subsystem is initialized, then do the
18779 ** allocation.
18780 */
18781 SQLITE_API void *sqlite3_malloc(int n){
18782 #ifndef SQLITE_OMIT_AUTOINIT
18783   if( sqlite3_initialize() ) return 0;
18784 #endif
18785   return sqlite3Malloc(n);
18786 }
18787
18788 /*
18789 ** Each thread may only have a single outstanding allocation from
18790 ** xScratchMalloc().  We verify this constraint in the single-threaded
18791 ** case by setting scratchAllocOut to 1 when an allocation
18792 ** is outstanding clearing it when the allocation is freed.
18793 */
18794 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18795 static int scratchAllocOut = 0;
18796 #endif
18797
18798
18799 /*
18800 ** Allocate memory that is to be used and released right away.
18801 ** This routine is similar to alloca() in that it is not intended
18802 ** for situations where the memory might be held long-term.  This
18803 ** routine is intended to get memory to old large transient data
18804 ** structures that would not normally fit on the stack of an
18805 ** embedded processor.
18806 */
18807 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18808   void *p;
18809   assert( n>0 );
18810
18811   sqlite3_mutex_enter(mem0.mutex);
18812   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18813     p = mem0.pScratchFree;
18814     mem0.pScratchFree = mem0.pScratchFree->pNext;
18815     mem0.nScratchFree--;
18816     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18817     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18818     sqlite3_mutex_leave(mem0.mutex);
18819   }else{
18820     if( sqlite3GlobalConfig.bMemstat ){
18821       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18822       n = mallocWithAlarm(n, &p);
18823       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18824       sqlite3_mutex_leave(mem0.mutex);
18825     }else{
18826       sqlite3_mutex_leave(mem0.mutex);
18827       p = sqlite3GlobalConfig.m.xMalloc(n);
18828     }
18829     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18830   }
18831   assert( sqlite3_mutex_notheld(mem0.mutex) );
18832
18833
18834 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18835   /* Verify that no more than two scratch allocations per thread
18836   ** are outstanding at one time.  (This is only checked in the
18837   ** single-threaded case since checking in the multi-threaded case
18838   ** would be much more complicated.) */
18839   assert( scratchAllocOut<=1 );
18840   if( p ) scratchAllocOut++;
18841 #endif
18842
18843   return p;
18844 }
18845 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18846   if( p ){
18847
18848 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18849     /* Verify that no more than two scratch allocation per thread
18850     ** is outstanding at one time.  (This is only checked in the
18851     ** single-threaded case since checking in the multi-threaded case
18852     ** would be much more complicated.) */
18853     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18854     scratchAllocOut--;
18855 #endif
18856
18857     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18858       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18859       ScratchFreeslot *pSlot;
18860       pSlot = (ScratchFreeslot*)p;
18861       sqlite3_mutex_enter(mem0.mutex);
18862       pSlot->pNext = mem0.pScratchFree;
18863       mem0.pScratchFree = pSlot;
18864       mem0.nScratchFree++;
18865       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18866       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18867       sqlite3_mutex_leave(mem0.mutex);
18868     }else{
18869       /* Release memory back to the heap */
18870       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18871       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18872       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18873       if( sqlite3GlobalConfig.bMemstat ){
18874         int iSize = sqlite3MallocSize(p);
18875         sqlite3_mutex_enter(mem0.mutex);
18876         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18877         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18878         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18879         sqlite3GlobalConfig.m.xFree(p);
18880         sqlite3_mutex_leave(mem0.mutex);
18881       }else{
18882         sqlite3GlobalConfig.m.xFree(p);
18883       }
18884     }
18885   }
18886 }
18887
18888 /*
18889 ** TRUE if p is a lookaside memory allocation from db
18890 */
18891 #ifndef SQLITE_OMIT_LOOKASIDE
18892 static int isLookaside(sqlite3 *db, void *p){
18893   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18894 }
18895 #else
18896 #define isLookaside(A,B) 0
18897 #endif
18898
18899 /*
18900 ** Return the size of a memory allocation previously obtained from
18901 ** sqlite3Malloc() or sqlite3_malloc().
18902 */
18903 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18904   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18905   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18906   return sqlite3GlobalConfig.m.xSize(p);
18907 }
18908 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18909   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18910   if( db && isLookaside(db, p) ){
18911     return db->lookaside.sz;
18912   }else{
18913     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18914     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18915     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18916     return sqlite3GlobalConfig.m.xSize(p);
18917   }
18918 }
18919
18920 /*
18921 ** Free memory previously obtained from sqlite3Malloc().
18922 */
18923 SQLITE_API void sqlite3_free(void *p){
18924   if( p==0 ) return;  /* IMP: R-49053-54554 */
18925   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18926   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18927   if( sqlite3GlobalConfig.bMemstat ){
18928     sqlite3_mutex_enter(mem0.mutex);
18929     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18930     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18931     sqlite3GlobalConfig.m.xFree(p);
18932     sqlite3_mutex_leave(mem0.mutex);
18933   }else{
18934     sqlite3GlobalConfig.m.xFree(p);
18935   }
18936 }
18937
18938 /*
18939 ** Free memory that might be associated with a particular database
18940 ** connection.
18941 */
18942 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18943   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18944   if( db ){
18945     if( db->pnBytesFreed ){
18946       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18947       return;
18948     }
18949     if( isLookaside(db, p) ){
18950       LookasideSlot *pBuf = (LookasideSlot*)p;
18951 #if SQLITE_DEBUG
18952       /* Trash all content in the buffer being freed */
18953       memset(p, 0xaa, db->lookaside.sz);
18954 #endif
18955       pBuf->pNext = db->lookaside.pFree;
18956       db->lookaside.pFree = pBuf;
18957       db->lookaside.nOut--;
18958       return;
18959     }
18960   }
18961   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18962   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18963   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18964   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18965   sqlite3_free(p);
18966 }
18967
18968 /*
18969 ** Change the size of an existing memory allocation
18970 */
18971 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18972   int nOld, nNew, nDiff;
18973   void *pNew;
18974   if( pOld==0 ){
18975     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18976   }
18977   if( nBytes<=0 ){
18978     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18979     return 0;
18980   }
18981   if( nBytes>=0x7fffff00 ){
18982     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18983     return 0;
18984   }
18985   nOld = sqlite3MallocSize(pOld);
18986   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18987   ** argument to xRealloc is always a value returned by a prior call to
18988   ** xRoundup. */
18989   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18990   if( nOld==nNew ){
18991     pNew = pOld;
18992   }else if( sqlite3GlobalConfig.bMemstat ){
18993     sqlite3_mutex_enter(mem0.mutex);
18994     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18995     nDiff = nNew - nOld;
18996     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
18997           mem0.alarmThreshold-nDiff ){
18998       sqlite3MallocAlarm(nDiff);
18999     }
19000     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19001     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19002     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19003     if( pNew==0 && mem0.alarmCallback ){
19004       sqlite3MallocAlarm(nBytes);
19005       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19006     }
19007     if( pNew ){
19008       nNew = sqlite3MallocSize(pNew);
19009       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19010     }
19011     sqlite3_mutex_leave(mem0.mutex);
19012   }else{
19013     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19014   }
19015   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19016   return pNew;
19017 }
19018
19019 /*
19020 ** The public interface to sqlite3Realloc.  Make sure that the memory
19021 ** subsystem is initialized prior to invoking sqliteRealloc.
19022 */
19023 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19024 #ifndef SQLITE_OMIT_AUTOINIT
19025   if( sqlite3_initialize() ) return 0;
19026 #endif
19027   return sqlite3Realloc(pOld, n);
19028 }
19029
19030
19031 /*
19032 ** Allocate and zero memory.
19033 */ 
19034 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19035   void *p = sqlite3Malloc(n);
19036   if( p ){
19037     memset(p, 0, n);
19038   }
19039   return p;
19040 }
19041
19042 /*
19043 ** Allocate and zero memory.  If the allocation fails, make
19044 ** the mallocFailed flag in the connection pointer.
19045 */
19046 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19047   void *p = sqlite3DbMallocRaw(db, n);
19048   if( p ){
19049     memset(p, 0, n);
19050   }
19051   return p;
19052 }
19053
19054 /*
19055 ** Allocate and zero memory.  If the allocation fails, make
19056 ** the mallocFailed flag in the connection pointer.
19057 **
19058 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19059 ** failure on the same database connection) then always return 0.
19060 ** Hence for a particular database connection, once malloc starts
19061 ** failing, it fails consistently until mallocFailed is reset.
19062 ** This is an important assumption.  There are many places in the
19063 ** code that do things like this:
19064 **
19065 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19066 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19067 **         if( b ) a[10] = 9;
19068 **
19069 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19070 ** that all prior mallocs (ex: "a") worked too.
19071 */
19072 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19073   void *p;
19074   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19075   assert( db==0 || db->pnBytesFreed==0 );
19076 #ifndef SQLITE_OMIT_LOOKASIDE
19077   if( db ){
19078     LookasideSlot *pBuf;
19079     if( db->mallocFailed ){
19080       return 0;
19081     }
19082     if( db->lookaside.bEnabled ){
19083       if( n>db->lookaside.sz ){
19084         db->lookaside.anStat[1]++;
19085       }else if( (pBuf = db->lookaside.pFree)==0 ){
19086         db->lookaside.anStat[2]++;
19087       }else{
19088         db->lookaside.pFree = pBuf->pNext;
19089         db->lookaside.nOut++;
19090         db->lookaside.anStat[0]++;
19091         if( db->lookaside.nOut>db->lookaside.mxOut ){
19092           db->lookaside.mxOut = db->lookaside.nOut;
19093         }
19094         return (void*)pBuf;
19095       }
19096     }
19097   }
19098 #else
19099   if( db && db->mallocFailed ){
19100     return 0;
19101   }
19102 #endif
19103   p = sqlite3Malloc(n);
19104   if( !p && db ){
19105     db->mallocFailed = 1;
19106   }
19107   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19108          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19109   return p;
19110 }
19111
19112 /*
19113 ** Resize the block of memory pointed to by p to n bytes. If the
19114 ** resize fails, set the mallocFailed flag in the connection object.
19115 */
19116 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19117   void *pNew = 0;
19118   assert( db!=0 );
19119   assert( sqlite3_mutex_held(db->mutex) );
19120   if( db->mallocFailed==0 ){
19121     if( p==0 ){
19122       return sqlite3DbMallocRaw(db, n);
19123     }
19124     if( isLookaside(db, p) ){
19125       if( n<=db->lookaside.sz ){
19126         return p;
19127       }
19128       pNew = sqlite3DbMallocRaw(db, n);
19129       if( pNew ){
19130         memcpy(pNew, p, db->lookaside.sz);
19131         sqlite3DbFree(db, p);
19132       }
19133     }else{
19134       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19135       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19136       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19137       pNew = sqlite3_realloc(p, n);
19138       if( !pNew ){
19139         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19140         db->mallocFailed = 1;
19141       }
19142       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19143             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19144     }
19145   }
19146   return pNew;
19147 }
19148
19149 /*
19150 ** Attempt to reallocate p.  If the reallocation fails, then free p
19151 ** and set the mallocFailed flag in the database connection.
19152 */
19153 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19154   void *pNew;
19155   pNew = sqlite3DbRealloc(db, p, n);
19156   if( !pNew ){
19157     sqlite3DbFree(db, p);
19158   }
19159   return pNew;
19160 }
19161
19162 /*
19163 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19164 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19165 ** is because when memory debugging is turned on, these two functions are 
19166 ** called via macros that record the current file and line number in the
19167 ** ThreadData structure.
19168 */
19169 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19170   char *zNew;
19171   size_t n;
19172   if( z==0 ){
19173     return 0;
19174   }
19175   n = sqlite3Strlen30(z) + 1;
19176   assert( (n&0x7fffffff)==n );
19177   zNew = sqlite3DbMallocRaw(db, (int)n);
19178   if( zNew ){
19179     memcpy(zNew, z, n);
19180   }
19181   return zNew;
19182 }
19183 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19184   char *zNew;
19185   if( z==0 ){
19186     return 0;
19187   }
19188   assert( (n&0x7fffffff)==n );
19189   zNew = sqlite3DbMallocRaw(db, n+1);
19190   if( zNew ){
19191     memcpy(zNew, z, n);
19192     zNew[n] = 0;
19193   }
19194   return zNew;
19195 }
19196
19197 /*
19198 ** Create a string from the zFromat argument and the va_list that follows.
19199 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19200 ** point to that string.
19201 */
19202 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19203   va_list ap;
19204   char *z;
19205
19206   va_start(ap, zFormat);
19207   z = sqlite3VMPrintf(db, zFormat, ap);
19208   va_end(ap);
19209   sqlite3DbFree(db, *pz);
19210   *pz = z;
19211 }
19212
19213
19214 /*
19215 ** This function must be called before exiting any API function (i.e. 
19216 ** returning control to the user) that has called sqlite3_malloc or
19217 ** sqlite3_realloc.
19218 **
19219 ** The returned value is normally a copy of the second argument to this
19220 ** function. However, if a malloc() failure has occurred since the previous
19221 ** invocation SQLITE_NOMEM is returned instead. 
19222 **
19223 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19224 ** then the connection error-code (the value returned by sqlite3_errcode())
19225 ** is set to SQLITE_NOMEM.
19226 */
19227 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19228   /* If the db handle is not NULL, then we must hold the connection handle
19229   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19230   ** is unsafe, as is the call to sqlite3Error().
19231   */
19232   assert( !db || sqlite3_mutex_held(db->mutex) );
19233   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19234     sqlite3Error(db, SQLITE_NOMEM, 0);
19235     db->mallocFailed = 0;
19236     rc = SQLITE_NOMEM;
19237   }
19238   return rc & (db ? db->errMask : 0xff);
19239 }
19240
19241 /************** End of malloc.c **********************************************/
19242 /************** Begin file printf.c ******************************************/
19243 /*
19244 ** The "printf" code that follows dates from the 1980's.  It is in
19245 ** the public domain.  The original comments are included here for
19246 ** completeness.  They are very out-of-date but might be useful as
19247 ** an historical reference.  Most of the "enhancements" have been backed
19248 ** out so that the functionality is now the same as standard printf().
19249 **
19250 **************************************************************************
19251 **
19252 ** This file contains code for a set of "printf"-like routines.  These
19253 ** routines format strings much like the printf() from the standard C
19254 ** library, though the implementation here has enhancements to support
19255 ** SQLlite.
19256 */
19257
19258 /*
19259 ** Conversion types fall into various categories as defined by the
19260 ** following enumeration.
19261 */
19262 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19263 #define etFLOAT       2 /* Floating point.  %f */
19264 #define etEXP         3 /* Exponentional notation. %e and %E */
19265 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19266 #define etSIZE        5 /* Return number of characters processed so far. %n */
19267 #define etSTRING      6 /* Strings. %s */
19268 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19269 #define etPERCENT     8 /* Percent symbol. %% */
19270 #define etCHARX       9 /* Characters. %c */
19271 /* The rest are extensions, not normally found in printf() */
19272 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19273 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19274                           NULL pointers replaced by SQL NULL.  %Q */
19275 #define etTOKEN      12 /* a pointer to a Token structure */
19276 #define etSRCLIST    13 /* a pointer to a SrcList */
19277 #define etPOINTER    14 /* The %p conversion */
19278 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19279 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19280
19281 #define etINVALID     0 /* Any unrecognized conversion type */
19282
19283
19284 /*
19285 ** An "etByte" is an 8-bit unsigned value.
19286 */
19287 typedef unsigned char etByte;
19288
19289 /*
19290 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19291 ** by an instance of the following structure
19292 */
19293 typedef struct et_info {   /* Information about each format field */
19294   char fmttype;            /* The format field code letter */
19295   etByte base;             /* The base for radix conversion */
19296   etByte flags;            /* One or more of FLAG_ constants below */
19297   etByte type;             /* Conversion paradigm */
19298   etByte charset;          /* Offset into aDigits[] of the digits string */
19299   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19300 } et_info;
19301
19302 /*
19303 ** Allowed values for et_info.flags
19304 */
19305 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19306 #define FLAG_INTERN  2     /* True if for internal use only */
19307 #define FLAG_STRING  4     /* Allow infinity precision */
19308
19309
19310 /*
19311 ** The following table is searched linearly, so it is good to put the
19312 ** most frequently used conversion types first.
19313 */
19314 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19315 static const char aPrefix[] = "-x0\000X0";
19316 static const et_info fmtinfo[] = {
19317   {  'd', 10, 1, etRADIX,      0,  0 },
19318   {  's',  0, 4, etSTRING,     0,  0 },
19319   {  'g',  0, 1, etGENERIC,    30, 0 },
19320   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19321   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19322   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19323   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19324   {  'c',  0, 0, etCHARX,      0,  0 },
19325   {  'o',  8, 0, etRADIX,      0,  2 },
19326   {  'u', 10, 0, etRADIX,      0,  0 },
19327   {  'x', 16, 0, etRADIX,      16, 1 },
19328   {  'X', 16, 0, etRADIX,      0,  4 },
19329 #ifndef SQLITE_OMIT_FLOATING_POINT
19330   {  'f',  0, 1, etFLOAT,      0,  0 },
19331   {  'e',  0, 1, etEXP,        30, 0 },
19332   {  'E',  0, 1, etEXP,        14, 0 },
19333   {  'G',  0, 1, etGENERIC,    14, 0 },
19334 #endif
19335   {  'i', 10, 1, etRADIX,      0,  0 },
19336   {  'n',  0, 0, etSIZE,       0,  0 },
19337   {  '%',  0, 0, etPERCENT,    0,  0 },
19338   {  'p', 16, 0, etPOINTER,    0,  1 },
19339
19340 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19341 ** use only */
19342   {  'T',  0, 2, etTOKEN,      0,  0 },
19343   {  'S',  0, 2, etSRCLIST,    0,  0 },
19344   {  'r', 10, 3, etORDINAL,    0,  0 },
19345 };
19346
19347 /*
19348 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19349 ** conversions will work.
19350 */
19351 #ifndef SQLITE_OMIT_FLOATING_POINT
19352 /*
19353 ** "*val" is a double such that 0.1 <= *val < 10.0
19354 ** Return the ascii code for the leading digit of *val, then
19355 ** multiply "*val" by 10.0 to renormalize.
19356 **
19357 ** Example:
19358 **     input:     *val = 3.14159
19359 **     output:    *val = 1.4159    function return = '3'
19360 **
19361 ** The counter *cnt is incremented each time.  After counter exceeds
19362 ** 16 (the number of significant digits in a 64-bit float) '0' is
19363 ** always returned.
19364 */
19365 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19366   int digit;
19367   LONGDOUBLE_TYPE d;
19368   if( (*cnt)<=0 ) return '0';
19369   (*cnt)--;
19370   digit = (int)*val;
19371   d = digit;
19372   digit += '0';
19373   *val = (*val - d)*10.0;
19374   return (char)digit;
19375 }
19376 #endif /* SQLITE_OMIT_FLOATING_POINT */
19377
19378 /*
19379 ** Append N space characters to the given string buffer.
19380 */
19381 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19382   static const char zSpaces[] = "                             ";
19383   while( N>=(int)sizeof(zSpaces)-1 ){
19384     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19385     N -= sizeof(zSpaces)-1;
19386   }
19387   if( N>0 ){
19388     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19389   }
19390 }
19391
19392 /*
19393 ** On machines with a small stack size, you can redefine the
19394 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19395 */
19396 #ifndef SQLITE_PRINT_BUF_SIZE
19397 # define SQLITE_PRINT_BUF_SIZE 70
19398 #endif
19399 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19400
19401 /*
19402 ** Render a string given by "fmt" into the StrAccum object.
19403 */
19404 SQLITE_PRIVATE void sqlite3VXPrintf(
19405   StrAccum *pAccum,                  /* Accumulate results here */
19406   int useExtended,                   /* Allow extended %-conversions */
19407   const char *fmt,                   /* Format string */
19408   va_list ap                         /* arguments */
19409 ){
19410   int c;                     /* Next character in the format string */
19411   char *bufpt;               /* Pointer to the conversion buffer */
19412   int precision;             /* Precision of the current field */
19413   int length;                /* Length of the field */
19414   int idx;                   /* A general purpose loop counter */
19415   int width;                 /* Width of the current field */
19416   etByte flag_leftjustify;   /* True if "-" flag is present */
19417   etByte flag_plussign;      /* True if "+" flag is present */
19418   etByte flag_blanksign;     /* True if " " flag is present */
19419   etByte flag_alternateform; /* True if "#" flag is present */
19420   etByte flag_altform2;      /* True if "!" flag is present */
19421   etByte flag_zeropad;       /* True if field width constant starts with zero */
19422   etByte flag_long;          /* True if "l" flag is present */
19423   etByte flag_longlong;      /* True if the "ll" flag is present */
19424   etByte done;               /* Loop termination flag */
19425   etByte xtype = 0;          /* Conversion paradigm */
19426   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19427   sqlite_uint64 longvalue;   /* Value for integer types */
19428   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19429   const et_info *infop;      /* Pointer to the appropriate info structure */
19430   char *zOut;                /* Rendering buffer */
19431   int nOut;                  /* Size of the rendering buffer */
19432   char *zExtra;              /* Malloced memory used by some conversion */
19433 #ifndef SQLITE_OMIT_FLOATING_POINT
19434   int  exp, e2;              /* exponent of real numbers */
19435   int nsd;                   /* Number of significant digits returned */
19436   double rounder;            /* Used for rounding floating point values */
19437   etByte flag_dp;            /* True if decimal point should be shown */
19438   etByte flag_rtz;           /* True if trailing zeros should be removed */
19439 #endif
19440   char buf[etBUFSIZE];       /* Conversion buffer */
19441
19442   bufpt = 0;
19443   for(; (c=(*fmt))!=0; ++fmt){
19444     if( c!='%' ){
19445       int amt;
19446       bufpt = (char *)fmt;
19447       amt = 1;
19448       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19449       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19450       if( c==0 ) break;
19451     }
19452     if( (c=(*++fmt))==0 ){
19453       sqlite3StrAccumAppend(pAccum, "%", 1);
19454       break;
19455     }
19456     /* Find out what flags are present */
19457     flag_leftjustify = flag_plussign = flag_blanksign = 
19458      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19459     done = 0;
19460     do{
19461       switch( c ){
19462         case '-':   flag_leftjustify = 1;     break;
19463         case '+':   flag_plussign = 1;        break;
19464         case ' ':   flag_blanksign = 1;       break;
19465         case '#':   flag_alternateform = 1;   break;
19466         case '!':   flag_altform2 = 1;        break;
19467         case '0':   flag_zeropad = 1;         break;
19468         default:    done = 1;                 break;
19469       }
19470     }while( !done && (c=(*++fmt))!=0 );
19471     /* Get the field width */
19472     width = 0;
19473     if( c=='*' ){
19474       width = va_arg(ap,int);
19475       if( width<0 ){
19476         flag_leftjustify = 1;
19477         width = -width;
19478       }
19479       c = *++fmt;
19480     }else{
19481       while( c>='0' && c<='9' ){
19482         width = width*10 + c - '0';
19483         c = *++fmt;
19484       }
19485     }
19486     /* Get the precision */
19487     if( c=='.' ){
19488       precision = 0;
19489       c = *++fmt;
19490       if( c=='*' ){
19491         precision = va_arg(ap,int);
19492         if( precision<0 ) precision = -precision;
19493         c = *++fmt;
19494       }else{
19495         while( c>='0' && c<='9' ){
19496           precision = precision*10 + c - '0';
19497           c = *++fmt;
19498         }
19499       }
19500     }else{
19501       precision = -1;
19502     }
19503     /* Get the conversion type modifier */
19504     if( c=='l' ){
19505       flag_long = 1;
19506       c = *++fmt;
19507       if( c=='l' ){
19508         flag_longlong = 1;
19509         c = *++fmt;
19510       }else{
19511         flag_longlong = 0;
19512       }
19513     }else{
19514       flag_long = flag_longlong = 0;
19515     }
19516     /* Fetch the info entry for the field */
19517     infop = &fmtinfo[0];
19518     xtype = etINVALID;
19519     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19520       if( c==fmtinfo[idx].fmttype ){
19521         infop = &fmtinfo[idx];
19522         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19523           xtype = infop->type;
19524         }else{
19525           return;
19526         }
19527         break;
19528       }
19529     }
19530     zExtra = 0;
19531
19532     /*
19533     ** At this point, variables are initialized as follows:
19534     **
19535     **   flag_alternateform          TRUE if a '#' is present.
19536     **   flag_altform2               TRUE if a '!' is present.
19537     **   flag_plussign               TRUE if a '+' is present.
19538     **   flag_leftjustify            TRUE if a '-' is present or if the
19539     **                               field width was negative.
19540     **   flag_zeropad                TRUE if the width began with 0.
19541     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19542     **                               the conversion character.
19543     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19544     **                               the conversion character.
19545     **   flag_blanksign              TRUE if a ' ' is present.
19546     **   width                       The specified field width.  This is
19547     **                               always non-negative.  Zero is the default.
19548     **   precision                   The specified precision.  The default
19549     **                               is -1.
19550     **   xtype                       The class of the conversion.
19551     **   infop                       Pointer to the appropriate info struct.
19552     */
19553     switch( xtype ){
19554       case etPOINTER:
19555         flag_longlong = sizeof(char*)==sizeof(i64);
19556         flag_long = sizeof(char*)==sizeof(long int);
19557         /* Fall through into the next case */
19558       case etORDINAL:
19559       case etRADIX:
19560         if( infop->flags & FLAG_SIGNED ){
19561           i64 v;
19562           if( flag_longlong ){
19563             v = va_arg(ap,i64);
19564           }else if( flag_long ){
19565             v = va_arg(ap,long int);
19566           }else{
19567             v = va_arg(ap,int);
19568           }
19569           if( v<0 ){
19570             if( v==SMALLEST_INT64 ){
19571               longvalue = ((u64)1)<<63;
19572             }else{
19573               longvalue = -v;
19574             }
19575             prefix = '-';
19576           }else{
19577             longvalue = v;
19578             if( flag_plussign )        prefix = '+';
19579             else if( flag_blanksign )  prefix = ' ';
19580             else                       prefix = 0;
19581           }
19582         }else{
19583           if( flag_longlong ){
19584             longvalue = va_arg(ap,u64);
19585           }else if( flag_long ){
19586             longvalue = va_arg(ap,unsigned long int);
19587           }else{
19588             longvalue = va_arg(ap,unsigned int);
19589           }
19590           prefix = 0;
19591         }
19592         if( longvalue==0 ) flag_alternateform = 0;
19593         if( flag_zeropad && precision<width-(prefix!=0) ){
19594           precision = width-(prefix!=0);
19595         }
19596         if( precision<etBUFSIZE-10 ){
19597           nOut = etBUFSIZE;
19598           zOut = buf;
19599         }else{
19600           nOut = precision + 10;
19601           zOut = zExtra = sqlite3Malloc( nOut );
19602           if( zOut==0 ){
19603             pAccum->mallocFailed = 1;
19604             return;
19605           }
19606         }
19607         bufpt = &zOut[nOut-1];
19608         if( xtype==etORDINAL ){
19609           static const char zOrd[] = "thstndrd";
19610           int x = (int)(longvalue % 10);
19611           if( x>=4 || (longvalue/10)%10==1 ){
19612             x = 0;
19613           }
19614           *(--bufpt) = zOrd[x*2+1];
19615           *(--bufpt) = zOrd[x*2];
19616         }
19617         {
19618           register const char *cset;      /* Use registers for speed */
19619           register int base;
19620           cset = &aDigits[infop->charset];
19621           base = infop->base;
19622           do{                                           /* Convert to ascii */
19623             *(--bufpt) = cset[longvalue%base];
19624             longvalue = longvalue/base;
19625           }while( longvalue>0 );
19626         }
19627         length = (int)(&zOut[nOut-1]-bufpt);
19628         for(idx=precision-length; idx>0; idx--){
19629           *(--bufpt) = '0';                             /* Zero pad */
19630         }
19631         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19632         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19633           const char *pre;
19634           char x;
19635           pre = &aPrefix[infop->prefix];
19636           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19637         }
19638         length = (int)(&zOut[nOut-1]-bufpt);
19639         break;
19640       case etFLOAT:
19641       case etEXP:
19642       case etGENERIC:
19643         realvalue = va_arg(ap,double);
19644 #ifdef SQLITE_OMIT_FLOATING_POINT
19645         length = 0;
19646 #else
19647         if( precision<0 ) precision = 6;         /* Set default precision */
19648         if( realvalue<0.0 ){
19649           realvalue = -realvalue;
19650           prefix = '-';
19651         }else{
19652           if( flag_plussign )          prefix = '+';
19653           else if( flag_blanksign )    prefix = ' ';
19654           else                         prefix = 0;
19655         }
19656         if( xtype==etGENERIC && precision>0 ) precision--;
19657 #if 0
19658         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19659         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19660 #else
19661         /* It makes more sense to use 0.5 */
19662         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19663 #endif
19664         if( xtype==etFLOAT ) realvalue += rounder;
19665         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19666         exp = 0;
19667         if( sqlite3IsNaN((double)realvalue) ){
19668           bufpt = "NaN";
19669           length = 3;
19670           break;
19671         }
19672         if( realvalue>0.0 ){
19673           LONGDOUBLE_TYPE scale = 1.0;
19674           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19675           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19676           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19677           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19678           realvalue /= scale;
19679           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19680           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19681           if( exp>350 ){
19682             if( prefix=='-' ){
19683               bufpt = "-Inf";
19684             }else if( prefix=='+' ){
19685               bufpt = "+Inf";
19686             }else{
19687               bufpt = "Inf";
19688             }
19689             length = sqlite3Strlen30(bufpt);
19690             break;
19691           }
19692         }
19693         bufpt = buf;
19694         /*
19695         ** If the field type is etGENERIC, then convert to either etEXP
19696         ** or etFLOAT, as appropriate.
19697         */
19698         if( xtype!=etFLOAT ){
19699           realvalue += rounder;
19700           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19701         }
19702         if( xtype==etGENERIC ){
19703           flag_rtz = !flag_alternateform;
19704           if( exp<-4 || exp>precision ){
19705             xtype = etEXP;
19706           }else{
19707             precision = precision - exp;
19708             xtype = etFLOAT;
19709           }
19710         }else{
19711           flag_rtz = flag_altform2;
19712         }
19713         if( xtype==etEXP ){
19714           e2 = 0;
19715         }else{
19716           e2 = exp;
19717         }
19718         if( e2+precision+width > etBUFSIZE - 15 ){
19719           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19720           if( bufpt==0 ){
19721             pAccum->mallocFailed = 1;
19722             return;
19723           }
19724         }
19725         zOut = bufpt;
19726         nsd = 16 + flag_altform2*10;
19727         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19728         /* The sign in front of the number */
19729         if( prefix ){
19730           *(bufpt++) = prefix;
19731         }
19732         /* Digits prior to the decimal point */
19733         if( e2<0 ){
19734           *(bufpt++) = '0';
19735         }else{
19736           for(; e2>=0; e2--){
19737             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19738           }
19739         }
19740         /* The decimal point */
19741         if( flag_dp ){
19742           *(bufpt++) = '.';
19743         }
19744         /* "0" digits after the decimal point but before the first
19745         ** significant digit of the number */
19746         for(e2++; e2<0; precision--, e2++){
19747           assert( precision>0 );
19748           *(bufpt++) = '0';
19749         }
19750         /* Significant digits after the decimal point */
19751         while( (precision--)>0 ){
19752           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19753         }
19754         /* Remove trailing zeros and the "." if no digits follow the "." */
19755         if( flag_rtz && flag_dp ){
19756           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19757           assert( bufpt>zOut );
19758           if( bufpt[-1]=='.' ){
19759             if( flag_altform2 ){
19760               *(bufpt++) = '0';
19761             }else{
19762               *(--bufpt) = 0;
19763             }
19764           }
19765         }
19766         /* Add the "eNNN" suffix */
19767         if( xtype==etEXP ){
19768           *(bufpt++) = aDigits[infop->charset];
19769           if( exp<0 ){
19770             *(bufpt++) = '-'; exp = -exp;
19771           }else{
19772             *(bufpt++) = '+';
19773           }
19774           if( exp>=100 ){
19775             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19776             exp %= 100;
19777           }
19778           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19779           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19780         }
19781         *bufpt = 0;
19782
19783         /* The converted number is in buf[] and zero terminated. Output it.
19784         ** Note that the number is in the usual order, not reversed as with
19785         ** integer conversions. */
19786         length = (int)(bufpt-zOut);
19787         bufpt = zOut;
19788
19789         /* Special case:  Add leading zeros if the flag_zeropad flag is
19790         ** set and we are not left justified */
19791         if( flag_zeropad && !flag_leftjustify && length < width){
19792           int i;
19793           int nPad = width - length;
19794           for(i=width; i>=nPad; i--){
19795             bufpt[i] = bufpt[i-nPad];
19796           }
19797           i = prefix!=0;
19798           while( nPad-- ) bufpt[i++] = '0';
19799           length = width;
19800         }
19801 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19802         break;
19803       case etSIZE:
19804         *(va_arg(ap,int*)) = pAccum->nChar;
19805         length = width = 0;
19806         break;
19807       case etPERCENT:
19808         buf[0] = '%';
19809         bufpt = buf;
19810         length = 1;
19811         break;
19812       case etCHARX:
19813         c = va_arg(ap,int);
19814         buf[0] = (char)c;
19815         if( precision>=0 ){
19816           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19817           length = precision;
19818         }else{
19819           length =1;
19820         }
19821         bufpt = buf;
19822         break;
19823       case etSTRING:
19824       case etDYNSTRING:
19825         bufpt = va_arg(ap,char*);
19826         if( bufpt==0 ){
19827           bufpt = "";
19828         }else if( xtype==etDYNSTRING ){
19829           zExtra = bufpt;
19830         }
19831         if( precision>=0 ){
19832           for(length=0; length<precision && bufpt[length]; length++){}
19833         }else{
19834           length = sqlite3Strlen30(bufpt);
19835         }
19836         break;
19837       case etSQLESCAPE:
19838       case etSQLESCAPE2:
19839       case etSQLESCAPE3: {
19840         int i, j, k, n, isnull;
19841         int needQuote;
19842         char ch;
19843         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19844         char *escarg = va_arg(ap,char*);
19845         isnull = escarg==0;
19846         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19847         k = precision;
19848         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19849           if( ch==q )  n++;
19850         }
19851         needQuote = !isnull && xtype==etSQLESCAPE2;
19852         n += i + 1 + needQuote*2;
19853         if( n>etBUFSIZE ){
19854           bufpt = zExtra = sqlite3Malloc( n );
19855           if( bufpt==0 ){
19856             pAccum->mallocFailed = 1;
19857             return;
19858           }
19859         }else{
19860           bufpt = buf;
19861         }
19862         j = 0;
19863         if( needQuote ) bufpt[j++] = q;
19864         k = i;
19865         for(i=0; i<k; i++){
19866           bufpt[j++] = ch = escarg[i];
19867           if( ch==q ) bufpt[j++] = ch;
19868         }
19869         if( needQuote ) bufpt[j++] = q;
19870         bufpt[j] = 0;
19871         length = j;
19872         /* The precision in %q and %Q means how many input characters to
19873         ** consume, not the length of the output...
19874         ** if( precision>=0 && precision<length ) length = precision; */
19875         break;
19876       }
19877       case etTOKEN: {
19878         Token *pToken = va_arg(ap, Token*);
19879         if( pToken ){
19880           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19881         }
19882         length = width = 0;
19883         break;
19884       }
19885       case etSRCLIST: {
19886         SrcList *pSrc = va_arg(ap, SrcList*);
19887         int k = va_arg(ap, int);
19888         struct SrcList_item *pItem = &pSrc->a[k];
19889         assert( k>=0 && k<pSrc->nSrc );
19890         if( pItem->zDatabase ){
19891           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19892           sqlite3StrAccumAppend(pAccum, ".", 1);
19893         }
19894         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19895         length = width = 0;
19896         break;
19897       }
19898       default: {
19899         assert( xtype==etINVALID );
19900         return;
19901       }
19902     }/* End switch over the format type */
19903     /*
19904     ** The text of the conversion is pointed to by "bufpt" and is
19905     ** "length" characters long.  The field width is "width".  Do
19906     ** the output.
19907     */
19908     if( !flag_leftjustify ){
19909       register int nspace;
19910       nspace = width-length;
19911       if( nspace>0 ){
19912         sqlite3AppendSpace(pAccum, nspace);
19913       }
19914     }
19915     if( length>0 ){
19916       sqlite3StrAccumAppend(pAccum, bufpt, length);
19917     }
19918     if( flag_leftjustify ){
19919       register int nspace;
19920       nspace = width-length;
19921       if( nspace>0 ){
19922         sqlite3AppendSpace(pAccum, nspace);
19923       }
19924     }
19925     sqlite3_free(zExtra);
19926   }/* End for loop over the format string */
19927 } /* End of function */
19928
19929 /*
19930 ** Append N bytes of text from z to the StrAccum object.
19931 */
19932 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19933   assert( z!=0 || N==0 );
19934   if( p->tooBig | p->mallocFailed ){
19935     testcase(p->tooBig);
19936     testcase(p->mallocFailed);
19937     return;
19938   }
19939   assert( p->zText!=0 || p->nChar==0 );
19940   if( N<0 ){
19941     N = sqlite3Strlen30(z);
19942   }
19943   if( N==0 || NEVER(z==0) ){
19944     return;
19945   }
19946   if( p->nChar+N >= p->nAlloc ){
19947     char *zNew;
19948     if( !p->useMalloc ){
19949       p->tooBig = 1;
19950       N = p->nAlloc - p->nChar - 1;
19951       if( N<=0 ){
19952         return;
19953       }
19954     }else{
19955       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19956       i64 szNew = p->nChar;
19957       szNew += N + 1;
19958       if( szNew > p->mxAlloc ){
19959         sqlite3StrAccumReset(p);
19960         p->tooBig = 1;
19961         return;
19962       }else{
19963         p->nAlloc = (int)szNew;
19964       }
19965       if( p->useMalloc==1 ){
19966         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19967       }else{
19968         zNew = sqlite3_realloc(zOld, p->nAlloc);
19969       }
19970       if( zNew ){
19971         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
19972         p->zText = zNew;
19973       }else{
19974         p->mallocFailed = 1;
19975         sqlite3StrAccumReset(p);
19976         return;
19977       }
19978     }
19979   }
19980   assert( p->zText );
19981   memcpy(&p->zText[p->nChar], z, N);
19982   p->nChar += N;
19983 }
19984
19985 /*
19986 ** Finish off a string by making sure it is zero-terminated.
19987 ** Return a pointer to the resulting string.  Return a NULL
19988 ** pointer if any kind of error was encountered.
19989 */
19990 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19991   if( p->zText ){
19992     p->zText[p->nChar] = 0;
19993     if( p->useMalloc && p->zText==p->zBase ){
19994       if( p->useMalloc==1 ){
19995         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19996       }else{
19997         p->zText = sqlite3_malloc(p->nChar+1);
19998       }
19999       if( p->zText ){
20000         memcpy(p->zText, p->zBase, p->nChar+1);
20001       }else{
20002         p->mallocFailed = 1;
20003       }
20004     }
20005   }
20006   return p->zText;
20007 }
20008
20009 /*
20010 ** Reset an StrAccum string.  Reclaim all malloced memory.
20011 */
20012 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20013   if( p->zText!=p->zBase ){
20014     if( p->useMalloc==1 ){
20015       sqlite3DbFree(p->db, p->zText);
20016     }else{
20017       sqlite3_free(p->zText);
20018     }
20019   }
20020   p->zText = 0;
20021 }
20022
20023 /*
20024 ** Initialize a string accumulator
20025 */
20026 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20027   p->zText = p->zBase = zBase;
20028   p->db = 0;
20029   p->nChar = 0;
20030   p->nAlloc = n;
20031   p->mxAlloc = mx;
20032   p->useMalloc = 1;
20033   p->tooBig = 0;
20034   p->mallocFailed = 0;
20035 }
20036
20037 /*
20038 ** Print into memory obtained from sqliteMalloc().  Use the internal
20039 ** %-conversion extensions.
20040 */
20041 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20042   char *z;
20043   char zBase[SQLITE_PRINT_BUF_SIZE];
20044   StrAccum acc;
20045   assert( db!=0 );
20046   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20047                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20048   acc.db = db;
20049   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20050   z = sqlite3StrAccumFinish(&acc);
20051   if( acc.mallocFailed ){
20052     db->mallocFailed = 1;
20053   }
20054   return z;
20055 }
20056
20057 /*
20058 ** Print into memory obtained from sqliteMalloc().  Use the internal
20059 ** %-conversion extensions.
20060 */
20061 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20062   va_list ap;
20063   char *z;
20064   va_start(ap, zFormat);
20065   z = sqlite3VMPrintf(db, zFormat, ap);
20066   va_end(ap);
20067   return z;
20068 }
20069
20070 /*
20071 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20072 ** the string and before returnning.  This routine is intended to be used
20073 ** to modify an existing string.  For example:
20074 **
20075 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20076 **
20077 */
20078 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20079   va_list ap;
20080   char *z;
20081   va_start(ap, zFormat);
20082   z = sqlite3VMPrintf(db, zFormat, ap);
20083   va_end(ap);
20084   sqlite3DbFree(db, zStr);
20085   return z;
20086 }
20087
20088 /*
20089 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20090 ** %-conversion extensions.
20091 */
20092 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20093   char *z;
20094   char zBase[SQLITE_PRINT_BUF_SIZE];
20095   StrAccum acc;
20096 #ifndef SQLITE_OMIT_AUTOINIT
20097   if( sqlite3_initialize() ) return 0;
20098 #endif
20099   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20100   acc.useMalloc = 2;
20101   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20102   z = sqlite3StrAccumFinish(&acc);
20103   return z;
20104 }
20105
20106 /*
20107 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20108 ** %-conversion extensions.
20109 */
20110 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20111   va_list ap;
20112   char *z;
20113 #ifndef SQLITE_OMIT_AUTOINIT
20114   if( sqlite3_initialize() ) return 0;
20115 #endif
20116   va_start(ap, zFormat);
20117   z = sqlite3_vmprintf(zFormat, ap);
20118   va_end(ap);
20119   return z;
20120 }
20121
20122 /*
20123 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20124 ** current locale settings.  This is important for SQLite because we
20125 ** are not able to use a "," as the decimal point in place of "." as
20126 ** specified by some locales.
20127 **
20128 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20129 ** from the snprintf() standard.  Unfortunately, it is too late to change
20130 ** this without breaking compatibility, so we just have to live with the
20131 ** mistake.
20132 **
20133 ** sqlite3_vsnprintf() is the varargs version.
20134 */
20135 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20136   StrAccum acc;
20137   if( n<=0 ) return zBuf;
20138   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20139   acc.useMalloc = 0;
20140   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20141   return sqlite3StrAccumFinish(&acc);
20142 }
20143 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20144   char *z;
20145   va_list ap;
20146   va_start(ap,zFormat);
20147   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20148   va_end(ap);
20149   return z;
20150 }
20151
20152 /*
20153 ** This is the routine that actually formats the sqlite3_log() message.
20154 ** We house it in a separate routine from sqlite3_log() to avoid using
20155 ** stack space on small-stack systems when logging is disabled.
20156 **
20157 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20158 ** allocate memory because it might be called while the memory allocator
20159 ** mutex is held.
20160 */
20161 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20162   StrAccum acc;                          /* String accumulator */
20163   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20164
20165   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20166   acc.useMalloc = 0;
20167   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20168   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20169                            sqlite3StrAccumFinish(&acc));
20170 }
20171
20172 /*
20173 ** Format and write a message to the log if logging is enabled.
20174 */
20175 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20176   va_list ap;                             /* Vararg list */
20177   if( sqlite3GlobalConfig.xLog ){
20178     va_start(ap, zFormat);
20179     renderLogMsg(iErrCode, zFormat, ap);
20180     va_end(ap);
20181   }
20182 }
20183
20184 #if defined(SQLITE_DEBUG)
20185 /*
20186 ** A version of printf() that understands %lld.  Used for debugging.
20187 ** The printf() built into some versions of windows does not understand %lld
20188 ** and segfaults if you give it a long long int.
20189 */
20190 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20191   va_list ap;
20192   StrAccum acc;
20193   char zBuf[500];
20194   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20195   acc.useMalloc = 0;
20196   va_start(ap,zFormat);
20197   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20198   va_end(ap);
20199   sqlite3StrAccumFinish(&acc);
20200   fprintf(stdout,"%s", zBuf);
20201   fflush(stdout);
20202 }
20203 #endif
20204
20205 #ifndef SQLITE_OMIT_TRACE
20206 /*
20207 ** variable-argument wrapper around sqlite3VXPrintf().
20208 */
20209 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20210   va_list ap;
20211   va_start(ap,zFormat);
20212   sqlite3VXPrintf(p, 1, zFormat, ap);
20213   va_end(ap);
20214 }
20215 #endif
20216
20217 /************** End of printf.c **********************************************/
20218 /************** Begin file random.c ******************************************/
20219 /*
20220 ** 2001 September 15
20221 **
20222 ** The author disclaims copyright to this source code.  In place of
20223 ** a legal notice, here is a blessing:
20224 **
20225 **    May you do good and not evil.
20226 **    May you find forgiveness for yourself and forgive others.
20227 **    May you share freely, never taking more than you give.
20228 **
20229 *************************************************************************
20230 ** This file contains code to implement a pseudo-random number
20231 ** generator (PRNG) for SQLite.
20232 **
20233 ** Random numbers are used by some of the database backends in order
20234 ** to generate random integer keys for tables or random filenames.
20235 */
20236
20237
20238 /* All threads share a single random number generator.
20239 ** This structure is the current state of the generator.
20240 */
20241 static SQLITE_WSD struct sqlite3PrngType {
20242   unsigned char isInit;          /* True if initialized */
20243   unsigned char i, j;            /* State variables */
20244   unsigned char s[256];          /* State variables */
20245 } sqlite3Prng;
20246
20247 /*
20248 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20249 ** must be held while executing this routine.
20250 **
20251 ** Why not just use a library random generator like lrand48() for this?
20252 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20253 ** good source of random numbers.  The lrand48() library function may
20254 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20255 ** subtle problems on some systems that could cause problems.  It is hard
20256 ** to know.  To minimize the risk of problems due to bad lrand48()
20257 ** implementations, SQLite uses this random number generator based
20258 ** on RC4, which we know works very well.
20259 **
20260 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20261 ** randomness any more.  But we will leave this code in all the same.
20262 */
20263 static u8 randomByte(void){
20264   unsigned char t;
20265
20266
20267   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20268   ** state vector.  If writable static data is unsupported on the target,
20269   ** we have to locate the state vector at run-time.  In the more common
20270   ** case where writable static data is supported, wsdPrng can refer directly
20271   ** to the "sqlite3Prng" state vector declared above.
20272   */
20273 #ifdef SQLITE_OMIT_WSD
20274   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20275 # define wsdPrng p[0]
20276 #else
20277 # define wsdPrng sqlite3Prng
20278 #endif
20279
20280
20281   /* Initialize the state of the random number generator once,
20282   ** the first time this routine is called.  The seed value does
20283   ** not need to contain a lot of randomness since we are not
20284   ** trying to do secure encryption or anything like that...
20285   **
20286   ** Nothing in this file or anywhere else in SQLite does any kind of
20287   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20288   ** number generator) not as an encryption device.
20289   */
20290   if( !wsdPrng.isInit ){
20291     int i;
20292     char k[256];
20293     wsdPrng.j = 0;
20294     wsdPrng.i = 0;
20295     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20296     for(i=0; i<256; i++){
20297       wsdPrng.s[i] = (u8)i;
20298     }
20299     for(i=0; i<256; i++){
20300       wsdPrng.j += wsdPrng.s[i] + k[i];
20301       t = wsdPrng.s[wsdPrng.j];
20302       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20303       wsdPrng.s[i] = t;
20304     }
20305     wsdPrng.isInit = 1;
20306   }
20307
20308   /* Generate and return single random byte
20309   */
20310   wsdPrng.i++;
20311   t = wsdPrng.s[wsdPrng.i];
20312   wsdPrng.j += t;
20313   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20314   wsdPrng.s[wsdPrng.j] = t;
20315   t += wsdPrng.s[wsdPrng.i];
20316   return wsdPrng.s[t];
20317 }
20318
20319 /*
20320 ** Return N random bytes.
20321 */
20322 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20323   unsigned char *zBuf = pBuf;
20324 #if SQLITE_THREADSAFE
20325   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20326 #endif
20327   sqlite3_mutex_enter(mutex);
20328   while( N-- ){
20329     *(zBuf++) = randomByte();
20330   }
20331   sqlite3_mutex_leave(mutex);
20332 }
20333
20334 #ifndef SQLITE_OMIT_BUILTIN_TEST
20335 /*
20336 ** For testing purposes, we sometimes want to preserve the state of
20337 ** PRNG and restore the PRNG to its saved state at a later time, or
20338 ** to reset the PRNG to its initial state.  These routines accomplish
20339 ** those tasks.
20340 **
20341 ** The sqlite3_test_control() interface calls these routines to
20342 ** control the PRNG.
20343 */
20344 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20345 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20346   memcpy(
20347     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20348     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20349     sizeof(sqlite3Prng)
20350   );
20351 }
20352 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20353   memcpy(
20354     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20355     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20356     sizeof(sqlite3Prng)
20357   );
20358 }
20359 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20360   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20361 }
20362 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20363
20364 /************** End of random.c **********************************************/
20365 /************** Begin file utf.c *********************************************/
20366 /*
20367 ** 2004 April 13
20368 **
20369 ** The author disclaims copyright to this source code.  In place of
20370 ** a legal notice, here is a blessing:
20371 **
20372 **    May you do good and not evil.
20373 **    May you find forgiveness for yourself and forgive others.
20374 **    May you share freely, never taking more than you give.
20375 **
20376 *************************************************************************
20377 ** This file contains routines used to translate between UTF-8, 
20378 ** UTF-16, UTF-16BE, and UTF-16LE.
20379 **
20380 ** Notes on UTF-8:
20381 **
20382 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20383 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20384 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20385 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20386 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20387 **
20388 **
20389 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20390 **
20391 **      Word-0               Word-1          Value
20392 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20393 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20394 **
20395 **
20396 ** BOM or Byte Order Mark:
20397 **     0xff 0xfe   little-endian utf-16 follows
20398 **     0xfe 0xff   big-endian utf-16 follows
20399 **
20400 */
20401 /* #include <assert.h> */
20402
20403 #ifndef SQLITE_AMALGAMATION
20404 /*
20405 ** The following constant value is used by the SQLITE_BIGENDIAN and
20406 ** SQLITE_LITTLEENDIAN macros.
20407 */
20408 SQLITE_PRIVATE const int sqlite3one = 1;
20409 #endif /* SQLITE_AMALGAMATION */
20410
20411 /*
20412 ** This lookup table is used to help decode the first byte of
20413 ** a multi-byte UTF8 character.
20414 */
20415 static const unsigned char sqlite3Utf8Trans1[] = {
20416   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20417   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20418   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20419   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20420   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20421   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20422   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20423   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20424 };
20425
20426
20427 #define WRITE_UTF8(zOut, c) {                          \
20428   if( c<0x00080 ){                                     \
20429     *zOut++ = (u8)(c&0xFF);                            \
20430   }                                                    \
20431   else if( c<0x00800 ){                                \
20432     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20433     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20434   }                                                    \
20435   else if( c<0x10000 ){                                \
20436     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20437     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20438     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20439   }else{                                               \
20440     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20441     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20442     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20443     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20444   }                                                    \
20445 }
20446
20447 #define WRITE_UTF16LE(zOut, c) {                                    \
20448   if( c<=0xFFFF ){                                                  \
20449     *zOut++ = (u8)(c&0x00FF);                                       \
20450     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20451   }else{                                                            \
20452     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20453     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20454     *zOut++ = (u8)(c&0x00FF);                                       \
20455     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20456   }                                                                 \
20457 }
20458
20459 #define WRITE_UTF16BE(zOut, c) {                                    \
20460   if( c<=0xFFFF ){                                                  \
20461     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20462     *zOut++ = (u8)(c&0x00FF);                                       \
20463   }else{                                                            \
20464     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20465     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20466     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20467     *zOut++ = (u8)(c&0x00FF);                                       \
20468   }                                                                 \
20469 }
20470
20471 #define READ_UTF16LE(zIn, TERM, c){                                   \
20472   c = (*zIn++);                                                       \
20473   c += ((*zIn++)<<8);                                                 \
20474   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20475     int c2 = (*zIn++);                                                \
20476     c2 += ((*zIn++)<<8);                                              \
20477     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20478   }                                                                   \
20479 }
20480
20481 #define READ_UTF16BE(zIn, TERM, c){                                   \
20482   c = ((*zIn++)<<8);                                                  \
20483   c += (*zIn++);                                                      \
20484   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20485     int c2 = ((*zIn++)<<8);                                           \
20486     c2 += (*zIn++);                                                   \
20487     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20488   }                                                                   \
20489 }
20490
20491 /*
20492 ** Translate a single UTF-8 character.  Return the unicode value.
20493 **
20494 ** During translation, assume that the byte that zTerm points
20495 ** is a 0x00.
20496 **
20497 ** Write a pointer to the next unread byte back into *pzNext.
20498 **
20499 ** Notes On Invalid UTF-8:
20500 **
20501 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20502 **     be encoded as a multi-byte character.  Any multi-byte character that
20503 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20504 **
20505 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20506 **     If a multi-byte character attempts to encode a value between
20507 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20508 **
20509 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20510 **     byte of a character are interpreted as single-byte characters
20511 **     and rendered as themselves even though they are technically
20512 **     invalid characters.
20513 **
20514 **  *  This routine accepts an infinite number of different UTF8 encodings
20515 **     for unicode values 0x80 and greater.  It do not change over-length
20516 **     encodings to 0xfffd as some systems recommend.
20517 */
20518 #define READ_UTF8(zIn, zTerm, c)                           \
20519   c = *(zIn++);                                            \
20520   if( c>=0xc0 ){                                           \
20521     c = sqlite3Utf8Trans1[c-0xc0];                         \
20522     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20523       c = (c<<6) + (0x3f & *(zIn++));                      \
20524     }                                                      \
20525     if( c<0x80                                             \
20526         || (c&0xFFFFF800)==0xD800                          \
20527         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20528   }
20529 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20530   const unsigned char *zIn,       /* First byte of UTF-8 character */
20531   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20532 ){
20533   unsigned int c;
20534
20535   /* Same as READ_UTF8() above but without the zTerm parameter.
20536   ** For this routine, we assume the UTF8 string is always zero-terminated.
20537   */
20538   c = *(zIn++);
20539   if( c>=0xc0 ){
20540     c = sqlite3Utf8Trans1[c-0xc0];
20541     while( (*zIn & 0xc0)==0x80 ){
20542       c = (c<<6) + (0x3f & *(zIn++));
20543     }
20544     if( c<0x80
20545         || (c&0xFFFFF800)==0xD800
20546         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20547   }
20548   *pzNext = zIn;
20549   return c;
20550 }
20551
20552
20553
20554
20555 /*
20556 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20557 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20558 */ 
20559 /* #define TRANSLATE_TRACE 1 */
20560
20561 #ifndef SQLITE_OMIT_UTF16
20562 /*
20563 ** This routine transforms the internal text encoding used by pMem to
20564 ** desiredEnc. It is an error if the string is already of the desired
20565 ** encoding, or if *pMem does not contain a string value.
20566 */
20567 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20568   int len;                    /* Maximum length of output string in bytes */
20569   unsigned char *zOut;                  /* Output buffer */
20570   unsigned char *zIn;                   /* Input iterator */
20571   unsigned char *zTerm;                 /* End of input */
20572   unsigned char *z;                     /* Output iterator */
20573   unsigned int c;
20574
20575   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20576   assert( pMem->flags&MEM_Str );
20577   assert( pMem->enc!=desiredEnc );
20578   assert( pMem->enc!=0 );
20579   assert( pMem->n>=0 );
20580
20581 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20582   {
20583     char zBuf[100];
20584     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20585     fprintf(stderr, "INPUT:  %s\n", zBuf);
20586   }
20587 #endif
20588
20589   /* If the translation is between UTF-16 little and big endian, then 
20590   ** all that is required is to swap the byte order. This case is handled
20591   ** differently from the others.
20592   */
20593   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20594     u8 temp;
20595     int rc;
20596     rc = sqlite3VdbeMemMakeWriteable(pMem);
20597     if( rc!=SQLITE_OK ){
20598       assert( rc==SQLITE_NOMEM );
20599       return SQLITE_NOMEM;
20600     }
20601     zIn = (u8*)pMem->z;
20602     zTerm = &zIn[pMem->n&~1];
20603     while( zIn<zTerm ){
20604       temp = *zIn;
20605       *zIn = *(zIn+1);
20606       zIn++;
20607       *zIn++ = temp;
20608     }
20609     pMem->enc = desiredEnc;
20610     goto translate_out;
20611   }
20612
20613   /* Set len to the maximum number of bytes required in the output buffer. */
20614   if( desiredEnc==SQLITE_UTF8 ){
20615     /* When converting from UTF-16, the maximum growth results from
20616     ** translating a 2-byte character to a 4-byte UTF-8 character.
20617     ** A single byte is required for the output string
20618     ** nul-terminator.
20619     */
20620     pMem->n &= ~1;
20621     len = pMem->n * 2 + 1;
20622   }else{
20623     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20624     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20625     ** character. Two bytes are required in the output buffer for the
20626     ** nul-terminator.
20627     */
20628     len = pMem->n * 2 + 2;
20629   }
20630
20631   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20632   ** byte past the end.
20633   **
20634   ** Variable zOut is set to point at the output buffer, space obtained
20635   ** from sqlite3_malloc().
20636   */
20637   zIn = (u8*)pMem->z;
20638   zTerm = &zIn[pMem->n];
20639   zOut = sqlite3DbMallocRaw(pMem->db, len);
20640   if( !zOut ){
20641     return SQLITE_NOMEM;
20642   }
20643   z = zOut;
20644
20645   if( pMem->enc==SQLITE_UTF8 ){
20646     if( desiredEnc==SQLITE_UTF16LE ){
20647       /* UTF-8 -> UTF-16 Little-endian */
20648       while( zIn<zTerm ){
20649         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20650         READ_UTF8(zIn, zTerm, c);
20651         WRITE_UTF16LE(z, c);
20652       }
20653     }else{
20654       assert( desiredEnc==SQLITE_UTF16BE );
20655       /* UTF-8 -> UTF-16 Big-endian */
20656       while( zIn<zTerm ){
20657         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20658         READ_UTF8(zIn, zTerm, c);
20659         WRITE_UTF16BE(z, c);
20660       }
20661     }
20662     pMem->n = (int)(z - zOut);
20663     *z++ = 0;
20664   }else{
20665     assert( desiredEnc==SQLITE_UTF8 );
20666     if( pMem->enc==SQLITE_UTF16LE ){
20667       /* UTF-16 Little-endian -> UTF-8 */
20668       while( zIn<zTerm ){
20669         READ_UTF16LE(zIn, zIn<zTerm, c); 
20670         WRITE_UTF8(z, c);
20671       }
20672     }else{
20673       /* UTF-16 Big-endian -> UTF-8 */
20674       while( zIn<zTerm ){
20675         READ_UTF16BE(zIn, zIn<zTerm, c); 
20676         WRITE_UTF8(z, c);
20677       }
20678     }
20679     pMem->n = (int)(z - zOut);
20680   }
20681   *z = 0;
20682   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20683
20684   sqlite3VdbeMemRelease(pMem);
20685   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20686   pMem->enc = desiredEnc;
20687   pMem->flags |= (MEM_Term|MEM_Dyn);
20688   pMem->z = (char*)zOut;
20689   pMem->zMalloc = pMem->z;
20690
20691 translate_out:
20692 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20693   {
20694     char zBuf[100];
20695     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20696     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20697   }
20698 #endif
20699   return SQLITE_OK;
20700 }
20701
20702 /*
20703 ** This routine checks for a byte-order mark at the beginning of the 
20704 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20705 ** the encoding of the Mem adjusted. This routine does not do any
20706 ** byte-swapping, it just sets Mem.enc appropriately.
20707 **
20708 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20709 ** changed by this function.
20710 */
20711 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20712   int rc = SQLITE_OK;
20713   u8 bom = 0;
20714
20715   assert( pMem->n>=0 );
20716   if( pMem->n>1 ){
20717     u8 b1 = *(u8 *)pMem->z;
20718     u8 b2 = *(((u8 *)pMem->z) + 1);
20719     if( b1==0xFE && b2==0xFF ){
20720       bom = SQLITE_UTF16BE;
20721     }
20722     if( b1==0xFF && b2==0xFE ){
20723       bom = SQLITE_UTF16LE;
20724     }
20725   }
20726   
20727   if( bom ){
20728     rc = sqlite3VdbeMemMakeWriteable(pMem);
20729     if( rc==SQLITE_OK ){
20730       pMem->n -= 2;
20731       memmove(pMem->z, &pMem->z[2], pMem->n);
20732       pMem->z[pMem->n] = '\0';
20733       pMem->z[pMem->n+1] = '\0';
20734       pMem->flags |= MEM_Term;
20735       pMem->enc = bom;
20736     }
20737   }
20738   return rc;
20739 }
20740 #endif /* SQLITE_OMIT_UTF16 */
20741
20742 /*
20743 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20744 ** return the number of unicode characters in pZ up to (but not including)
20745 ** the first 0x00 byte. If nByte is not less than zero, return the
20746 ** number of unicode characters in the first nByte of pZ (or up to 
20747 ** the first 0x00, whichever comes first).
20748 */
20749 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20750   int r = 0;
20751   const u8 *z = (const u8*)zIn;
20752   const u8 *zTerm;
20753   if( nByte>=0 ){
20754     zTerm = &z[nByte];
20755   }else{
20756     zTerm = (const u8*)(-1);
20757   }
20758   assert( z<=zTerm );
20759   while( *z!=0 && z<zTerm ){
20760     SQLITE_SKIP_UTF8(z);
20761     r++;
20762   }
20763   return r;
20764 }
20765
20766 /* This test function is not currently used by the automated test-suite. 
20767 ** Hence it is only available in debug builds.
20768 */
20769 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20770 /*
20771 ** Translate UTF-8 to UTF-8.
20772 **
20773 ** This has the effect of making sure that the string is well-formed
20774 ** UTF-8.  Miscoded characters are removed.
20775 **
20776 ** The translation is done in-place and aborted if the output
20777 ** overruns the input.
20778 */
20779 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20780   unsigned char *zOut = zIn;
20781   unsigned char *zStart = zIn;
20782   u32 c;
20783
20784   while( zIn[0] && zOut<=zIn ){
20785     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20786     if( c!=0xfffd ){
20787       WRITE_UTF8(zOut, c);
20788     }
20789   }
20790   *zOut = 0;
20791   return (int)(zOut - zStart);
20792 }
20793 #endif
20794
20795 #ifndef SQLITE_OMIT_UTF16
20796 /*
20797 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20798 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20799 ** be freed by the calling function.
20800 **
20801 ** NULL is returned if there is an allocation error.
20802 */
20803 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20804   Mem m;
20805   memset(&m, 0, sizeof(m));
20806   m.db = db;
20807   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20808   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20809   if( db->mallocFailed ){
20810     sqlite3VdbeMemRelease(&m);
20811     m.z = 0;
20812   }
20813   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20814   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20815   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20816   assert( m.z || db->mallocFailed );
20817   return m.z;
20818 }
20819
20820 /*
20821 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20822 ** enc. A pointer to the new string is returned, and the value of *pnOut
20823 ** is set to the length of the returned string in bytes. The call should
20824 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20825 ** no longer required.
20826 ** 
20827 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20828 ** flag set.
20829 */
20830 #ifdef SQLITE_ENABLE_STAT3
20831 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20832   Mem m;
20833   memset(&m, 0, sizeof(m));
20834   m.db = db;
20835   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20836   if( sqlite3VdbeMemTranslate(&m, enc) ){
20837     assert( db->mallocFailed );
20838     return 0;
20839   }
20840   assert( m.z==m.zMalloc );
20841   *pnOut = m.n;
20842   return m.z;
20843 }
20844 #endif
20845
20846 /*
20847 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20848 ** Return the number of bytes in the first nChar unicode characters
20849 ** in pZ.  nChar must be non-negative.
20850 */
20851 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20852   int c;
20853   unsigned char const *z = zIn;
20854   int n = 0;
20855   
20856   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20857     while( n<nChar ){
20858       READ_UTF16BE(z, 1, c);
20859       n++;
20860     }
20861   }else{
20862     while( n<nChar ){
20863       READ_UTF16LE(z, 1, c);
20864       n++;
20865     }
20866   }
20867   return (int)(z-(unsigned char const *)zIn);
20868 }
20869
20870 #if defined(SQLITE_TEST)
20871 /*
20872 ** This routine is called from the TCL test function "translate_selftest".
20873 ** It checks that the primitives for serializing and deserializing
20874 ** characters in each encoding are inverses of each other.
20875 */
20876 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20877   unsigned int i, t;
20878   unsigned char zBuf[20];
20879   unsigned char *z;
20880   int n;
20881   unsigned int c;
20882
20883   for(i=0; i<0x00110000; i++){
20884     z = zBuf;
20885     WRITE_UTF8(z, i);
20886     n = (int)(z-zBuf);
20887     assert( n>0 && n<=4 );
20888     z[0] = 0;
20889     z = zBuf;
20890     c = sqlite3Utf8Read(z, (const u8**)&z);
20891     t = i;
20892     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20893     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20894     assert( c==t );
20895     assert( (z-zBuf)==n );
20896   }
20897   for(i=0; i<0x00110000; i++){
20898     if( i>=0xD800 && i<0xE000 ) continue;
20899     z = zBuf;
20900     WRITE_UTF16LE(z, i);
20901     n = (int)(z-zBuf);
20902     assert( n>0 && n<=4 );
20903     z[0] = 0;
20904     z = zBuf;
20905     READ_UTF16LE(z, 1, c);
20906     assert( c==i );
20907     assert( (z-zBuf)==n );
20908   }
20909   for(i=0; i<0x00110000; i++){
20910     if( i>=0xD800 && i<0xE000 ) continue;
20911     z = zBuf;
20912     WRITE_UTF16BE(z, i);
20913     n = (int)(z-zBuf);
20914     assert( n>0 && n<=4 );
20915     z[0] = 0;
20916     z = zBuf;
20917     READ_UTF16BE(z, 1, c);
20918     assert( c==i );
20919     assert( (z-zBuf)==n );
20920   }
20921 }
20922 #endif /* SQLITE_TEST */
20923 #endif /* SQLITE_OMIT_UTF16 */
20924
20925 /************** End of utf.c *************************************************/
20926 /************** Begin file util.c ********************************************/
20927 /*
20928 ** 2001 September 15
20929 **
20930 ** The author disclaims copyright to this source code.  In place of
20931 ** a legal notice, here is a blessing:
20932 **
20933 **    May you do good and not evil.
20934 **    May you find forgiveness for yourself and forgive others.
20935 **    May you share freely, never taking more than you give.
20936 **
20937 *************************************************************************
20938 ** Utility functions used throughout sqlite.
20939 **
20940 ** This file contains functions for allocating memory, comparing
20941 ** strings, and stuff like that.
20942 **
20943 */
20944 /* #include <stdarg.h> */
20945 #ifdef SQLITE_HAVE_ISNAN
20946 # include <math.h>
20947 #endif
20948
20949 /*
20950 ** Routine needed to support the testcase() macro.
20951 */
20952 #ifdef SQLITE_COVERAGE_TEST
20953 SQLITE_PRIVATE void sqlite3Coverage(int x){
20954   static unsigned dummy = 0;
20955   dummy += (unsigned)x;
20956 }
20957 #endif
20958
20959 #ifndef SQLITE_OMIT_FLOATING_POINT
20960 /*
20961 ** Return true if the floating point value is Not a Number (NaN).
20962 **
20963 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20964 ** Otherwise, we have our own implementation that works on most systems.
20965 */
20966 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20967   int rc;   /* The value return */
20968 #if !defined(SQLITE_HAVE_ISNAN)
20969   /*
20970   ** Systems that support the isnan() library function should probably
20971   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20972   ** found that many systems do not have a working isnan() function so
20973   ** this implementation is provided as an alternative.
20974   **
20975   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20976   ** On the other hand, the use of -ffast-math comes with the following
20977   ** warning:
20978   **
20979   **      This option [-ffast-math] should never be turned on by any
20980   **      -O option since it can result in incorrect output for programs
20981   **      which depend on an exact implementation of IEEE or ISO 
20982   **      rules/specifications for math functions.
20983   **
20984   ** Under MSVC, this NaN test may fail if compiled with a floating-
20985   ** point precision mode other than /fp:precise.  From the MSDN 
20986   ** documentation:
20987   **
20988   **      The compiler [with /fp:precise] will properly handle comparisons 
20989   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20990   **      ...
20991   */
20992 #ifdef __FAST_MATH__
20993 # error SQLite will not work correctly with the -ffast-math option of GCC.
20994 #endif
20995   volatile double y = x;
20996   volatile double z = y;
20997   rc = (y!=z);
20998 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20999   rc = isnan(x);
21000 #endif /* SQLITE_HAVE_ISNAN */
21001   testcase( rc );
21002   return rc;
21003 }
21004 #endif /* SQLITE_OMIT_FLOATING_POINT */
21005
21006 /*
21007 ** Compute a string length that is limited to what can be stored in
21008 ** lower 30 bits of a 32-bit signed integer.
21009 **
21010 ** The value returned will never be negative.  Nor will it ever be greater
21011 ** than the actual length of the string.  For very long strings (greater
21012 ** than 1GiB) the value returned might be less than the true string length.
21013 */
21014 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21015   const char *z2 = z;
21016   if( z==0 ) return 0;
21017   while( *z2 ){ z2++; }
21018   return 0x3fffffff & (int)(z2 - z);
21019 }
21020
21021 /*
21022 ** Set the most recent error code and error string for the sqlite
21023 ** handle "db". The error code is set to "err_code".
21024 **
21025 ** If it is not NULL, string zFormat specifies the format of the
21026 ** error string in the style of the printf functions: The following
21027 ** format characters are allowed:
21028 **
21029 **      %s      Insert a string
21030 **      %z      A string that should be freed after use
21031 **      %d      Insert an integer
21032 **      %T      Insert a token
21033 **      %S      Insert the first element of a SrcList
21034 **
21035 ** zFormat and any string tokens that follow it are assumed to be
21036 ** encoded in UTF-8.
21037 **
21038 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21039 ** should be called with err_code set to SQLITE_OK and zFormat set
21040 ** to NULL.
21041 */
21042 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21043   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21044     db->errCode = err_code;
21045     if( zFormat ){
21046       char *z;
21047       va_list ap;
21048       va_start(ap, zFormat);
21049       z = sqlite3VMPrintf(db, zFormat, ap);
21050       va_end(ap);
21051       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21052     }else{
21053       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21054     }
21055   }
21056 }
21057
21058 /*
21059 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21060 ** The following formatting characters are allowed:
21061 **
21062 **      %s      Insert a string
21063 **      %z      A string that should be freed after use
21064 **      %d      Insert an integer
21065 **      %T      Insert a token
21066 **      %S      Insert the first element of a SrcList
21067 **
21068 ** This function should be used to report any error that occurs whilst
21069 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21070 ** last thing the sqlite3_prepare() function does is copy the error
21071 ** stored by this function into the database handle using sqlite3Error().
21072 ** Function sqlite3Error() should be used during statement execution
21073 ** (sqlite3_step() etc.).
21074 */
21075 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21076   char *zMsg;
21077   va_list ap;
21078   sqlite3 *db = pParse->db;
21079   va_start(ap, zFormat);
21080   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21081   va_end(ap);
21082   if( db->suppressErr ){
21083     sqlite3DbFree(db, zMsg);
21084   }else{
21085     pParse->nErr++;
21086     sqlite3DbFree(db, pParse->zErrMsg);
21087     pParse->zErrMsg = zMsg;
21088     pParse->rc = SQLITE_ERROR;
21089   }
21090 }
21091
21092 /*
21093 ** Convert an SQL-style quoted string into a normal string by removing
21094 ** the quote characters.  The conversion is done in-place.  If the
21095 ** input does not begin with a quote character, then this routine
21096 ** is a no-op.
21097 **
21098 ** The input string must be zero-terminated.  A new zero-terminator
21099 ** is added to the dequoted string.
21100 **
21101 ** The return value is -1 if no dequoting occurs or the length of the
21102 ** dequoted string, exclusive of the zero terminator, if dequoting does
21103 ** occur.
21104 **
21105 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21106 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21107 ** "a-b-c".
21108 */
21109 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21110   char quote;
21111   int i, j;
21112   if( z==0 ) return -1;
21113   quote = z[0];
21114   switch( quote ){
21115     case '\'':  break;
21116     case '"':   break;
21117     case '`':   break;                /* For MySQL compatibility */
21118     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21119     default:    return -1;
21120   }
21121   for(i=1, j=0; ALWAYS(z[i]); i++){
21122     if( z[i]==quote ){
21123       if( z[i+1]==quote ){
21124         z[j++] = quote;
21125         i++;
21126       }else{
21127         break;
21128       }
21129     }else{
21130       z[j++] = z[i];
21131     }
21132   }
21133   z[j] = 0;
21134   return j;
21135 }
21136
21137 /* Convenient short-hand */
21138 #define UpperToLower sqlite3UpperToLower
21139
21140 /*
21141 ** Some systems have stricmp().  Others have strcasecmp().  Because
21142 ** there is no consistency, we will define our own.
21143 **
21144 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21145 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21146 ** the contents of two buffers containing UTF-8 strings in a
21147 ** case-independent fashion, using the same definition of "case
21148 ** independence" that SQLite uses internally when comparing identifiers.
21149 */
21150 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21151   register unsigned char *a, *b;
21152   a = (unsigned char *)zLeft;
21153   b = (unsigned char *)zRight;
21154   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21155   return UpperToLower[*a] - UpperToLower[*b];
21156 }
21157 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21158   register unsigned char *a, *b;
21159   a = (unsigned char *)zLeft;
21160   b = (unsigned char *)zRight;
21161   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21162   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21163 }
21164
21165 /*
21166 ** The string z[] is an text representation of a real number.
21167 ** Convert this string to a double and write it into *pResult.
21168 **
21169 ** The string z[] is length bytes in length (bytes, not characters) and
21170 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21171 **
21172 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21173 ** if the string is empty or contains extraneous text.  Valid numbers
21174 ** are in one of these formats:
21175 **
21176 **    [+-]digits[E[+-]digits]
21177 **    [+-]digits.[digits][E[+-]digits]
21178 **    [+-].digits[E[+-]digits]
21179 **
21180 ** Leading and trailing whitespace is ignored for the purpose of determining
21181 ** validity.
21182 **
21183 ** If some prefix of the input string is a valid number, this routine
21184 ** returns FALSE but it still converts the prefix and writes the result
21185 ** into *pResult.
21186 */
21187 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21188 #ifndef SQLITE_OMIT_FLOATING_POINT
21189   int incr = (enc==SQLITE_UTF8?1:2);
21190   const char *zEnd = z + length;
21191   /* sign * significand * (10 ^ (esign * exponent)) */
21192   int sign = 1;    /* sign of significand */
21193   i64 s = 0;       /* significand */
21194   int d = 0;       /* adjust exponent for shifting decimal point */
21195   int esign = 1;   /* sign of exponent */
21196   int e = 0;       /* exponent */
21197   int eValid = 1;  /* True exponent is either not used or is well-formed */
21198   double result;
21199   int nDigits = 0;
21200
21201   *pResult = 0.0;   /* Default return value, in case of an error */
21202
21203   if( enc==SQLITE_UTF16BE ) z++;
21204
21205   /* skip leading spaces */
21206   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21207   if( z>=zEnd ) return 0;
21208
21209   /* get sign of significand */
21210   if( *z=='-' ){
21211     sign = -1;
21212     z+=incr;
21213   }else if( *z=='+' ){
21214     z+=incr;
21215   }
21216
21217   /* skip leading zeroes */
21218   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21219
21220   /* copy max significant digits to significand */
21221   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21222     s = s*10 + (*z - '0');
21223     z+=incr, nDigits++;
21224   }
21225
21226   /* skip non-significant significand digits
21227   ** (increase exponent by d to shift decimal left) */
21228   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21229   if( z>=zEnd ) goto do_atof_calc;
21230
21231   /* if decimal point is present */
21232   if( *z=='.' ){
21233     z+=incr;
21234     /* copy digits from after decimal to significand
21235     ** (decrease exponent by d to shift decimal right) */
21236     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21237       s = s*10 + (*z - '0');
21238       z+=incr, nDigits++, d--;
21239     }
21240     /* skip non-significant digits */
21241     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21242   }
21243   if( z>=zEnd ) goto do_atof_calc;
21244
21245   /* if exponent is present */
21246   if( *z=='e' || *z=='E' ){
21247     z+=incr;
21248     eValid = 0;
21249     if( z>=zEnd ) goto do_atof_calc;
21250     /* get sign of exponent */
21251     if( *z=='-' ){
21252       esign = -1;
21253       z+=incr;
21254     }else if( *z=='+' ){
21255       z+=incr;
21256     }
21257     /* copy digits to exponent */
21258     while( z<zEnd && sqlite3Isdigit(*z) ){
21259       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21260       z+=incr;
21261       eValid = 1;
21262     }
21263   }
21264
21265   /* skip trailing spaces */
21266   if( nDigits && eValid ){
21267     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21268   }
21269
21270 do_atof_calc:
21271   /* adjust exponent by d, and update sign */
21272   e = (e*esign) + d;
21273   if( e<0 ) {
21274     esign = -1;
21275     e *= -1;
21276   } else {
21277     esign = 1;
21278   }
21279
21280   /* if 0 significand */
21281   if( !s ) {
21282     /* In the IEEE 754 standard, zero is signed.
21283     ** Add the sign if we've seen at least one digit */
21284     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21285   } else {
21286     /* attempt to reduce exponent */
21287     if( esign>0 ){
21288       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21289     }else{
21290       while( !(s%10) && e>0 ) e--,s/=10;
21291     }
21292
21293     /* adjust the sign of significand */
21294     s = sign<0 ? -s : s;
21295
21296     /* if exponent, scale significand as appropriate
21297     ** and store in result. */
21298     if( e ){
21299       LONGDOUBLE_TYPE scale = 1.0;
21300       /* attempt to handle extremely small/large numbers better */
21301       if( e>307 && e<342 ){
21302         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21303         if( esign<0 ){
21304           result = s / scale;
21305           result /= 1.0e+308;
21306         }else{
21307           result = s * scale;
21308           result *= 1.0e+308;
21309         }
21310       }else if( e>=342 ){
21311         if( esign<0 ){
21312           result = 0.0*s;
21313         }else{
21314           result = 1e308*1e308*s;  /* Infinity */
21315         }
21316       }else{
21317         /* 1.0e+22 is the largest power of 10 than can be 
21318         ** represented exactly. */
21319         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21320         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21321         if( esign<0 ){
21322           result = s / scale;
21323         }else{
21324           result = s * scale;
21325         }
21326       }
21327     } else {
21328       result = (double)s;
21329     }
21330   }
21331
21332   /* store the result */
21333   *pResult = result;
21334
21335   /* return true if number and no extra non-whitespace chracters after */
21336   return z>=zEnd && nDigits>0 && eValid;
21337 #else
21338   return !sqlite3Atoi64(z, pResult, length, enc);
21339 #endif /* SQLITE_OMIT_FLOATING_POINT */
21340 }
21341
21342 /*
21343 ** Compare the 19-character string zNum against the text representation
21344 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21345 ** if zNum is less than, equal to, or greater than the string.
21346 ** Note that zNum must contain exactly 19 characters.
21347 **
21348 ** Unlike memcmp() this routine is guaranteed to return the difference
21349 ** in the values of the last digit if the only difference is in the
21350 ** last digit.  So, for example,
21351 **
21352 **      compare2pow63("9223372036854775800", 1)
21353 **
21354 ** will return -8.
21355 */
21356 static int compare2pow63(const char *zNum, int incr){
21357   int c = 0;
21358   int i;
21359                     /* 012345678901234567 */
21360   const char *pow63 = "922337203685477580";
21361   for(i=0; c==0 && i<18; i++){
21362     c = (zNum[i*incr]-pow63[i])*10;
21363   }
21364   if( c==0 ){
21365     c = zNum[18*incr] - '8';
21366     testcase( c==(-1) );
21367     testcase( c==0 );
21368     testcase( c==(+1) );
21369   }
21370   return c;
21371 }
21372
21373
21374 /*
21375 ** Convert zNum to a 64-bit signed integer.
21376 **
21377 ** If the zNum value is representable as a 64-bit twos-complement 
21378 ** integer, then write that value into *pNum and return 0.
21379 **
21380 ** If zNum is exactly 9223372036854665808, return 2.  This special
21381 ** case is broken out because while 9223372036854665808 cannot be a 
21382 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21383 **
21384 ** If zNum is too big for a 64-bit integer and is not
21385 ** 9223372036854665808 then return 1.
21386 **
21387 ** length is the number of bytes in the string (bytes, not characters).
21388 ** The string is not necessarily zero-terminated.  The encoding is
21389 ** given by enc.
21390 */
21391 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21392   int incr = (enc==SQLITE_UTF8?1:2);
21393   u64 u = 0;
21394   int neg = 0; /* assume positive */
21395   int i;
21396   int c = 0;
21397   const char *zStart;
21398   const char *zEnd = zNum + length;
21399   if( enc==SQLITE_UTF16BE ) zNum++;
21400   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21401   if( zNum<zEnd ){
21402     if( *zNum=='-' ){
21403       neg = 1;
21404       zNum+=incr;
21405     }else if( *zNum=='+' ){
21406       zNum+=incr;
21407     }
21408   }
21409   zStart = zNum;
21410   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21411   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21412     u = u*10 + c - '0';
21413   }
21414   if( u>LARGEST_INT64 ){
21415     *pNum = SMALLEST_INT64;
21416   }else if( neg ){
21417     *pNum = -(i64)u;
21418   }else{
21419     *pNum = (i64)u;
21420   }
21421   testcase( i==18 );
21422   testcase( i==19 );
21423   testcase( i==20 );
21424   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21425     /* zNum is empty or contains non-numeric text or is longer
21426     ** than 19 digits (thus guaranteeing that it is too large) */
21427     return 1;
21428   }else if( i<19*incr ){
21429     /* Less than 19 digits, so we know that it fits in 64 bits */
21430     assert( u<=LARGEST_INT64 );
21431     return 0;
21432   }else{
21433     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21434     c = compare2pow63(zNum, incr);
21435     if( c<0 ){
21436       /* zNum is less than 9223372036854775808 so it fits */
21437       assert( u<=LARGEST_INT64 );
21438       return 0;
21439     }else if( c>0 ){
21440       /* zNum is greater than 9223372036854775808 so it overflows */
21441       return 1;
21442     }else{
21443       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21444       ** special case 2 overflow if positive */
21445       assert( u-1==LARGEST_INT64 );
21446       assert( (*pNum)==SMALLEST_INT64 );
21447       return neg ? 0 : 2;
21448     }
21449   }
21450 }
21451
21452 /*
21453 ** If zNum represents an integer that will fit in 32-bits, then set
21454 ** *pValue to that integer and return true.  Otherwise return false.
21455 **
21456 ** Any non-numeric characters that following zNum are ignored.
21457 ** This is different from sqlite3Atoi64() which requires the
21458 ** input number to be zero-terminated.
21459 */
21460 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21461   sqlite_int64 v = 0;
21462   int i, c;
21463   int neg = 0;
21464   if( zNum[0]=='-' ){
21465     neg = 1;
21466     zNum++;
21467   }else if( zNum[0]=='+' ){
21468     zNum++;
21469   }
21470   while( zNum[0]=='0' ) zNum++;
21471   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21472     v = v*10 + c;
21473   }
21474
21475   /* The longest decimal representation of a 32 bit integer is 10 digits:
21476   **
21477   **             1234567890
21478   **     2^31 -> 2147483648
21479   */
21480   testcase( i==10 );
21481   if( i>10 ){
21482     return 0;
21483   }
21484   testcase( v-neg==2147483647 );
21485   if( v-neg>2147483647 ){
21486     return 0;
21487   }
21488   if( neg ){
21489     v = -v;
21490   }
21491   *pValue = (int)v;
21492   return 1;
21493 }
21494
21495 /*
21496 ** Return a 32-bit integer value extracted from a string.  If the
21497 ** string is not an integer, just return 0.
21498 */
21499 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21500   int x = 0;
21501   if( z ) sqlite3GetInt32(z, &x);
21502   return x;
21503 }
21504
21505 /*
21506 ** The variable-length integer encoding is as follows:
21507 **
21508 ** KEY:
21509 **         A = 0xxxxxxx    7 bits of data and one flag bit
21510 **         B = 1xxxxxxx    7 bits of data and one flag bit
21511 **         C = xxxxxxxx    8 bits of data
21512 **
21513 **  7 bits - A
21514 ** 14 bits - BA
21515 ** 21 bits - BBA
21516 ** 28 bits - BBBA
21517 ** 35 bits - BBBBA
21518 ** 42 bits - BBBBBA
21519 ** 49 bits - BBBBBBA
21520 ** 56 bits - BBBBBBBA
21521 ** 64 bits - BBBBBBBBC
21522 */
21523
21524 /*
21525 ** Write a 64-bit variable-length integer to memory starting at p[0].
21526 ** The length of data write will be between 1 and 9 bytes.  The number
21527 ** of bytes written is returned.
21528 **
21529 ** A variable-length integer consists of the lower 7 bits of each byte
21530 ** for all bytes that have the 8th bit set and one byte with the 8th
21531 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21532 ** 8 bits and is the last byte.
21533 */
21534 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21535   int i, j, n;
21536   u8 buf[10];
21537   if( v & (((u64)0xff000000)<<32) ){
21538     p[8] = (u8)v;
21539     v >>= 8;
21540     for(i=7; i>=0; i--){
21541       p[i] = (u8)((v & 0x7f) | 0x80);
21542       v >>= 7;
21543     }
21544     return 9;
21545   }    
21546   n = 0;
21547   do{
21548     buf[n++] = (u8)((v & 0x7f) | 0x80);
21549     v >>= 7;
21550   }while( v!=0 );
21551   buf[0] &= 0x7f;
21552   assert( n<=9 );
21553   for(i=0, j=n-1; j>=0; j--, i++){
21554     p[i] = buf[j];
21555   }
21556   return n;
21557 }
21558
21559 /*
21560 ** This routine is a faster version of sqlite3PutVarint() that only
21561 ** works for 32-bit positive integers and which is optimized for
21562 ** the common case of small integers.  A MACRO version, putVarint32,
21563 ** is provided which inlines the single-byte case.  All code should use
21564 ** the MACRO version as this function assumes the single-byte case has
21565 ** already been handled.
21566 */
21567 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21568 #ifndef putVarint32
21569   if( (v & ~0x7f)==0 ){
21570     p[0] = v;
21571     return 1;
21572   }
21573 #endif
21574   if( (v & ~0x3fff)==0 ){
21575     p[0] = (u8)((v>>7) | 0x80);
21576     p[1] = (u8)(v & 0x7f);
21577     return 2;
21578   }
21579   return sqlite3PutVarint(p, v);
21580 }
21581
21582 /*
21583 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21584 ** are defined here rather than simply putting the constant expressions
21585 ** inline in order to work around bugs in the RVT compiler.
21586 **
21587 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21588 **
21589 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21590 */
21591 #define SLOT_2_0     0x001fc07f
21592 #define SLOT_4_2_0   0xf01fc07f
21593
21594
21595 /*
21596 ** Read a 64-bit variable-length integer from memory starting at p[0].
21597 ** Return the number of bytes read.  The value is stored in *v.
21598 */
21599 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21600   u32 a,b,s;
21601
21602   a = *p;
21603   /* a: p0 (unmasked) */
21604   if (!(a&0x80))
21605   {
21606     *v = a;
21607     return 1;
21608   }
21609
21610   p++;
21611   b = *p;
21612   /* b: p1 (unmasked) */
21613   if (!(b&0x80))
21614   {
21615     a &= 0x7f;
21616     a = a<<7;
21617     a |= b;
21618     *v = a;
21619     return 2;
21620   }
21621
21622   /* Verify that constants are precomputed correctly */
21623   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21624   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21625
21626   p++;
21627   a = a<<14;
21628   a |= *p;
21629   /* a: p0<<14 | p2 (unmasked) */
21630   if (!(a&0x80))
21631   {
21632     a &= SLOT_2_0;
21633     b &= 0x7f;
21634     b = b<<7;
21635     a |= b;
21636     *v = a;
21637     return 3;
21638   }
21639
21640   /* CSE1 from below */
21641   a &= SLOT_2_0;
21642   p++;
21643   b = b<<14;
21644   b |= *p;
21645   /* b: p1<<14 | p3 (unmasked) */
21646   if (!(b&0x80))
21647   {
21648     b &= SLOT_2_0;
21649     /* moved CSE1 up */
21650     /* a &= (0x7f<<14)|(0x7f); */
21651     a = a<<7;
21652     a |= b;
21653     *v = a;
21654     return 4;
21655   }
21656
21657   /* a: p0<<14 | p2 (masked) */
21658   /* b: p1<<14 | p3 (unmasked) */
21659   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21660   /* moved CSE1 up */
21661   /* a &= (0x7f<<14)|(0x7f); */
21662   b &= SLOT_2_0;
21663   s = a;
21664   /* s: p0<<14 | p2 (masked) */
21665
21666   p++;
21667   a = a<<14;
21668   a |= *p;
21669   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21670   if (!(a&0x80))
21671   {
21672     /* we can skip these cause they were (effectively) done above in calc'ing s */
21673     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21674     /* b &= (0x7f<<14)|(0x7f); */
21675     b = b<<7;
21676     a |= b;
21677     s = s>>18;
21678     *v = ((u64)s)<<32 | a;
21679     return 5;
21680   }
21681
21682   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21683   s = s<<7;
21684   s |= b;
21685   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21686
21687   p++;
21688   b = b<<14;
21689   b |= *p;
21690   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21691   if (!(b&0x80))
21692   {
21693     /* we can skip this cause it was (effectively) done above in calc'ing s */
21694     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21695     a &= SLOT_2_0;
21696     a = a<<7;
21697     a |= b;
21698     s = s>>18;
21699     *v = ((u64)s)<<32 | a;
21700     return 6;
21701   }
21702
21703   p++;
21704   a = a<<14;
21705   a |= *p;
21706   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21707   if (!(a&0x80))
21708   {
21709     a &= SLOT_4_2_0;
21710     b &= SLOT_2_0;
21711     b = b<<7;
21712     a |= b;
21713     s = s>>11;
21714     *v = ((u64)s)<<32 | a;
21715     return 7;
21716   }
21717
21718   /* CSE2 from below */
21719   a &= SLOT_2_0;
21720   p++;
21721   b = b<<14;
21722   b |= *p;
21723   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21724   if (!(b&0x80))
21725   {
21726     b &= SLOT_4_2_0;
21727     /* moved CSE2 up */
21728     /* a &= (0x7f<<14)|(0x7f); */
21729     a = a<<7;
21730     a |= b;
21731     s = s>>4;
21732     *v = ((u64)s)<<32 | a;
21733     return 8;
21734   }
21735
21736   p++;
21737   a = a<<15;
21738   a |= *p;
21739   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21740
21741   /* moved CSE2 up */
21742   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21743   b &= SLOT_2_0;
21744   b = b<<8;
21745   a |= b;
21746
21747   s = s<<4;
21748   b = p[-4];
21749   b &= 0x7f;
21750   b = b>>3;
21751   s |= b;
21752
21753   *v = ((u64)s)<<32 | a;
21754
21755   return 9;
21756 }
21757
21758 /*
21759 ** Read a 32-bit variable-length integer from memory starting at p[0].
21760 ** Return the number of bytes read.  The value is stored in *v.
21761 **
21762 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21763 ** integer, then set *v to 0xffffffff.
21764 **
21765 ** A MACRO version, getVarint32, is provided which inlines the 
21766 ** single-byte case.  All code should use the MACRO version as 
21767 ** this function assumes the single-byte case has already been handled.
21768 */
21769 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21770   u32 a,b;
21771
21772   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21773   ** by the getVarin32() macro */
21774   a = *p;
21775   /* a: p0 (unmasked) */
21776 #ifndef getVarint32
21777   if (!(a&0x80))
21778   {
21779     /* Values between 0 and 127 */
21780     *v = a;
21781     return 1;
21782   }
21783 #endif
21784
21785   /* The 2-byte case */
21786   p++;
21787   b = *p;
21788   /* b: p1 (unmasked) */
21789   if (!(b&0x80))
21790   {
21791     /* Values between 128 and 16383 */
21792     a &= 0x7f;
21793     a = a<<7;
21794     *v = a | b;
21795     return 2;
21796   }
21797
21798   /* The 3-byte case */
21799   p++;
21800   a = a<<14;
21801   a |= *p;
21802   /* a: p0<<14 | p2 (unmasked) */
21803   if (!(a&0x80))
21804   {
21805     /* Values between 16384 and 2097151 */
21806     a &= (0x7f<<14)|(0x7f);
21807     b &= 0x7f;
21808     b = b<<7;
21809     *v = a | b;
21810     return 3;
21811   }
21812
21813   /* A 32-bit varint is used to store size information in btrees.
21814   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21815   ** A 3-byte varint is sufficient, for example, to record the size
21816   ** of a 1048569-byte BLOB or string.
21817   **
21818   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21819   ** rare larger cases can be handled by the slower 64-bit varint
21820   ** routine.
21821   */
21822 #if 1
21823   {
21824     u64 v64;
21825     u8 n;
21826
21827     p -= 2;
21828     n = sqlite3GetVarint(p, &v64);
21829     assert( n>3 && n<=9 );
21830     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21831       *v = 0xffffffff;
21832     }else{
21833       *v = (u32)v64;
21834     }
21835     return n;
21836   }
21837
21838 #else
21839   /* For following code (kept for historical record only) shows an
21840   ** unrolling for the 3- and 4-byte varint cases.  This code is
21841   ** slightly faster, but it is also larger and much harder to test.
21842   */
21843   p++;
21844   b = b<<14;
21845   b |= *p;
21846   /* b: p1<<14 | p3 (unmasked) */
21847   if (!(b&0x80))
21848   {
21849     /* Values between 2097152 and 268435455 */
21850     b &= (0x7f<<14)|(0x7f);
21851     a &= (0x7f<<14)|(0x7f);
21852     a = a<<7;
21853     *v = a | b;
21854     return 4;
21855   }
21856
21857   p++;
21858   a = a<<14;
21859   a |= *p;
21860   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21861   if (!(a&0x80))
21862   {
21863     /* Values  between 268435456 and 34359738367 */
21864     a &= SLOT_4_2_0;
21865     b &= SLOT_4_2_0;
21866     b = b<<7;
21867     *v = a | b;
21868     return 5;
21869   }
21870
21871   /* We can only reach this point when reading a corrupt database
21872   ** file.  In that case we are not in any hurry.  Use the (relatively
21873   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21874   ** value. */
21875   {
21876     u64 v64;
21877     u8 n;
21878
21879     p -= 4;
21880     n = sqlite3GetVarint(p, &v64);
21881     assert( n>5 && n<=9 );
21882     *v = (u32)v64;
21883     return n;
21884   }
21885 #endif
21886 }
21887
21888 /*
21889 ** Return the number of bytes that will be needed to store the given
21890 ** 64-bit integer.
21891 */
21892 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21893   int i = 0;
21894   do{
21895     i++;
21896     v >>= 7;
21897   }while( v!=0 && ALWAYS(i<9) );
21898   return i;
21899 }
21900
21901
21902 /*
21903 ** Read or write a four-byte big-endian integer value.
21904 */
21905 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21906   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21907 }
21908 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21909   p[0] = (u8)(v>>24);
21910   p[1] = (u8)(v>>16);
21911   p[2] = (u8)(v>>8);
21912   p[3] = (u8)v;
21913 }
21914
21915
21916
21917 /*
21918 ** Translate a single byte of Hex into an integer.
21919 ** This routine only works if h really is a valid hexadecimal
21920 ** character:  0..9a..fA..F
21921 */
21922 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
21923   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21924 #ifdef SQLITE_ASCII
21925   h += 9*(1&(h>>6));
21926 #endif
21927 #ifdef SQLITE_EBCDIC
21928   h += 9*(1&~(h>>4));
21929 #endif
21930   return (u8)(h & 0xf);
21931 }
21932
21933 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21934 /*
21935 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21936 ** value.  Return a pointer to its binary value.  Space to hold the
21937 ** binary value has been obtained from malloc and must be freed by
21938 ** the calling routine.
21939 */
21940 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21941   char *zBlob;
21942   int i;
21943
21944   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21945   n--;
21946   if( zBlob ){
21947     for(i=0; i<n; i+=2){
21948       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
21949     }
21950     zBlob[i/2] = 0;
21951   }
21952   return zBlob;
21953 }
21954 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21955
21956 /*
21957 ** Log an error that is an API call on a connection pointer that should
21958 ** not have been used.  The "type" of connection pointer is given as the
21959 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21960 */
21961 static void logBadConnection(const char *zType){
21962   sqlite3_log(SQLITE_MISUSE, 
21963      "API call with %s database connection pointer",
21964      zType
21965   );
21966 }
21967
21968 /*
21969 ** Check to make sure we have a valid db pointer.  This test is not
21970 ** foolproof but it does provide some measure of protection against
21971 ** misuse of the interface such as passing in db pointers that are
21972 ** NULL or which have been previously closed.  If this routine returns
21973 ** 1 it means that the db pointer is valid and 0 if it should not be
21974 ** dereferenced for any reason.  The calling function should invoke
21975 ** SQLITE_MISUSE immediately.
21976 **
21977 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21978 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21979 ** open properly and is not fit for general use but which can be
21980 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21981 */
21982 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21983   u32 magic;
21984   if( db==0 ){
21985     logBadConnection("NULL");
21986     return 0;
21987   }
21988   magic = db->magic;
21989   if( magic!=SQLITE_MAGIC_OPEN ){
21990     if( sqlite3SafetyCheckSickOrOk(db) ){
21991       testcase( sqlite3GlobalConfig.xLog!=0 );
21992       logBadConnection("unopened");
21993     }
21994     return 0;
21995   }else{
21996     return 1;
21997   }
21998 }
21999 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22000   u32 magic;
22001   magic = db->magic;
22002   if( magic!=SQLITE_MAGIC_SICK &&
22003       magic!=SQLITE_MAGIC_OPEN &&
22004       magic!=SQLITE_MAGIC_BUSY ){
22005     testcase( sqlite3GlobalConfig.xLog!=0 );
22006     logBadConnection("invalid");
22007     return 0;
22008   }else{
22009     return 1;
22010   }
22011 }
22012
22013 /*
22014 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22015 ** the other 64-bit signed integer at *pA and store the result in *pA.
22016 ** Return 0 on success.  Or if the operation would have resulted in an
22017 ** overflow, leave *pA unchanged and return 1.
22018 */
22019 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22020   i64 iA = *pA;
22021   testcase( iA==0 ); testcase( iA==1 );
22022   testcase( iB==-1 ); testcase( iB==0 );
22023   if( iB>=0 ){
22024     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22025     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22026     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22027     *pA += iB;
22028   }else{
22029     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22030     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22031     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22032     *pA += iB;
22033   }
22034   return 0; 
22035 }
22036 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22037   testcase( iB==SMALLEST_INT64+1 );
22038   if( iB==SMALLEST_INT64 ){
22039     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22040     if( (*pA)>=0 ) return 1;
22041     *pA -= iB;
22042     return 0;
22043   }else{
22044     return sqlite3AddInt64(pA, -iB);
22045   }
22046 }
22047 #define TWOPOWER32 (((i64)1)<<32)
22048 #define TWOPOWER31 (((i64)1)<<31)
22049 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22050   i64 iA = *pA;
22051   i64 iA1, iA0, iB1, iB0, r;
22052
22053   iA1 = iA/TWOPOWER32;
22054   iA0 = iA % TWOPOWER32;
22055   iB1 = iB/TWOPOWER32;
22056   iB0 = iB % TWOPOWER32;
22057   if( iA1*iB1 != 0 ) return 1;
22058   assert( iA1*iB0==0 || iA0*iB1==0 );
22059   r = iA1*iB0 + iA0*iB1;
22060   testcase( r==(-TWOPOWER31)-1 );
22061   testcase( r==(-TWOPOWER31) );
22062   testcase( r==TWOPOWER31 );
22063   testcase( r==TWOPOWER31-1 );
22064   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22065   r *= TWOPOWER32;
22066   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22067   *pA = r;
22068   return 0;
22069 }
22070
22071 /*
22072 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22073 ** if the integer has a value of -2147483648, return +2147483647
22074 */
22075 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22076   if( x>=0 ) return x;
22077   if( x==(int)0x80000000 ) return 0x7fffffff;
22078   return -x;
22079 }
22080
22081 #ifdef SQLITE_ENABLE_8_3_NAMES
22082 /*
22083 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22084 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22085 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22086 ** three characters, then shorten the suffix on z[] to be the last three
22087 ** characters of the original suffix.
22088 **
22089 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22090 ** do the suffix shortening regardless of URI parameter.
22091 **
22092 ** Examples:
22093 **
22094 **     test.db-journal    =>   test.nal
22095 **     test.db-wal        =>   test.wal
22096 **     test.db-shm        =>   test.shm
22097 **     test.db-mj7f3319fa =>   test.9fa
22098 */
22099 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22100 #if SQLITE_ENABLE_8_3_NAMES<2
22101   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22102 #endif
22103   {
22104     int i, sz;
22105     sz = sqlite3Strlen30(z);
22106     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22107     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22108   }
22109 }
22110 #endif
22111
22112 /************** End of util.c ************************************************/
22113 /************** Begin file hash.c ********************************************/
22114 /*
22115 ** 2001 September 22
22116 **
22117 ** The author disclaims copyright to this source code.  In place of
22118 ** a legal notice, here is a blessing:
22119 **
22120 **    May you do good and not evil.
22121 **    May you find forgiveness for yourself and forgive others.
22122 **    May you share freely, never taking more than you give.
22123 **
22124 *************************************************************************
22125 ** This is the implementation of generic hash-tables
22126 ** used in SQLite.
22127 */
22128 /* #include <assert.h> */
22129
22130 /* Turn bulk memory into a hash table object by initializing the
22131 ** fields of the Hash structure.
22132 **
22133 ** "pNew" is a pointer to the hash table that is to be initialized.
22134 */
22135 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22136   assert( pNew!=0 );
22137   pNew->first = 0;
22138   pNew->count = 0;
22139   pNew->htsize = 0;
22140   pNew->ht = 0;
22141 }
22142
22143 /* Remove all entries from a hash table.  Reclaim all memory.
22144 ** Call this routine to delete a hash table or to reset a hash table
22145 ** to the empty state.
22146 */
22147 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22148   HashElem *elem;         /* For looping over all elements of the table */
22149
22150   assert( pH!=0 );
22151   elem = pH->first;
22152   pH->first = 0;
22153   sqlite3_free(pH->ht);
22154   pH->ht = 0;
22155   pH->htsize = 0;
22156   while( elem ){
22157     HashElem *next_elem = elem->next;
22158     sqlite3_free(elem);
22159     elem = next_elem;
22160   }
22161   pH->count = 0;
22162 }
22163
22164 /*
22165 ** The hashing function.
22166 */
22167 static unsigned int strHash(const char *z, int nKey){
22168   int h = 0;
22169   assert( nKey>=0 );
22170   while( nKey > 0  ){
22171     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22172     nKey--;
22173   }
22174   return h;
22175 }
22176
22177
22178 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22179 ** insert pNew into the pEntry hash bucket.
22180 */
22181 static void insertElement(
22182   Hash *pH,              /* The complete hash table */
22183   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22184   HashElem *pNew         /* The element to be inserted */
22185 ){
22186   HashElem *pHead;       /* First element already in pEntry */
22187   if( pEntry ){
22188     pHead = pEntry->count ? pEntry->chain : 0;
22189     pEntry->count++;
22190     pEntry->chain = pNew;
22191   }else{
22192     pHead = 0;
22193   }
22194   if( pHead ){
22195     pNew->next = pHead;
22196     pNew->prev = pHead->prev;
22197     if( pHead->prev ){ pHead->prev->next = pNew; }
22198     else             { pH->first = pNew; }
22199     pHead->prev = pNew;
22200   }else{
22201     pNew->next = pH->first;
22202     if( pH->first ){ pH->first->prev = pNew; }
22203     pNew->prev = 0;
22204     pH->first = pNew;
22205   }
22206 }
22207
22208
22209 /* Resize the hash table so that it cantains "new_size" buckets.
22210 **
22211 ** The hash table might fail to resize if sqlite3_malloc() fails or
22212 ** if the new size is the same as the prior size.
22213 ** Return TRUE if the resize occurs and false if not.
22214 */
22215 static int rehash(Hash *pH, unsigned int new_size){
22216   struct _ht *new_ht;            /* The new hash table */
22217   HashElem *elem, *next_elem;    /* For looping over existing elements */
22218
22219 #if SQLITE_MALLOC_SOFT_LIMIT>0
22220   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22221     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22222   }
22223   if( new_size==pH->htsize ) return 0;
22224 #endif
22225
22226   /* The inability to allocates space for a larger hash table is
22227   ** a performance hit but it is not a fatal error.  So mark the
22228   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
22229   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22230   ** only zeroes the requested number of bytes whereas this module will
22231   ** use the actual amount of space allocated for the hash table (which
22232   ** may be larger than the requested amount).
22233   */
22234   sqlite3BeginBenignMalloc();
22235   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22236   sqlite3EndBenignMalloc();
22237
22238   if( new_ht==0 ) return 0;
22239   sqlite3_free(pH->ht);
22240   pH->ht = new_ht;
22241   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22242   memset(new_ht, 0, new_size*sizeof(struct _ht));
22243   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22244     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22245     next_elem = elem->next;
22246     insertElement(pH, &new_ht[h], elem);
22247   }
22248   return 1;
22249 }
22250
22251 /* This function (for internal use only) locates an element in an
22252 ** hash table that matches the given key.  The hash for this key has
22253 ** already been computed and is passed as the 4th parameter.
22254 */
22255 static HashElem *findElementGivenHash(
22256   const Hash *pH,     /* The pH to be searched */
22257   const char *pKey,   /* The key we are searching for */
22258   int nKey,           /* Bytes in key (not counting zero terminator) */
22259   unsigned int h      /* The hash for this key. */
22260 ){
22261   HashElem *elem;                /* Used to loop thru the element list */
22262   int count;                     /* Number of elements left to test */
22263
22264   if( pH->ht ){
22265     struct _ht *pEntry = &pH->ht[h];
22266     elem = pEntry->chain;
22267     count = pEntry->count;
22268   }else{
22269     elem = pH->first;
22270     count = pH->count;
22271   }
22272   while( count-- && ALWAYS(elem) ){
22273     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22274       return elem;
22275     }
22276     elem = elem->next;
22277   }
22278   return 0;
22279 }
22280
22281 /* Remove a single entry from the hash table given a pointer to that
22282 ** element and a hash on the element's key.
22283 */
22284 static void removeElementGivenHash(
22285   Hash *pH,         /* The pH containing "elem" */
22286   HashElem* elem,   /* The element to be removed from the pH */
22287   unsigned int h    /* Hash value for the element */
22288 ){
22289   struct _ht *pEntry;
22290   if( elem->prev ){
22291     elem->prev->next = elem->next; 
22292   }else{
22293     pH->first = elem->next;
22294   }
22295   if( elem->next ){
22296     elem->next->prev = elem->prev;
22297   }
22298   if( pH->ht ){
22299     pEntry = &pH->ht[h];
22300     if( pEntry->chain==elem ){
22301       pEntry->chain = elem->next;
22302     }
22303     pEntry->count--;
22304     assert( pEntry->count>=0 );
22305   }
22306   sqlite3_free( elem );
22307   pH->count--;
22308   if( pH->count<=0 ){
22309     assert( pH->first==0 );
22310     assert( pH->count==0 );
22311     sqlite3HashClear(pH);
22312   }
22313 }
22314
22315 /* Attempt to locate an element of the hash table pH with a key
22316 ** that matches pKey,nKey.  Return the data for this element if it is
22317 ** found, or NULL if there is no match.
22318 */
22319 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22320   HashElem *elem;    /* The element that matches key */
22321   unsigned int h;    /* A hash on key */
22322
22323   assert( pH!=0 );
22324   assert( pKey!=0 );
22325   assert( nKey>=0 );
22326   if( pH->ht ){
22327     h = strHash(pKey, nKey) % pH->htsize;
22328   }else{
22329     h = 0;
22330   }
22331   elem = findElementGivenHash(pH, pKey, nKey, h);
22332   return elem ? elem->data : 0;
22333 }
22334
22335 /* Insert an element into the hash table pH.  The key is pKey,nKey
22336 ** and the data is "data".
22337 **
22338 ** If no element exists with a matching key, then a new
22339 ** element is created and NULL is returned.
22340 **
22341 ** If another element already exists with the same key, then the
22342 ** new data replaces the old data and the old data is returned.
22343 ** The key is not copied in this instance.  If a malloc fails, then
22344 ** the new data is returned and the hash table is unchanged.
22345 **
22346 ** If the "data" parameter to this function is NULL, then the
22347 ** element corresponding to "key" is removed from the hash table.
22348 */
22349 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22350   unsigned int h;       /* the hash of the key modulo hash table size */
22351   HashElem *elem;       /* Used to loop thru the element list */
22352   HashElem *new_elem;   /* New element added to the pH */
22353
22354   assert( pH!=0 );
22355   assert( pKey!=0 );
22356   assert( nKey>=0 );
22357   if( pH->htsize ){
22358     h = strHash(pKey, nKey) % pH->htsize;
22359   }else{
22360     h = 0;
22361   }
22362   elem = findElementGivenHash(pH,pKey,nKey,h);
22363   if( elem ){
22364     void *old_data = elem->data;
22365     if( data==0 ){
22366       removeElementGivenHash(pH,elem,h);
22367     }else{
22368       elem->data = data;
22369       elem->pKey = pKey;
22370       assert(nKey==elem->nKey);
22371     }
22372     return old_data;
22373   }
22374   if( data==0 ) return 0;
22375   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22376   if( new_elem==0 ) return data;
22377   new_elem->pKey = pKey;
22378   new_elem->nKey = nKey;
22379   new_elem->data = data;
22380   pH->count++;
22381   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22382     if( rehash(pH, pH->count*2) ){
22383       assert( pH->htsize>0 );
22384       h = strHash(pKey, nKey) % pH->htsize;
22385     }
22386   }
22387   if( pH->ht ){
22388     insertElement(pH, &pH->ht[h], new_elem);
22389   }else{
22390     insertElement(pH, 0, new_elem);
22391   }
22392   return 0;
22393 }
22394
22395 /************** End of hash.c ************************************************/
22396 /************** Begin file opcodes.c *****************************************/
22397 /* Automatically generated.  Do not edit */
22398 /* See the mkopcodec.awk script for details. */
22399 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22400 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22401  static const char *const azName[] = { "?",
22402      /*   1 */ "Goto",
22403      /*   2 */ "Gosub",
22404      /*   3 */ "Return",
22405      /*   4 */ "Yield",
22406      /*   5 */ "HaltIfNull",
22407      /*   6 */ "Halt",
22408      /*   7 */ "Integer",
22409      /*   8 */ "Int64",
22410      /*   9 */ "String",
22411      /*  10 */ "Null",
22412      /*  11 */ "Blob",
22413      /*  12 */ "Variable",
22414      /*  13 */ "Move",
22415      /*  14 */ "Copy",
22416      /*  15 */ "SCopy",
22417      /*  16 */ "ResultRow",
22418      /*  17 */ "CollSeq",
22419      /*  18 */ "Function",
22420      /*  19 */ "Not",
22421      /*  20 */ "AddImm",
22422      /*  21 */ "MustBeInt",
22423      /*  22 */ "RealAffinity",
22424      /*  23 */ "Permutation",
22425      /*  24 */ "Compare",
22426      /*  25 */ "Jump",
22427      /*  26 */ "Once",
22428      /*  27 */ "If",
22429      /*  28 */ "IfNot",
22430      /*  29 */ "Column",
22431      /*  30 */ "Affinity",
22432      /*  31 */ "MakeRecord",
22433      /*  32 */ "Count",
22434      /*  33 */ "Savepoint",
22435      /*  34 */ "AutoCommit",
22436      /*  35 */ "Transaction",
22437      /*  36 */ "ReadCookie",
22438      /*  37 */ "SetCookie",
22439      /*  38 */ "VerifyCookie",
22440      /*  39 */ "OpenRead",
22441      /*  40 */ "OpenWrite",
22442      /*  41 */ "OpenAutoindex",
22443      /*  42 */ "OpenEphemeral",
22444      /*  43 */ "SorterOpen",
22445      /*  44 */ "OpenPseudo",
22446      /*  45 */ "Close",
22447      /*  46 */ "SeekLt",
22448      /*  47 */ "SeekLe",
22449      /*  48 */ "SeekGe",
22450      /*  49 */ "SeekGt",
22451      /*  50 */ "Seek",
22452      /*  51 */ "NotFound",
22453      /*  52 */ "Found",
22454      /*  53 */ "IsUnique",
22455      /*  54 */ "NotExists",
22456      /*  55 */ "Sequence",
22457      /*  56 */ "NewRowid",
22458      /*  57 */ "Insert",
22459      /*  58 */ "InsertInt",
22460      /*  59 */ "Delete",
22461      /*  60 */ "ResetCount",
22462      /*  61 */ "SorterCompare",
22463      /*  62 */ "SorterData",
22464      /*  63 */ "RowKey",
22465      /*  64 */ "RowData",
22466      /*  65 */ "Rowid",
22467      /*  66 */ "NullRow",
22468      /*  67 */ "Last",
22469      /*  68 */ "Or",
22470      /*  69 */ "And",
22471      /*  70 */ "SorterSort",
22472      /*  71 */ "Sort",
22473      /*  72 */ "Rewind",
22474      /*  73 */ "IsNull",
22475      /*  74 */ "NotNull",
22476      /*  75 */ "Ne",
22477      /*  76 */ "Eq",
22478      /*  77 */ "Gt",
22479      /*  78 */ "Le",
22480      /*  79 */ "Lt",
22481      /*  80 */ "Ge",
22482      /*  81 */ "SorterNext",
22483      /*  82 */ "BitAnd",
22484      /*  83 */ "BitOr",
22485      /*  84 */ "ShiftLeft",
22486      /*  85 */ "ShiftRight",
22487      /*  86 */ "Add",
22488      /*  87 */ "Subtract",
22489      /*  88 */ "Multiply",
22490      /*  89 */ "Divide",
22491      /*  90 */ "Remainder",
22492      /*  91 */ "Concat",
22493      /*  92 */ "Prev",
22494      /*  93 */ "BitNot",
22495      /*  94 */ "String8",
22496      /*  95 */ "Next",
22497      /*  96 */ "SorterInsert",
22498      /*  97 */ "IdxInsert",
22499      /*  98 */ "IdxDelete",
22500      /*  99 */ "IdxRowid",
22501      /* 100 */ "IdxLT",
22502      /* 101 */ "IdxGE",
22503      /* 102 */ "Destroy",
22504      /* 103 */ "Clear",
22505      /* 104 */ "CreateIndex",
22506      /* 105 */ "CreateTable",
22507      /* 106 */ "ParseSchema",
22508      /* 107 */ "LoadAnalysis",
22509      /* 108 */ "DropTable",
22510      /* 109 */ "DropIndex",
22511      /* 110 */ "DropTrigger",
22512      /* 111 */ "IntegrityCk",
22513      /* 112 */ "RowSetAdd",
22514      /* 113 */ "RowSetRead",
22515      /* 114 */ "RowSetTest",
22516      /* 115 */ "Program",
22517      /* 116 */ "Param",
22518      /* 117 */ "FkCounter",
22519      /* 118 */ "FkIfZero",
22520      /* 119 */ "MemMax",
22521      /* 120 */ "IfPos",
22522      /* 121 */ "IfNeg",
22523      /* 122 */ "IfZero",
22524      /* 123 */ "AggStep",
22525      /* 124 */ "AggFinal",
22526      /* 125 */ "Checkpoint",
22527      /* 126 */ "JournalMode",
22528      /* 127 */ "Vacuum",
22529      /* 128 */ "IncrVacuum",
22530      /* 129 */ "Expire",
22531      /* 130 */ "Real",
22532      /* 131 */ "TableLock",
22533      /* 132 */ "VBegin",
22534      /* 133 */ "VCreate",
22535      /* 134 */ "VDestroy",
22536      /* 135 */ "VOpen",
22537      /* 136 */ "VFilter",
22538      /* 137 */ "VColumn",
22539      /* 138 */ "VNext",
22540      /* 139 */ "VRename",
22541      /* 140 */ "VUpdate",
22542      /* 141 */ "ToText",
22543      /* 142 */ "ToBlob",
22544      /* 143 */ "ToNumeric",
22545      /* 144 */ "ToInt",
22546      /* 145 */ "ToReal",
22547      /* 146 */ "Pagecount",
22548      /* 147 */ "MaxPgcnt",
22549      /* 148 */ "Trace",
22550      /* 149 */ "Noop",
22551      /* 150 */ "Explain",
22552   };
22553   return azName[i];
22554 }
22555 #endif
22556
22557 /************** End of opcodes.c *********************************************/
22558 /************** Begin file os_unix.c *****************************************/
22559 /*
22560 ** 2004 May 22
22561 **
22562 ** The author disclaims copyright to this source code.  In place of
22563 ** a legal notice, here is a blessing:
22564 **
22565 **    May you do good and not evil.
22566 **    May you find forgiveness for yourself and forgive others.
22567 **    May you share freely, never taking more than you give.
22568 **
22569 ******************************************************************************
22570 **
22571 ** This file contains the VFS implementation for unix-like operating systems
22572 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22573 **
22574 ** There are actually several different VFS implementations in this file.
22575 ** The differences are in the way that file locking is done.  The default
22576 ** implementation uses Posix Advisory Locks.  Alternative implementations
22577 ** use flock(), dot-files, various proprietary locking schemas, or simply
22578 ** skip locking all together.
22579 **
22580 ** This source file is organized into divisions where the logic for various
22581 ** subfunctions is contained within the appropriate division.  PLEASE
22582 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22583 ** in the correct division and should be clearly labeled.
22584 **
22585 ** The layout of divisions is as follows:
22586 **
22587 **   *  General-purpose declarations and utility functions.
22588 **   *  Unique file ID logic used by VxWorks.
22589 **   *  Various locking primitive implementations (all except proxy locking):
22590 **      + for Posix Advisory Locks
22591 **      + for no-op locks
22592 **      + for dot-file locks
22593 **      + for flock() locking
22594 **      + for named semaphore locks (VxWorks only)
22595 **      + for AFP filesystem locks (MacOSX only)
22596 **   *  sqlite3_file methods not associated with locking.
22597 **   *  Definitions of sqlite3_io_methods objects for all locking
22598 **      methods plus "finder" functions for each locking method.
22599 **   *  sqlite3_vfs method implementations.
22600 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22601 **   *  Definitions of sqlite3_vfs objects for all locking methods
22602 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22603 */
22604 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22605
22606 /*
22607 ** There are various methods for file locking used for concurrency
22608 ** control:
22609 **
22610 **   1. POSIX locking (the default),
22611 **   2. No locking,
22612 **   3. Dot-file locking,
22613 **   4. flock() locking,
22614 **   5. AFP locking (OSX only),
22615 **   6. Named POSIX semaphores (VXWorks only),
22616 **   7. proxy locking. (OSX only)
22617 **
22618 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22619 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22620 ** selection of the appropriate locking style based on the filesystem
22621 ** where the database is located.  
22622 */
22623 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22624 #  if defined(__APPLE__)
22625 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22626 #  else
22627 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22628 #  endif
22629 #endif
22630
22631 /*
22632 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22633 ** vxworks, or 0 otherwise.
22634 */
22635 #ifndef OS_VXWORKS
22636 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22637 #    define OS_VXWORKS 1
22638 #  else
22639 #    define OS_VXWORKS 0
22640 #  endif
22641 #endif
22642
22643 /*
22644 ** These #defines should enable >2GB file support on Posix if the
22645 ** underlying operating system supports it.  If the OS lacks
22646 ** large file support, these should be no-ops.
22647 **
22648 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22649 ** on the compiler command line.  This is necessary if you are compiling
22650 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22651 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22652 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22653 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22654 ** portability you should omit LFS.
22655 **
22656 ** The previous paragraph was written in 2005.  (This paragraph is written
22657 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22658 ** you should probably leave LFS enabled.  But some embedded platforms might
22659 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22660 */
22661 #ifndef SQLITE_DISABLE_LFS
22662 # define _LARGE_FILE       1
22663 # ifndef _FILE_OFFSET_BITS
22664 #   define _FILE_OFFSET_BITS 64
22665 # endif
22666 # define _LARGEFILE_SOURCE 1
22667 #endif
22668
22669 /*
22670 ** standard include files.
22671 */
22672 #include <sys/types.h>
22673 #include <sys/stat.h>
22674 #include <fcntl.h>
22675 #include <unistd.h>
22676 /* #include <time.h> */
22677 #include <sys/time.h>
22678 #include <errno.h>
22679 #ifndef SQLITE_OMIT_WAL
22680 #include <sys/mman.h>
22681 #endif
22682
22683
22684 #if SQLITE_ENABLE_LOCKING_STYLE
22685 # include <sys/ioctl.h>
22686 # if OS_VXWORKS
22687 #  include <semaphore.h>
22688 #  include <limits.h>
22689 # else
22690 #  include <sys/file.h>
22691 #  include <sys/param.h>
22692 # endif
22693 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22694
22695 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22696 # include <sys/mount.h>
22697 #endif
22698
22699 #ifdef HAVE_UTIME
22700 # include <utime.h>
22701 #endif
22702
22703 /*
22704 ** Allowed values of unixFile.fsFlags
22705 */
22706 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22707
22708 /*
22709 ** If we are to be thread-safe, include the pthreads header and define
22710 ** the SQLITE_UNIX_THREADS macro.
22711 */
22712 #if SQLITE_THREADSAFE
22713 /* # include <pthread.h> */
22714 # define SQLITE_UNIX_THREADS 1
22715 #endif
22716
22717 /*
22718 ** Default permissions when creating a new file
22719 */
22720 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22721 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22722 #endif
22723
22724 /*
22725 ** Default permissions when creating auto proxy dir
22726 */
22727 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22728 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22729 #endif
22730
22731 /*
22732 ** Maximum supported path-length.
22733 */
22734 #define MAX_PATHNAME 512
22735
22736 /*
22737 ** Only set the lastErrno if the error code is a real error and not 
22738 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22739 */
22740 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22741
22742 /* Forward references */
22743 typedef struct unixShm unixShm;               /* Connection shared memory */
22744 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22745 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22746 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22747
22748 /*
22749 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22750 ** cannot be closed immediately. In these cases, instances of the following
22751 ** structure are used to store the file descriptor while waiting for an
22752 ** opportunity to either close or reuse it.
22753 */
22754 struct UnixUnusedFd {
22755   int fd;                   /* File descriptor to close */
22756   int flags;                /* Flags this file descriptor was opened with */
22757   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22758 };
22759
22760 /*
22761 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22762 ** VFS implementations.
22763 */
22764 typedef struct unixFile unixFile;
22765 struct unixFile {
22766   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22767   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
22768   unixInodeInfo *pInode;              /* Info about locks on this inode */
22769   int h;                              /* The file descriptor */
22770   unsigned char eFileLock;            /* The type of lock held on this fd */
22771   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
22772   int lastErrno;                      /* The unix errno from last I/O error */
22773   void *lockingContext;               /* Locking style specific state */
22774   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22775   const char *zPath;                  /* Name of the file */
22776   unixShm *pShm;                      /* Shared memory segment information */
22777   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22778 #if SQLITE_ENABLE_LOCKING_STYLE
22779   int openFlags;                      /* The flags specified at open() */
22780 #endif
22781 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22782   unsigned fsFlags;                   /* cached details from statfs() */
22783 #endif
22784 #if OS_VXWORKS
22785   struct vxworksFileId *pId;          /* Unique file ID */
22786 #endif
22787 #ifdef SQLITE_DEBUG
22788   /* The next group of variables are used to track whether or not the
22789   ** transaction counter in bytes 24-27 of database files are updated
22790   ** whenever any part of the database changes.  An assertion fault will
22791   ** occur if a file is updated without also updating the transaction
22792   ** counter.  This test is made to avoid new problems similar to the
22793   ** one described by ticket #3584. 
22794   */
22795   unsigned char transCntrChng;   /* True if the transaction counter changed */
22796   unsigned char dbUpdate;        /* True if any part of database file changed */
22797   unsigned char inNormalWrite;   /* True if in a normal write operation */
22798 #endif
22799 #ifdef SQLITE_TEST
22800   /* In test mode, increase the size of this structure a bit so that 
22801   ** it is larger than the struct CrashFile defined in test6.c.
22802   */
22803   char aPadding[32];
22804 #endif
22805 };
22806
22807 /*
22808 ** Allowed values for the unixFile.ctrlFlags bitmask:
22809 */
22810 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
22811 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
22812 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
22813 #ifndef SQLITE_DISABLE_DIRSYNC
22814 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
22815 #else
22816 # define UNIXFILE_DIRSYNC    0x00
22817 #endif
22818 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
22819 #define UNIXFILE_DELETE      0x20     /* Delete on close */
22820 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
22821 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
22822
22823 /*
22824 ** Include code that is common to all os_*.c files
22825 */
22826 /************** Include os_common.h in the middle of os_unix.c ***************/
22827 /************** Begin file os_common.h ***************************************/
22828 /*
22829 ** 2004 May 22
22830 **
22831 ** The author disclaims copyright to this source code.  In place of
22832 ** a legal notice, here is a blessing:
22833 **
22834 **    May you do good and not evil.
22835 **    May you find forgiveness for yourself and forgive others.
22836 **    May you share freely, never taking more than you give.
22837 **
22838 ******************************************************************************
22839 **
22840 ** This file contains macros and a little bit of code that is common to
22841 ** all of the platform-specific files (os_*.c) and is #included into those
22842 ** files.
22843 **
22844 ** This file should be #included by the os_*.c files only.  It is not a
22845 ** general purpose header file.
22846 */
22847 #ifndef _OS_COMMON_H_
22848 #define _OS_COMMON_H_
22849
22850 /*
22851 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22852 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22853 ** switch.  The following code should catch this problem at compile-time.
22854 */
22855 #ifdef MEMORY_DEBUG
22856 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22857 #endif
22858
22859 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22860 # ifndef SQLITE_DEBUG_OS_TRACE
22861 #   define SQLITE_DEBUG_OS_TRACE 0
22862 # endif
22863   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22864 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22865 #else
22866 # define OSTRACE(X)
22867 #endif
22868
22869 /*
22870 ** Macros for performance tracing.  Normally turned off.  Only works
22871 ** on i486 hardware.
22872 */
22873 #ifdef SQLITE_PERFORMANCE_TRACE
22874
22875 /* 
22876 ** hwtime.h contains inline assembler code for implementing 
22877 ** high-performance timing routines.
22878 */
22879 /************** Include hwtime.h in the middle of os_common.h ****************/
22880 /************** Begin file hwtime.h ******************************************/
22881 /*
22882 ** 2008 May 27
22883 **
22884 ** The author disclaims copyright to this source code.  In place of
22885 ** a legal notice, here is a blessing:
22886 **
22887 **    May you do good and not evil.
22888 **    May you find forgiveness for yourself and forgive others.
22889 **    May you share freely, never taking more than you give.
22890 **
22891 ******************************************************************************
22892 **
22893 ** This file contains inline asm code for retrieving "high-performance"
22894 ** counters for x86 class CPUs.
22895 */
22896 #ifndef _HWTIME_H_
22897 #define _HWTIME_H_
22898
22899 /*
22900 ** The following routine only works on pentium-class (or newer) processors.
22901 ** It uses the RDTSC opcode to read the cycle count value out of the
22902 ** processor and returns that value.  This can be used for high-res
22903 ** profiling.
22904 */
22905 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22906       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22907
22908   #if defined(__GNUC__)
22909
22910   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22911      unsigned int lo, hi;
22912      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22913      return (sqlite_uint64)hi << 32 | lo;
22914   }
22915
22916   #elif defined(_MSC_VER)
22917
22918   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22919      __asm {
22920         rdtsc
22921         ret       ; return value at EDX:EAX
22922      }
22923   }
22924
22925   #endif
22926
22927 #elif (defined(__GNUC__) && defined(__x86_64__))
22928
22929   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22930       unsigned long val;
22931       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22932       return val;
22933   }
22934  
22935 #elif (defined(__GNUC__) && defined(__ppc__))
22936
22937   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22938       unsigned long long retval;
22939       unsigned long junk;
22940       __asm__ __volatile__ ("\n\
22941           1:      mftbu   %1\n\
22942                   mftb    %L0\n\
22943                   mftbu   %0\n\
22944                   cmpw    %0,%1\n\
22945                   bne     1b"
22946                   : "=r" (retval), "=r" (junk));
22947       return retval;
22948   }
22949
22950 #else
22951
22952   #error Need implementation of sqlite3Hwtime() for your platform.
22953
22954   /*
22955   ** To compile without implementing sqlite3Hwtime() for your platform,
22956   ** you can remove the above #error and use the following
22957   ** stub function.  You will lose timing support for many
22958   ** of the debugging and testing utilities, but it should at
22959   ** least compile and run.
22960   */
22961 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22962
22963 #endif
22964
22965 #endif /* !defined(_HWTIME_H_) */
22966
22967 /************** End of hwtime.h **********************************************/
22968 /************** Continuing where we left off in os_common.h ******************/
22969
22970 static sqlite_uint64 g_start;
22971 static sqlite_uint64 g_elapsed;
22972 #define TIMER_START       g_start=sqlite3Hwtime()
22973 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22974 #define TIMER_ELAPSED     g_elapsed
22975 #else
22976 #define TIMER_START
22977 #define TIMER_END
22978 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22979 #endif
22980
22981 /*
22982 ** If we compile with the SQLITE_TEST macro set, then the following block
22983 ** of code will give us the ability to simulate a disk I/O error.  This
22984 ** is used for testing the I/O recovery logic.
22985 */
22986 #ifdef SQLITE_TEST
22987 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22988 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22989 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22990 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22991 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22992 SQLITE_API int sqlite3_diskfull_pending = 0;
22993 SQLITE_API int sqlite3_diskfull = 0;
22994 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22995 #define SimulateIOError(CODE)  \
22996   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22997        || sqlite3_io_error_pending-- == 1 )  \
22998               { local_ioerr(); CODE; }
22999 static void local_ioerr(){
23000   IOTRACE(("IOERR\n"));
23001   sqlite3_io_error_hit++;
23002   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23003 }
23004 #define SimulateDiskfullError(CODE) \
23005    if( sqlite3_diskfull_pending ){ \
23006      if( sqlite3_diskfull_pending == 1 ){ \
23007        local_ioerr(); \
23008        sqlite3_diskfull = 1; \
23009        sqlite3_io_error_hit = 1; \
23010        CODE; \
23011      }else{ \
23012        sqlite3_diskfull_pending--; \
23013      } \
23014    }
23015 #else
23016 #define SimulateIOErrorBenign(X)
23017 #define SimulateIOError(A)
23018 #define SimulateDiskfullError(A)
23019 #endif
23020
23021 /*
23022 ** When testing, keep a count of the number of open files.
23023 */
23024 #ifdef SQLITE_TEST
23025 SQLITE_API int sqlite3_open_file_count = 0;
23026 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23027 #else
23028 #define OpenCounter(X)
23029 #endif
23030
23031 #endif /* !defined(_OS_COMMON_H_) */
23032
23033 /************** End of os_common.h *******************************************/
23034 /************** Continuing where we left off in os_unix.c ********************/
23035
23036 /*
23037 ** Define various macros that are missing from some systems.
23038 */
23039 #ifndef O_LARGEFILE
23040 # define O_LARGEFILE 0
23041 #endif
23042 #ifdef SQLITE_DISABLE_LFS
23043 # undef O_LARGEFILE
23044 # define O_LARGEFILE 0
23045 #endif
23046 #ifndef O_NOFOLLOW
23047 # define O_NOFOLLOW 0
23048 #endif
23049 #ifndef O_BINARY
23050 # define O_BINARY 0
23051 #endif
23052
23053 /*
23054 ** The threadid macro resolves to the thread-id or to 0.  Used for
23055 ** testing and debugging only.
23056 */
23057 #if SQLITE_THREADSAFE
23058 #define threadid pthread_self()
23059 #else
23060 #define threadid 0
23061 #endif
23062
23063 /*
23064 ** Different Unix systems declare open() in different ways.  Same use
23065 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23066 ** The difference is important when using a pointer to the function.
23067 **
23068 ** The safest way to deal with the problem is to always use this wrapper
23069 ** which always has the same well-defined interface.
23070 */
23071 static int posixOpen(const char *zFile, int flags, int mode){
23072   return open(zFile, flags, mode);
23073 }
23074
23075 /*
23076 ** On some systems, calls to fchown() will trigger a message in a security
23077 ** log if they come from non-root processes.  So avoid calling fchown() if
23078 ** we are not running as root.
23079 */
23080 static int posixFchown(int fd, uid_t uid, gid_t gid){
23081   return geteuid() ? 0 : fchown(fd,uid,gid);
23082 }
23083
23084 /* Forward reference */
23085 static int openDirectory(const char*, int*);
23086
23087 /*
23088 ** Many system calls are accessed through pointer-to-functions so that
23089 ** they may be overridden at runtime to facilitate fault injection during
23090 ** testing and sandboxing.  The following array holds the names and pointers
23091 ** to all overrideable system calls.
23092 */
23093 static struct unix_syscall {
23094   const char *zName;            /* Name of the sytem call */
23095   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23096   sqlite3_syscall_ptr pDefault; /* Default value */
23097 } aSyscall[] = {
23098   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23099 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23100
23101   { "close",        (sqlite3_syscall_ptr)close,      0  },
23102 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23103
23104   { "access",       (sqlite3_syscall_ptr)access,     0  },
23105 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23106
23107   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23108 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23109
23110   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23111 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23112
23113 /*
23114 ** The DJGPP compiler environment looks mostly like Unix, but it
23115 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23116 ** that always succeeds.  This means that locking does not occur under
23117 ** DJGPP.  But it is DOS - what did you expect?
23118 */
23119 #ifdef __DJGPP__
23120   { "fstat",        0,                 0  },
23121 #define osFstat(a,b,c)    0
23122 #else     
23123   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23124 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23125 #endif
23126
23127   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23128 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23129
23130   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23131 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23132
23133   { "read",         (sqlite3_syscall_ptr)read,       0  },
23134 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23135
23136 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23137   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23138 #else
23139   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23140 #endif
23141 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23142
23143 #if defined(USE_PREAD64)
23144   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23145 #else
23146   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23147 #endif
23148 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23149
23150   { "write",        (sqlite3_syscall_ptr)write,      0  },
23151 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23152
23153 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23154   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23155 #else
23156   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23157 #endif
23158 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23159                     aSyscall[12].pCurrent)
23160
23161 #if defined(USE_PREAD64)
23162   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23163 #else
23164   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23165 #endif
23166 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23167                     aSyscall[13].pCurrent)
23168
23169 #if SQLITE_ENABLE_LOCKING_STYLE
23170   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23171 #else
23172   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
23173 #endif
23174 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23175
23176 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23177   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23178 #else
23179   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23180 #endif
23181 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23182
23183   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23184 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23185
23186   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23187 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23188
23189   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23190 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23191
23192   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23193 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23194
23195   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23196 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23197
23198   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
23199 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
23200
23201 }; /* End of the overrideable system calls */
23202
23203 /*
23204 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23205 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23206 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23207 ** system call named zName.
23208 */
23209 static int unixSetSystemCall(
23210   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23211   const char *zName,            /* Name of system call to override */
23212   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23213 ){
23214   unsigned int i;
23215   int rc = SQLITE_NOTFOUND;
23216
23217   UNUSED_PARAMETER(pNotUsed);
23218   if( zName==0 ){
23219     /* If no zName is given, restore all system calls to their default
23220     ** settings and return NULL
23221     */
23222     rc = SQLITE_OK;
23223     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23224       if( aSyscall[i].pDefault ){
23225         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23226       }
23227     }
23228   }else{
23229     /* If zName is specified, operate on only the one system call
23230     ** specified.
23231     */
23232     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23233       if( strcmp(zName, aSyscall[i].zName)==0 ){
23234         if( aSyscall[i].pDefault==0 ){
23235           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23236         }
23237         rc = SQLITE_OK;
23238         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23239         aSyscall[i].pCurrent = pNewFunc;
23240         break;
23241       }
23242     }
23243   }
23244   return rc;
23245 }
23246
23247 /*
23248 ** Return the value of a system call.  Return NULL if zName is not a
23249 ** recognized system call name.  NULL is also returned if the system call
23250 ** is currently undefined.
23251 */
23252 static sqlite3_syscall_ptr unixGetSystemCall(
23253   sqlite3_vfs *pNotUsed,
23254   const char *zName
23255 ){
23256   unsigned int i;
23257
23258   UNUSED_PARAMETER(pNotUsed);
23259   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23260     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23261   }
23262   return 0;
23263 }
23264
23265 /*
23266 ** Return the name of the first system call after zName.  If zName==NULL
23267 ** then return the name of the first system call.  Return NULL if zName
23268 ** is the last system call or if zName is not the name of a valid
23269 ** system call.
23270 */
23271 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23272   int i = -1;
23273
23274   UNUSED_PARAMETER(p);
23275   if( zName ){
23276     for(i=0; i<ArraySize(aSyscall)-1; i++){
23277       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23278     }
23279   }
23280   for(i++; i<ArraySize(aSyscall); i++){
23281     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23282   }
23283   return 0;
23284 }
23285
23286 /*
23287 ** Invoke open().  Do so multiple times, until it either succeeds or
23288 ** fails for some reason other than EINTR.
23289 **
23290 ** If the file creation mode "m" is 0 then set it to the default for
23291 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23292 ** 0644) as modified by the system umask.  If m is not 0, then
23293 ** make the file creation mode be exactly m ignoring the umask.
23294 **
23295 ** The m parameter will be non-zero only when creating -wal, -journal,
23296 ** and -shm files.  We want those files to have *exactly* the same
23297 ** permissions as their original database, unadulterated by the umask.
23298 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23299 ** transaction crashes and leaves behind hot journals, then any
23300 ** process that is able to write to the database will also be able to
23301 ** recover the hot journals.
23302 */
23303 static int robust_open(const char *z, int f, mode_t m){
23304   int fd;
23305   mode_t m2;
23306   mode_t origM = 0;
23307   if( m==0 ){
23308     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
23309   }else{
23310     m2 = m;
23311     origM = osUmask(0);
23312   }
23313   do{
23314 #if defined(O_CLOEXEC)
23315     fd = osOpen(z,f|O_CLOEXEC,m2);
23316 #else
23317     fd = osOpen(z,f,m2);
23318 #endif
23319   }while( fd<0 && errno==EINTR );
23320   if( m ){
23321     osUmask(origM);
23322   }
23323 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23324   if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23325 #endif
23326   return fd;
23327 }
23328
23329 /*
23330 ** Helper functions to obtain and relinquish the global mutex. The
23331 ** global mutex is used to protect the unixInodeInfo and
23332 ** vxworksFileId objects used by this file, all of which may be 
23333 ** shared by multiple threads.
23334 **
23335 ** Function unixMutexHeld() is used to assert() that the global mutex 
23336 ** is held when required. This function is only used as part of assert() 
23337 ** statements. e.g.
23338 **
23339 **   unixEnterMutex()
23340 **     assert( unixMutexHeld() );
23341 **   unixEnterLeave()
23342 */
23343 static void unixEnterMutex(void){
23344   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23345 }
23346 static void unixLeaveMutex(void){
23347   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23348 }
23349 #ifdef SQLITE_DEBUG
23350 static int unixMutexHeld(void) {
23351   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23352 }
23353 #endif
23354
23355
23356 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23357 /*
23358 ** Helper function for printing out trace information from debugging
23359 ** binaries. This returns the string represetation of the supplied
23360 ** integer lock-type.
23361 */
23362 static const char *azFileLock(int eFileLock){
23363   switch( eFileLock ){
23364     case NO_LOCK: return "NONE";
23365     case SHARED_LOCK: return "SHARED";
23366     case RESERVED_LOCK: return "RESERVED";
23367     case PENDING_LOCK: return "PENDING";
23368     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23369   }
23370   return "ERROR";
23371 }
23372 #endif
23373
23374 #ifdef SQLITE_LOCK_TRACE
23375 /*
23376 ** Print out information about all locking operations.
23377 **
23378 ** This routine is used for troubleshooting locks on multithreaded
23379 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23380 ** command-line option on the compiler.  This code is normally
23381 ** turned off.
23382 */
23383 static int lockTrace(int fd, int op, struct flock *p){
23384   char *zOpName, *zType;
23385   int s;
23386   int savedErrno;
23387   if( op==F_GETLK ){
23388     zOpName = "GETLK";
23389   }else if( op==F_SETLK ){
23390     zOpName = "SETLK";
23391   }else{
23392     s = osFcntl(fd, op, p);
23393     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23394     return s;
23395   }
23396   if( p->l_type==F_RDLCK ){
23397     zType = "RDLCK";
23398   }else if( p->l_type==F_WRLCK ){
23399     zType = "WRLCK";
23400   }else if( p->l_type==F_UNLCK ){
23401     zType = "UNLCK";
23402   }else{
23403     assert( 0 );
23404   }
23405   assert( p->l_whence==SEEK_SET );
23406   s = osFcntl(fd, op, p);
23407   savedErrno = errno;
23408   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23409      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23410      (int)p->l_pid, s);
23411   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23412     struct flock l2;
23413     l2 = *p;
23414     osFcntl(fd, F_GETLK, &l2);
23415     if( l2.l_type==F_RDLCK ){
23416       zType = "RDLCK";
23417     }else if( l2.l_type==F_WRLCK ){
23418       zType = "WRLCK";
23419     }else if( l2.l_type==F_UNLCK ){
23420       zType = "UNLCK";
23421     }else{
23422       assert( 0 );
23423     }
23424     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23425        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23426   }
23427   errno = savedErrno;
23428   return s;
23429 }
23430 #undef osFcntl
23431 #define osFcntl lockTrace
23432 #endif /* SQLITE_LOCK_TRACE */
23433
23434 /*
23435 ** Retry ftruncate() calls that fail due to EINTR
23436 */
23437 static int robust_ftruncate(int h, sqlite3_int64 sz){
23438   int rc;
23439   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23440   return rc;
23441 }
23442
23443 /*
23444 ** This routine translates a standard POSIX errno code into something
23445 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23446 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23447 ** and a variety of "please close the file descriptor NOW" errors into 
23448 ** SQLITE_IOERR
23449 ** 
23450 ** Errors during initialization of locks, or file system support for locks,
23451 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23452 */
23453 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23454   switch (posixError) {
23455 #if 0
23456   /* At one point this code was not commented out. In theory, this branch
23457   ** should never be hit, as this function should only be called after
23458   ** a locking-related function (i.e. fcntl()) has returned non-zero with
23459   ** the value of errno as the first argument. Since a system call has failed,
23460   ** errno should be non-zero.
23461   **
23462   ** Despite this, if errno really is zero, we still don't want to return
23463   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23464   ** propagated back to the caller. Commenting this branch out means errno==0
23465   ** will be handled by the "default:" case below.
23466   */
23467   case 0: 
23468     return SQLITE_OK;
23469 #endif
23470
23471   case EAGAIN:
23472   case ETIMEDOUT:
23473   case EBUSY:
23474   case EINTR:
23475   case ENOLCK:  
23476     /* random NFS retry error, unless during file system support 
23477      * introspection, in which it actually means what it says */
23478     return SQLITE_BUSY;
23479     
23480   case EACCES: 
23481     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23482     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23483         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23484         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23485         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23486       return SQLITE_BUSY;
23487     }
23488     /* else fall through */
23489   case EPERM: 
23490     return SQLITE_PERM;
23491     
23492   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23493   ** this module never makes such a call. And the code in SQLite itself 
23494   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23495   ** this case is also commented out. If the system does set errno to EDEADLK,
23496   ** the default SQLITE_IOERR_XXX code will be returned. */
23497 #if 0
23498   case EDEADLK:
23499     return SQLITE_IOERR_BLOCKED;
23500 #endif
23501     
23502 #if EOPNOTSUPP!=ENOTSUP
23503   case EOPNOTSUPP: 
23504     /* something went terribly awry, unless during file system support 
23505      * introspection, in which it actually means what it says */
23506 #endif
23507 #ifdef ENOTSUP
23508   case ENOTSUP: 
23509     /* invalid fd, unless during file system support introspection, in which 
23510      * it actually means what it says */
23511 #endif
23512   case EIO:
23513   case EBADF:
23514   case EINVAL:
23515   case ENOTCONN:
23516   case ENODEV:
23517   case ENXIO:
23518   case ENOENT:
23519 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23520   case ESTALE:
23521 #endif
23522   case ENOSYS:
23523     /* these should force the client to close the file and reconnect */
23524     
23525   default: 
23526     return sqliteIOErr;
23527   }
23528 }
23529
23530
23531
23532 /******************************************************************************
23533 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23534 **
23535 ** On most versions of unix, we can get a unique ID for a file by concatenating
23536 ** the device number and the inode number.  But this does not work on VxWorks.
23537 ** On VxWorks, a unique file id must be based on the canonical filename.
23538 **
23539 ** A pointer to an instance of the following structure can be used as a
23540 ** unique file ID in VxWorks.  Each instance of this structure contains
23541 ** a copy of the canonical filename.  There is also a reference count.  
23542 ** The structure is reclaimed when the number of pointers to it drops to
23543 ** zero.
23544 **
23545 ** There are never very many files open at one time and lookups are not
23546 ** a performance-critical path, so it is sufficient to put these
23547 ** structures on a linked list.
23548 */
23549 struct vxworksFileId {
23550   struct vxworksFileId *pNext;  /* Next in a list of them all */
23551   int nRef;                     /* Number of references to this one */
23552   int nName;                    /* Length of the zCanonicalName[] string */
23553   char *zCanonicalName;         /* Canonical filename */
23554 };
23555
23556 #if OS_VXWORKS
23557 /* 
23558 ** All unique filenames are held on a linked list headed by this
23559 ** variable:
23560 */
23561 static struct vxworksFileId *vxworksFileList = 0;
23562
23563 /*
23564 ** Simplify a filename into its canonical form
23565 ** by making the following changes:
23566 **
23567 **  * removing any trailing and duplicate /
23568 **  * convert /./ into just /
23569 **  * convert /A/../ where A is any simple name into just /
23570 **
23571 ** Changes are made in-place.  Return the new name length.
23572 **
23573 ** The original filename is in z[0..n-1].  Return the number of
23574 ** characters in the simplified name.
23575 */
23576 static int vxworksSimplifyName(char *z, int n){
23577   int i, j;
23578   while( n>1 && z[n-1]=='/' ){ n--; }
23579   for(i=j=0; i<n; i++){
23580     if( z[i]=='/' ){
23581       if( z[i+1]=='/' ) continue;
23582       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23583         i += 1;
23584         continue;
23585       }
23586       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23587         while( j>0 && z[j-1]!='/' ){ j--; }
23588         if( j>0 ){ j--; }
23589         i += 2;
23590         continue;
23591       }
23592     }
23593     z[j++] = z[i];
23594   }
23595   z[j] = 0;
23596   return j;
23597 }
23598
23599 /*
23600 ** Find a unique file ID for the given absolute pathname.  Return
23601 ** a pointer to the vxworksFileId object.  This pointer is the unique
23602 ** file ID.
23603 **
23604 ** The nRef field of the vxworksFileId object is incremented before
23605 ** the object is returned.  A new vxworksFileId object is created
23606 ** and added to the global list if necessary.
23607 **
23608 ** If a memory allocation error occurs, return NULL.
23609 */
23610 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23611   struct vxworksFileId *pNew;         /* search key and new file ID */
23612   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23613   int n;                              /* Length of zAbsoluteName string */
23614
23615   assert( zAbsoluteName[0]=='/' );
23616   n = (int)strlen(zAbsoluteName);
23617   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23618   if( pNew==0 ) return 0;
23619   pNew->zCanonicalName = (char*)&pNew[1];
23620   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23621   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23622
23623   /* Search for an existing entry that matching the canonical name.
23624   ** If found, increment the reference count and return a pointer to
23625   ** the existing file ID.
23626   */
23627   unixEnterMutex();
23628   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23629     if( pCandidate->nName==n 
23630      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23631     ){
23632        sqlite3_free(pNew);
23633        pCandidate->nRef++;
23634        unixLeaveMutex();
23635        return pCandidate;
23636     }
23637   }
23638
23639   /* No match was found.  We will make a new file ID */
23640   pNew->nRef = 1;
23641   pNew->nName = n;
23642   pNew->pNext = vxworksFileList;
23643   vxworksFileList = pNew;
23644   unixLeaveMutex();
23645   return pNew;
23646 }
23647
23648 /*
23649 ** Decrement the reference count on a vxworksFileId object.  Free
23650 ** the object when the reference count reaches zero.
23651 */
23652 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23653   unixEnterMutex();
23654   assert( pId->nRef>0 );
23655   pId->nRef--;
23656   if( pId->nRef==0 ){
23657     struct vxworksFileId **pp;
23658     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23659     assert( *pp==pId );
23660     *pp = pId->pNext;
23661     sqlite3_free(pId);
23662   }
23663   unixLeaveMutex();
23664 }
23665 #endif /* OS_VXWORKS */
23666 /*************** End of Unique File ID Utility Used By VxWorks ****************
23667 ******************************************************************************/
23668
23669
23670 /******************************************************************************
23671 *************************** Posix Advisory Locking ****************************
23672 **
23673 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23674 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23675 ** sets or clears a lock, that operation overrides any prior locks set
23676 ** by the same process.  It does not explicitly say so, but this implies
23677 ** that it overrides locks set by the same process using a different
23678 ** file descriptor.  Consider this test case:
23679 **
23680 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23681 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23682 **
23683 ** Suppose ./file1 and ./file2 are really the same file (because
23684 ** one is a hard or symbolic link to the other) then if you set
23685 ** an exclusive lock on fd1, then try to get an exclusive lock
23686 ** on fd2, it works.  I would have expected the second lock to
23687 ** fail since there was already a lock on the file due to fd1.
23688 ** But not so.  Since both locks came from the same process, the
23689 ** second overrides the first, even though they were on different
23690 ** file descriptors opened on different file names.
23691 **
23692 ** This means that we cannot use POSIX locks to synchronize file access
23693 ** among competing threads of the same process.  POSIX locks will work fine
23694 ** to synchronize access for threads in separate processes, but not
23695 ** threads within the same process.
23696 **
23697 ** To work around the problem, SQLite has to manage file locks internally
23698 ** on its own.  Whenever a new database is opened, we have to find the
23699 ** specific inode of the database file (the inode is determined by the
23700 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23701 ** and check for locks already existing on that inode.  When locks are
23702 ** created or removed, we have to look at our own internal record of the
23703 ** locks to see if another thread has previously set a lock on that same
23704 ** inode.
23705 **
23706 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23707 ** For VxWorks, we have to use the alternative unique ID system based on
23708 ** canonical filename and implemented in the previous division.)
23709 **
23710 ** The sqlite3_file structure for POSIX is no longer just an integer file
23711 ** descriptor.  It is now a structure that holds the integer file
23712 ** descriptor and a pointer to a structure that describes the internal
23713 ** locks on the corresponding inode.  There is one locking structure
23714 ** per inode, so if the same inode is opened twice, both unixFile structures
23715 ** point to the same locking structure.  The locking structure keeps
23716 ** a reference count (so we will know when to delete it) and a "cnt"
23717 ** field that tells us its internal lock status.  cnt==0 means the
23718 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23719 ** cnt>0 means there are cnt shared locks on the file.
23720 **
23721 ** Any attempt to lock or unlock a file first checks the locking
23722 ** structure.  The fcntl() system call is only invoked to set a 
23723 ** POSIX lock if the internal lock structure transitions between
23724 ** a locked and an unlocked state.
23725 **
23726 ** But wait:  there are yet more problems with POSIX advisory locks.
23727 **
23728 ** If you close a file descriptor that points to a file that has locks,
23729 ** all locks on that file that are owned by the current process are
23730 ** released.  To work around this problem, each unixInodeInfo object
23731 ** maintains a count of the number of pending locks on tha inode.
23732 ** When an attempt is made to close an unixFile, if there are
23733 ** other unixFile open on the same inode that are holding locks, the call
23734 ** to close() the file descriptor is deferred until all of the locks clear.
23735 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23736 ** be closed and that list is walked (and cleared) when the last lock
23737 ** clears.
23738 **
23739 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23740 **
23741 ** Many older versions of linux use the LinuxThreads library which is
23742 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23743 ** A cannot be modified or overridden by a different thread B.
23744 ** Only thread A can modify the lock.  Locking behavior is correct
23745 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23746 ** on linux - with NPTL a lock created by thread A can override locks
23747 ** in thread B.  But there is no way to know at compile-time which
23748 ** threading library is being used.  So there is no way to know at
23749 ** compile-time whether or not thread A can override locks on thread B.
23750 ** One has to do a run-time check to discover the behavior of the
23751 ** current process.
23752 **
23753 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23754 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23755 ** LinuxThreads provided that (1) there is no more than one connection 
23756 ** per database file in the same process and (2) database connections
23757 ** do not move across threads.
23758 */
23759
23760 /*
23761 ** An instance of the following structure serves as the key used
23762 ** to locate a particular unixInodeInfo object.
23763 */
23764 struct unixFileId {
23765   dev_t dev;                  /* Device number */
23766 #if OS_VXWORKS
23767   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23768 #else
23769   ino_t ino;                  /* Inode number */
23770 #endif
23771 };
23772
23773 /*
23774 ** An instance of the following structure is allocated for each open
23775 ** inode.  Or, on LinuxThreads, there is one of these structures for
23776 ** each inode opened by each thread.
23777 **
23778 ** A single inode can have multiple file descriptors, so each unixFile
23779 ** structure contains a pointer to an instance of this object and this
23780 ** object keeps a count of the number of unixFile pointing to it.
23781 */
23782 struct unixInodeInfo {
23783   struct unixFileId fileId;       /* The lookup key */
23784   int nShared;                    /* Number of SHARED locks held */
23785   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23786   unsigned char bProcessLock;     /* An exclusive process lock is held */
23787   int nRef;                       /* Number of pointers to this structure */
23788   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23789   int nLock;                      /* Number of outstanding file locks */
23790   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23791   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23792   unixInodeInfo *pPrev;           /*    .... doubly linked */
23793 #if SQLITE_ENABLE_LOCKING_STYLE
23794   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23795 #endif
23796 #if OS_VXWORKS
23797   sem_t *pSem;                    /* Named POSIX semaphore */
23798   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23799 #endif
23800 };
23801
23802 /*
23803 ** A lists of all unixInodeInfo objects.
23804 */
23805 static unixInodeInfo *inodeList = 0;
23806
23807 /*
23808 **
23809 ** This function - unixLogError_x(), is only ever called via the macro
23810 ** unixLogError().
23811 **
23812 ** It is invoked after an error occurs in an OS function and errno has been
23813 ** set. It logs a message using sqlite3_log() containing the current value of
23814 ** errno and, if possible, the human-readable equivalent from strerror() or
23815 ** strerror_r().
23816 **
23817 ** The first argument passed to the macro should be the error code that
23818 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
23819 ** The two subsequent arguments should be the name of the OS function that
23820 ** failed (e.g. "unlink", "open") and the associated file-system path,
23821 ** if any.
23822 */
23823 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
23824 static int unixLogErrorAtLine(
23825   int errcode,                    /* SQLite error code */
23826   const char *zFunc,              /* Name of OS function that failed */
23827   const char *zPath,              /* File path associated with error */
23828   int iLine                       /* Source line number where error occurred */
23829 ){
23830   char *zErr;                     /* Message from strerror() or equivalent */
23831   int iErrno = errno;             /* Saved syscall error number */
23832
23833   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
23834   ** the strerror() function to obtain the human-readable error message
23835   ** equivalent to errno. Otherwise, use strerror_r().
23836   */ 
23837 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
23838   char aErr[80];
23839   memset(aErr, 0, sizeof(aErr));
23840   zErr = aErr;
23841
23842   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
23843   ** assume that the system provides the GNU version of strerror_r() that
23844   ** returns a pointer to a buffer containing the error message. That pointer 
23845   ** may point to aErr[], or it may point to some static storage somewhere. 
23846   ** Otherwise, assume that the system provides the POSIX version of 
23847   ** strerror_r(), which always writes an error message into aErr[].
23848   **
23849   ** If the code incorrectly assumes that it is the POSIX version that is
23850   ** available, the error message will often be an empty string. Not a
23851   ** huge problem. Incorrectly concluding that the GNU version is available 
23852   ** could lead to a segfault though.
23853   */
23854 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
23855   zErr = 
23856 # endif
23857   strerror_r(iErrno, aErr, sizeof(aErr)-1);
23858
23859 #elif SQLITE_THREADSAFE
23860   /* This is a threadsafe build, but strerror_r() is not available. */
23861   zErr = "";
23862 #else
23863   /* Non-threadsafe build, use strerror(). */
23864   zErr = strerror(iErrno);
23865 #endif
23866
23867   assert( errcode!=SQLITE_OK );
23868   if( zPath==0 ) zPath = "";
23869   sqlite3_log(errcode,
23870       "os_unix.c:%d: (%d) %s(%s) - %s",
23871       iLine, iErrno, zFunc, zPath, zErr
23872   );
23873
23874   return errcode;
23875 }
23876
23877 /*
23878 ** Close a file descriptor.
23879 **
23880 ** We assume that close() almost always works, since it is only in a
23881 ** very sick application or on a very sick platform that it might fail.
23882 ** If it does fail, simply leak the file descriptor, but do log the
23883 ** error.
23884 **
23885 ** Note that it is not safe to retry close() after EINTR since the
23886 ** file descriptor might have already been reused by another thread.
23887 ** So we don't even try to recover from an EINTR.  Just log the error
23888 ** and move on.
23889 */
23890 static void robust_close(unixFile *pFile, int h, int lineno){
23891   if( osClose(h) ){
23892     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
23893                        pFile ? pFile->zPath : 0, lineno);
23894   }
23895 }
23896
23897 /*
23898 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23899 */ 
23900 static void closePendingFds(unixFile *pFile){
23901   unixInodeInfo *pInode = pFile->pInode;
23902   UnixUnusedFd *p;
23903   UnixUnusedFd *pNext;
23904   for(p=pInode->pUnused; p; p=pNext){
23905     pNext = p->pNext;
23906     robust_close(pFile, p->fd, __LINE__);
23907     sqlite3_free(p);
23908   }
23909   pInode->pUnused = 0;
23910 }
23911
23912 /*
23913 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23914 **
23915 ** The mutex entered using the unixEnterMutex() function must be held
23916 ** when this function is called.
23917 */
23918 static void releaseInodeInfo(unixFile *pFile){
23919   unixInodeInfo *pInode = pFile->pInode;
23920   assert( unixMutexHeld() );
23921   if( ALWAYS(pInode) ){
23922     pInode->nRef--;
23923     if( pInode->nRef==0 ){
23924       assert( pInode->pShmNode==0 );
23925       closePendingFds(pFile);
23926       if( pInode->pPrev ){
23927         assert( pInode->pPrev->pNext==pInode );
23928         pInode->pPrev->pNext = pInode->pNext;
23929       }else{
23930         assert( inodeList==pInode );
23931         inodeList = pInode->pNext;
23932       }
23933       if( pInode->pNext ){
23934         assert( pInode->pNext->pPrev==pInode );
23935         pInode->pNext->pPrev = pInode->pPrev;
23936       }
23937       sqlite3_free(pInode);
23938     }
23939   }
23940 }
23941
23942 /*
23943 ** Given a file descriptor, locate the unixInodeInfo object that
23944 ** describes that file descriptor.  Create a new one if necessary.  The
23945 ** return value might be uninitialized if an error occurs.
23946 **
23947 ** The mutex entered using the unixEnterMutex() function must be held
23948 ** when this function is called.
23949 **
23950 ** Return an appropriate error code.
23951 */
23952 static int findInodeInfo(
23953   unixFile *pFile,               /* Unix file with file desc used in the key */
23954   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23955 ){
23956   int rc;                        /* System call return code */
23957   int fd;                        /* The file descriptor for pFile */
23958   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23959   struct stat statbuf;           /* Low-level file information */
23960   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23961
23962   assert( unixMutexHeld() );
23963
23964   /* Get low-level information about the file that we can used to
23965   ** create a unique name for the file.
23966   */
23967   fd = pFile->h;
23968   rc = osFstat(fd, &statbuf);
23969   if( rc!=0 ){
23970     pFile->lastErrno = errno;
23971 #ifdef EOVERFLOW
23972     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23973 #endif
23974     return SQLITE_IOERR;
23975   }
23976
23977 #ifdef __APPLE__
23978   /* On OS X on an msdos filesystem, the inode number is reported
23979   ** incorrectly for zero-size files.  See ticket #3260.  To work
23980   ** around this problem (we consider it a bug in OS X, not SQLite)
23981   ** we always increase the file size to 1 by writing a single byte
23982   ** prior to accessing the inode number.  The one byte written is
23983   ** an ASCII 'S' character which also happens to be the first byte
23984   ** in the header of every SQLite database.  In this way, if there
23985   ** is a race condition such that another thread has already populated
23986   ** the first page of the database, no damage is done.
23987   */
23988   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23989     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
23990     if( rc!=1 ){
23991       pFile->lastErrno = errno;
23992       return SQLITE_IOERR;
23993     }
23994     rc = osFstat(fd, &statbuf);
23995     if( rc!=0 ){
23996       pFile->lastErrno = errno;
23997       return SQLITE_IOERR;
23998     }
23999   }
24000 #endif
24001
24002   memset(&fileId, 0, sizeof(fileId));
24003   fileId.dev = statbuf.st_dev;
24004 #if OS_VXWORKS
24005   fileId.pId = pFile->pId;
24006 #else
24007   fileId.ino = statbuf.st_ino;
24008 #endif
24009   pInode = inodeList;
24010   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24011     pInode = pInode->pNext;
24012   }
24013   if( pInode==0 ){
24014     pInode = sqlite3_malloc( sizeof(*pInode) );
24015     if( pInode==0 ){
24016       return SQLITE_NOMEM;
24017     }
24018     memset(pInode, 0, sizeof(*pInode));
24019     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24020     pInode->nRef = 1;
24021     pInode->pNext = inodeList;
24022     pInode->pPrev = 0;
24023     if( inodeList ) inodeList->pPrev = pInode;
24024     inodeList = pInode;
24025   }else{
24026     pInode->nRef++;
24027   }
24028   *ppInode = pInode;
24029   return SQLITE_OK;
24030 }
24031
24032
24033 /*
24034 ** This routine checks if there is a RESERVED lock held on the specified
24035 ** file by this or any other process. If such a lock is held, set *pResOut
24036 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24037 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24038 */
24039 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24040   int rc = SQLITE_OK;
24041   int reserved = 0;
24042   unixFile *pFile = (unixFile*)id;
24043
24044   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24045
24046   assert( pFile );
24047   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24048
24049   /* Check if a thread in this process holds such a lock */
24050   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24051     reserved = 1;
24052   }
24053
24054   /* Otherwise see if some other process holds it.
24055   */
24056 #ifndef __DJGPP__
24057   if( !reserved && !pFile->pInode->bProcessLock ){
24058     struct flock lock;
24059     lock.l_whence = SEEK_SET;
24060     lock.l_start = RESERVED_BYTE;
24061     lock.l_len = 1;
24062     lock.l_type = F_WRLCK;
24063     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24064       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24065       pFile->lastErrno = errno;
24066     } else if( lock.l_type!=F_UNLCK ){
24067       reserved = 1;
24068     }
24069   }
24070 #endif
24071   
24072   unixLeaveMutex();
24073   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24074
24075   *pResOut = reserved;
24076   return rc;
24077 }
24078
24079 /*
24080 ** Attempt to set a system-lock on the file pFile.  The lock is 
24081 ** described by pLock.
24082 **
24083 ** If the pFile was opened read/write from unix-excl, then the only lock
24084 ** ever obtained is an exclusive lock, and it is obtained exactly once
24085 ** the first time any lock is attempted.  All subsequent system locking
24086 ** operations become no-ops.  Locking operations still happen internally,
24087 ** in order to coordinate access between separate database connections
24088 ** within this process, but all of that is handled in memory and the
24089 ** operating system does not participate.
24090 **
24091 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24092 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24093 ** and is read-only.
24094 **
24095 ** Zero is returned if the call completes successfully, or -1 if a call
24096 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24097 */
24098 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24099   int rc;
24100   unixInodeInfo *pInode = pFile->pInode;
24101   assert( unixMutexHeld() );
24102   assert( pInode!=0 );
24103   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24104    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24105   ){
24106     if( pInode->bProcessLock==0 ){
24107       struct flock lock;
24108       assert( pInode->nLock==0 );
24109       lock.l_whence = SEEK_SET;
24110       lock.l_start = SHARED_FIRST;
24111       lock.l_len = SHARED_SIZE;
24112       lock.l_type = F_WRLCK;
24113       rc = osFcntl(pFile->h, F_SETLK, &lock);
24114       if( rc<0 ) return rc;
24115       pInode->bProcessLock = 1;
24116       pInode->nLock++;
24117     }else{
24118       rc = 0;
24119     }
24120   }else{
24121     rc = osFcntl(pFile->h, F_SETLK, pLock);
24122   }
24123   return rc;
24124 }
24125
24126 /*
24127 ** Lock the file with the lock specified by parameter eFileLock - one
24128 ** of the following:
24129 **
24130 **     (1) SHARED_LOCK
24131 **     (2) RESERVED_LOCK
24132 **     (3) PENDING_LOCK
24133 **     (4) EXCLUSIVE_LOCK
24134 **
24135 ** Sometimes when requesting one lock state, additional lock states
24136 ** are inserted in between.  The locking might fail on one of the later
24137 ** transitions leaving the lock state different from what it started but
24138 ** still short of its goal.  The following chart shows the allowed
24139 ** transitions and the inserted intermediate states:
24140 **
24141 **    UNLOCKED -> SHARED
24142 **    SHARED -> RESERVED
24143 **    SHARED -> (PENDING) -> EXCLUSIVE
24144 **    RESERVED -> (PENDING) -> EXCLUSIVE
24145 **    PENDING -> EXCLUSIVE
24146 **
24147 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24148 ** routine to lower a locking level.
24149 */
24150 static int unixLock(sqlite3_file *id, int eFileLock){
24151   /* The following describes the implementation of the various locks and
24152   ** lock transitions in terms of the POSIX advisory shared and exclusive
24153   ** lock primitives (called read-locks and write-locks below, to avoid
24154   ** confusion with SQLite lock names). The algorithms are complicated
24155   ** slightly in order to be compatible with windows systems simultaneously
24156   ** accessing the same database file, in case that is ever required.
24157   **
24158   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24159   ** byte', each single bytes at well known offsets, and the 'shared byte
24160   ** range', a range of 510 bytes at a well known offset.
24161   **
24162   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24163   ** byte'.  If this is successful, a random byte from the 'shared byte
24164   ** range' is read-locked and the lock on the 'pending byte' released.
24165   **
24166   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24167   ** A RESERVED lock is implemented by grabbing a write-lock on the
24168   ** 'reserved byte'. 
24169   **
24170   ** A process may only obtain a PENDING lock after it has obtained a
24171   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24172   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24173   ** obtained, but existing SHARED locks are allowed to persist. A process
24174   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24175   ** This property is used by the algorithm for rolling back a journal file
24176   ** after a crash.
24177   **
24178   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24179   ** implemented by obtaining a write-lock on the entire 'shared byte
24180   ** range'. Since all other locks require a read-lock on one of the bytes
24181   ** within this range, this ensures that no other locks are held on the
24182   ** database. 
24183   **
24184   ** The reason a single byte cannot be used instead of the 'shared byte
24185   ** range' is that some versions of windows do not support read-locks. By
24186   ** locking a random byte from a range, concurrent SHARED locks may exist
24187   ** even if the locking primitive used is always a write-lock.
24188   */
24189   int rc = SQLITE_OK;
24190   unixFile *pFile = (unixFile*)id;
24191   unixInodeInfo *pInode;
24192   struct flock lock;
24193   int tErrno = 0;
24194
24195   assert( pFile );
24196   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24197       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24198       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24199
24200   /* If there is already a lock of this type or more restrictive on the
24201   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24202   ** unixEnterMutex() hasn't been called yet.
24203   */
24204   if( pFile->eFileLock>=eFileLock ){
24205     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24206             azFileLock(eFileLock)));
24207     return SQLITE_OK;
24208   }
24209
24210   /* Make sure the locking sequence is correct.
24211   **  (1) We never move from unlocked to anything higher than shared lock.
24212   **  (2) SQLite never explicitly requests a pendig lock.
24213   **  (3) A shared lock is always held when a reserve lock is requested.
24214   */
24215   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24216   assert( eFileLock!=PENDING_LOCK );
24217   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24218
24219   /* This mutex is needed because pFile->pInode is shared across threads
24220   */
24221   unixEnterMutex();
24222   pInode = pFile->pInode;
24223
24224   /* If some thread using this PID has a lock via a different unixFile*
24225   ** handle that precludes the requested lock, return BUSY.
24226   */
24227   if( (pFile->eFileLock!=pInode->eFileLock && 
24228           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24229   ){
24230     rc = SQLITE_BUSY;
24231     goto end_lock;
24232   }
24233
24234   /* If a SHARED lock is requested, and some thread using this PID already
24235   ** has a SHARED or RESERVED lock, then increment reference counts and
24236   ** return SQLITE_OK.
24237   */
24238   if( eFileLock==SHARED_LOCK && 
24239       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24240     assert( eFileLock==SHARED_LOCK );
24241     assert( pFile->eFileLock==0 );
24242     assert( pInode->nShared>0 );
24243     pFile->eFileLock = SHARED_LOCK;
24244     pInode->nShared++;
24245     pInode->nLock++;
24246     goto end_lock;
24247   }
24248
24249
24250   /* A PENDING lock is needed before acquiring a SHARED lock and before
24251   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24252   ** be released.
24253   */
24254   lock.l_len = 1L;
24255   lock.l_whence = SEEK_SET;
24256   if( eFileLock==SHARED_LOCK 
24257       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24258   ){
24259     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24260     lock.l_start = PENDING_BYTE;
24261     if( unixFileLock(pFile, &lock) ){
24262       tErrno = errno;
24263       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24264       if( rc!=SQLITE_BUSY ){
24265         pFile->lastErrno = tErrno;
24266       }
24267       goto end_lock;
24268     }
24269   }
24270
24271
24272   /* If control gets to this point, then actually go ahead and make
24273   ** operating system calls for the specified lock.
24274   */
24275   if( eFileLock==SHARED_LOCK ){
24276     assert( pInode->nShared==0 );
24277     assert( pInode->eFileLock==0 );
24278     assert( rc==SQLITE_OK );
24279
24280     /* Now get the read-lock */
24281     lock.l_start = SHARED_FIRST;
24282     lock.l_len = SHARED_SIZE;
24283     if( unixFileLock(pFile, &lock) ){
24284       tErrno = errno;
24285       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24286     }
24287
24288     /* Drop the temporary PENDING lock */
24289     lock.l_start = PENDING_BYTE;
24290     lock.l_len = 1L;
24291     lock.l_type = F_UNLCK;
24292     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24293       /* This could happen with a network mount */
24294       tErrno = errno;
24295       rc = SQLITE_IOERR_UNLOCK; 
24296     }
24297
24298     if( rc ){
24299       if( rc!=SQLITE_BUSY ){
24300         pFile->lastErrno = tErrno;
24301       }
24302       goto end_lock;
24303     }else{
24304       pFile->eFileLock = SHARED_LOCK;
24305       pInode->nLock++;
24306       pInode->nShared = 1;
24307     }
24308   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24309     /* We are trying for an exclusive lock but another thread in this
24310     ** same process is still holding a shared lock. */
24311     rc = SQLITE_BUSY;
24312   }else{
24313     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24314     ** assumed that there is a SHARED or greater lock on the file
24315     ** already.
24316     */
24317     assert( 0!=pFile->eFileLock );
24318     lock.l_type = F_WRLCK;
24319
24320     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24321     if( eFileLock==RESERVED_LOCK ){
24322       lock.l_start = RESERVED_BYTE;
24323       lock.l_len = 1L;
24324     }else{
24325       lock.l_start = SHARED_FIRST;
24326       lock.l_len = SHARED_SIZE;
24327     }
24328
24329     if( unixFileLock(pFile, &lock) ){
24330       tErrno = errno;
24331       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24332       if( rc!=SQLITE_BUSY ){
24333         pFile->lastErrno = tErrno;
24334       }
24335     }
24336   }
24337   
24338
24339 #ifdef SQLITE_DEBUG
24340   /* Set up the transaction-counter change checking flags when
24341   ** transitioning from a SHARED to a RESERVED lock.  The change
24342   ** from SHARED to RESERVED marks the beginning of a normal
24343   ** write operation (not a hot journal rollback).
24344   */
24345   if( rc==SQLITE_OK
24346    && pFile->eFileLock<=SHARED_LOCK
24347    && eFileLock==RESERVED_LOCK
24348   ){
24349     pFile->transCntrChng = 0;
24350     pFile->dbUpdate = 0;
24351     pFile->inNormalWrite = 1;
24352   }
24353 #endif
24354
24355
24356   if( rc==SQLITE_OK ){
24357     pFile->eFileLock = eFileLock;
24358     pInode->eFileLock = eFileLock;
24359   }else if( eFileLock==EXCLUSIVE_LOCK ){
24360     pFile->eFileLock = PENDING_LOCK;
24361     pInode->eFileLock = PENDING_LOCK;
24362   }
24363
24364 end_lock:
24365   unixLeaveMutex();
24366   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24367       rc==SQLITE_OK ? "ok" : "failed"));
24368   return rc;
24369 }
24370
24371 /*
24372 ** Add the file descriptor used by file handle pFile to the corresponding
24373 ** pUnused list.
24374 */
24375 static void setPendingFd(unixFile *pFile){
24376   unixInodeInfo *pInode = pFile->pInode;
24377   UnixUnusedFd *p = pFile->pUnused;
24378   p->pNext = pInode->pUnused;
24379   pInode->pUnused = p;
24380   pFile->h = -1;
24381   pFile->pUnused = 0;
24382 }
24383
24384 /*
24385 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24386 ** must be either NO_LOCK or SHARED_LOCK.
24387 **
24388 ** If the locking level of the file descriptor is already at or below
24389 ** the requested locking level, this routine is a no-op.
24390 ** 
24391 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24392 ** the byte range is divided into 2 parts and the first part is unlocked then
24393 ** set to a read lock, then the other part is simply unlocked.  This works 
24394 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24395 ** remove the write lock on a region when a read lock is set.
24396 */
24397 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24398   unixFile *pFile = (unixFile*)id;
24399   unixInodeInfo *pInode;
24400   struct flock lock;
24401   int rc = SQLITE_OK;
24402
24403   assert( pFile );
24404   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24405       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24406       getpid()));
24407
24408   assert( eFileLock<=SHARED_LOCK );
24409   if( pFile->eFileLock<=eFileLock ){
24410     return SQLITE_OK;
24411   }
24412   unixEnterMutex();
24413   pInode = pFile->pInode;
24414   assert( pInode->nShared!=0 );
24415   if( pFile->eFileLock>SHARED_LOCK ){
24416     assert( pInode->eFileLock==pFile->eFileLock );
24417
24418 #ifdef SQLITE_DEBUG
24419     /* When reducing a lock such that other processes can start
24420     ** reading the database file again, make sure that the
24421     ** transaction counter was updated if any part of the database
24422     ** file changed.  If the transaction counter is not updated,
24423     ** other connections to the same file might not realize that
24424     ** the file has changed and hence might not know to flush their
24425     ** cache.  The use of a stale cache can lead to database corruption.
24426     */
24427     pFile->inNormalWrite = 0;
24428 #endif
24429
24430     /* downgrading to a shared lock on NFS involves clearing the write lock
24431     ** before establishing the readlock - to avoid a race condition we downgrade
24432     ** the lock in 2 blocks, so that part of the range will be covered by a 
24433     ** write lock until the rest is covered by a read lock:
24434     **  1:   [WWWWW]
24435     **  2:   [....W]
24436     **  3:   [RRRRW]
24437     **  4:   [RRRR.]
24438     */
24439     if( eFileLock==SHARED_LOCK ){
24440
24441 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24442       (void)handleNFSUnlock;
24443       assert( handleNFSUnlock==0 );
24444 #endif
24445 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24446       if( handleNFSUnlock ){
24447         int tErrno;               /* Error code from system call errors */
24448         off_t divSize = SHARED_SIZE - 1;
24449         
24450         lock.l_type = F_UNLCK;
24451         lock.l_whence = SEEK_SET;
24452         lock.l_start = SHARED_FIRST;
24453         lock.l_len = divSize;
24454         if( unixFileLock(pFile, &lock)==(-1) ){
24455           tErrno = errno;
24456           rc = SQLITE_IOERR_UNLOCK;
24457           if( IS_LOCK_ERROR(rc) ){
24458             pFile->lastErrno = tErrno;
24459           }
24460           goto end_unlock;
24461         }
24462         lock.l_type = F_RDLCK;
24463         lock.l_whence = SEEK_SET;
24464         lock.l_start = SHARED_FIRST;
24465         lock.l_len = divSize;
24466         if( unixFileLock(pFile, &lock)==(-1) ){
24467           tErrno = errno;
24468           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24469           if( IS_LOCK_ERROR(rc) ){
24470             pFile->lastErrno = tErrno;
24471           }
24472           goto end_unlock;
24473         }
24474         lock.l_type = F_UNLCK;
24475         lock.l_whence = SEEK_SET;
24476         lock.l_start = SHARED_FIRST+divSize;
24477         lock.l_len = SHARED_SIZE-divSize;
24478         if( unixFileLock(pFile, &lock)==(-1) ){
24479           tErrno = errno;
24480           rc = SQLITE_IOERR_UNLOCK;
24481           if( IS_LOCK_ERROR(rc) ){
24482             pFile->lastErrno = tErrno;
24483           }
24484           goto end_unlock;
24485         }
24486       }else
24487 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24488       {
24489         lock.l_type = F_RDLCK;
24490         lock.l_whence = SEEK_SET;
24491         lock.l_start = SHARED_FIRST;
24492         lock.l_len = SHARED_SIZE;
24493         if( unixFileLock(pFile, &lock) ){
24494           /* In theory, the call to unixFileLock() cannot fail because another
24495           ** process is holding an incompatible lock. If it does, this 
24496           ** indicates that the other process is not following the locking
24497           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24498           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
24499           ** an assert to fail). */ 
24500           rc = SQLITE_IOERR_RDLOCK;
24501           pFile->lastErrno = errno;
24502           goto end_unlock;
24503         }
24504       }
24505     }
24506     lock.l_type = F_UNLCK;
24507     lock.l_whence = SEEK_SET;
24508     lock.l_start = PENDING_BYTE;
24509     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24510     if( unixFileLock(pFile, &lock)==0 ){
24511       pInode->eFileLock = SHARED_LOCK;
24512     }else{
24513       rc = SQLITE_IOERR_UNLOCK;
24514       pFile->lastErrno = errno;
24515       goto end_unlock;
24516     }
24517   }
24518   if( eFileLock==NO_LOCK ){
24519     /* Decrement the shared lock counter.  Release the lock using an
24520     ** OS call only when all threads in this same process have released
24521     ** the lock.
24522     */
24523     pInode->nShared--;
24524     if( pInode->nShared==0 ){
24525       lock.l_type = F_UNLCK;
24526       lock.l_whence = SEEK_SET;
24527       lock.l_start = lock.l_len = 0L;
24528       if( unixFileLock(pFile, &lock)==0 ){
24529         pInode->eFileLock = NO_LOCK;
24530       }else{
24531         rc = SQLITE_IOERR_UNLOCK;
24532         pFile->lastErrno = errno;
24533         pInode->eFileLock = NO_LOCK;
24534         pFile->eFileLock = NO_LOCK;
24535       }
24536     }
24537
24538     /* Decrement the count of locks against this same file.  When the
24539     ** count reaches zero, close any other file descriptors whose close
24540     ** was deferred because of outstanding locks.
24541     */
24542     pInode->nLock--;
24543     assert( pInode->nLock>=0 );
24544     if( pInode->nLock==0 ){
24545       closePendingFds(pFile);
24546     }
24547   }
24548
24549 end_unlock:
24550   unixLeaveMutex();
24551   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24552   return rc;
24553 }
24554
24555 /*
24556 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24557 ** must be either NO_LOCK or SHARED_LOCK.
24558 **
24559 ** If the locking level of the file descriptor is already at or below
24560 ** the requested locking level, this routine is a no-op.
24561 */
24562 static int unixUnlock(sqlite3_file *id, int eFileLock){
24563   return posixUnlock(id, eFileLock, 0);
24564 }
24565
24566 /*
24567 ** This function performs the parts of the "close file" operation 
24568 ** common to all locking schemes. It closes the directory and file
24569 ** handles, if they are valid, and sets all fields of the unixFile
24570 ** structure to 0.
24571 **
24572 ** It is *not* necessary to hold the mutex when this routine is called,
24573 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24574 ** vxworksReleaseFileId() routine.
24575 */
24576 static int closeUnixFile(sqlite3_file *id){
24577   unixFile *pFile = (unixFile*)id;
24578   if( pFile->h>=0 ){
24579     robust_close(pFile, pFile->h, __LINE__);
24580     pFile->h = -1;
24581   }
24582 #if OS_VXWORKS
24583   if( pFile->pId ){
24584     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24585       osUnlink(pFile->pId->zCanonicalName);
24586     }
24587     vxworksReleaseFileId(pFile->pId);
24588     pFile->pId = 0;
24589   }
24590 #endif
24591   OSTRACE(("CLOSE   %-3d\n", pFile->h));
24592   OpenCounter(-1);
24593   sqlite3_free(pFile->pUnused);
24594   memset(pFile, 0, sizeof(unixFile));
24595   return SQLITE_OK;
24596 }
24597
24598 /*
24599 ** Close a file.
24600 */
24601 static int unixClose(sqlite3_file *id){
24602   int rc = SQLITE_OK;
24603   unixFile *pFile = (unixFile *)id;
24604   unixUnlock(id, NO_LOCK);
24605   unixEnterMutex();
24606
24607   /* unixFile.pInode is always valid here. Otherwise, a different close
24608   ** routine (e.g. nolockClose()) would be called instead.
24609   */
24610   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
24611   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
24612     /* If there are outstanding locks, do not actually close the file just
24613     ** yet because that would clear those locks.  Instead, add the file
24614     ** descriptor to pInode->pUnused list.  It will be automatically closed 
24615     ** when the last lock is cleared.
24616     */
24617     setPendingFd(pFile);
24618   }
24619   releaseInodeInfo(pFile);
24620   rc = closeUnixFile(id);
24621   unixLeaveMutex();
24622   return rc;
24623 }
24624
24625 /************** End of the posix advisory lock implementation *****************
24626 ******************************************************************************/
24627
24628 /******************************************************************************
24629 ****************************** No-op Locking **********************************
24630 **
24631 ** Of the various locking implementations available, this is by far the
24632 ** simplest:  locking is ignored.  No attempt is made to lock the database
24633 ** file for reading or writing.
24634 **
24635 ** This locking mode is appropriate for use on read-only databases
24636 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24637 ** also be used if the application employs some external mechanism to
24638 ** prevent simultaneous access of the same database by two or more
24639 ** database connections.  But there is a serious risk of database
24640 ** corruption if this locking mode is used in situations where multiple
24641 ** database connections are accessing the same database file at the same
24642 ** time and one or more of those connections are writing.
24643 */
24644
24645 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24646   UNUSED_PARAMETER(NotUsed);
24647   *pResOut = 0;
24648   return SQLITE_OK;
24649 }
24650 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24651   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24652   return SQLITE_OK;
24653 }
24654 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24655   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24656   return SQLITE_OK;
24657 }
24658
24659 /*
24660 ** Close the file.
24661 */
24662 static int nolockClose(sqlite3_file *id) {
24663   return closeUnixFile(id);
24664 }
24665
24666 /******************* End of the no-op lock implementation *********************
24667 ******************************************************************************/
24668
24669 /******************************************************************************
24670 ************************* Begin dot-file Locking ******************************
24671 **
24672 ** The dotfile locking implementation uses the existance of separate lock
24673 ** files (really a directory) to control access to the database.  This works
24674 ** on just about every filesystem imaginable.  But there are serious downsides:
24675 **
24676 **    (1)  There is zero concurrency.  A single reader blocks all other
24677 **         connections from reading or writing the database.
24678 **
24679 **    (2)  An application crash or power loss can leave stale lock files
24680 **         sitting around that need to be cleared manually.
24681 **
24682 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24683 ** other locking strategy is available.
24684 **
24685 ** Dotfile locking works by creating a subdirectory in the same directory as
24686 ** the database and with the same name but with a ".lock" extension added.
24687 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
24688 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24689 */
24690
24691 /*
24692 ** The file suffix added to the data base filename in order to create the
24693 ** lock directory.
24694 */
24695 #define DOTLOCK_SUFFIX ".lock"
24696
24697 /*
24698 ** This routine checks if there is a RESERVED lock held on the specified
24699 ** file by this or any other process. If such a lock is held, set *pResOut
24700 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24701 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24702 **
24703 ** In dotfile locking, either a lock exists or it does not.  So in this
24704 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24705 ** is held on the file and false if the file is unlocked.
24706 */
24707 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24708   int rc = SQLITE_OK;
24709   int reserved = 0;
24710   unixFile *pFile = (unixFile*)id;
24711
24712   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24713   
24714   assert( pFile );
24715
24716   /* Check if a thread in this process holds such a lock */
24717   if( pFile->eFileLock>SHARED_LOCK ){
24718     /* Either this connection or some other connection in the same process
24719     ** holds a lock on the file.  No need to check further. */
24720     reserved = 1;
24721   }else{
24722     /* The lock is held if and only if the lockfile exists */
24723     const char *zLockFile = (const char*)pFile->lockingContext;
24724     reserved = osAccess(zLockFile, 0)==0;
24725   }
24726   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24727   *pResOut = reserved;
24728   return rc;
24729 }
24730
24731 /*
24732 ** Lock the file with the lock specified by parameter eFileLock - one
24733 ** of the following:
24734 **
24735 **     (1) SHARED_LOCK
24736 **     (2) RESERVED_LOCK
24737 **     (3) PENDING_LOCK
24738 **     (4) EXCLUSIVE_LOCK
24739 **
24740 ** Sometimes when requesting one lock state, additional lock states
24741 ** are inserted in between.  The locking might fail on one of the later
24742 ** transitions leaving the lock state different from what it started but
24743 ** still short of its goal.  The following chart shows the allowed
24744 ** transitions and the inserted intermediate states:
24745 **
24746 **    UNLOCKED -> SHARED
24747 **    SHARED -> RESERVED
24748 **    SHARED -> (PENDING) -> EXCLUSIVE
24749 **    RESERVED -> (PENDING) -> EXCLUSIVE
24750 **    PENDING -> EXCLUSIVE
24751 **
24752 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24753 ** routine to lower a locking level.
24754 **
24755 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24756 ** But we track the other locking levels internally.
24757 */
24758 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24759   unixFile *pFile = (unixFile*)id;
24760   char *zLockFile = (char *)pFile->lockingContext;
24761   int rc = SQLITE_OK;
24762
24763
24764   /* If we have any lock, then the lock file already exists.  All we have
24765   ** to do is adjust our internal record of the lock level.
24766   */
24767   if( pFile->eFileLock > NO_LOCK ){
24768     pFile->eFileLock = eFileLock;
24769     /* Always update the timestamp on the old file */
24770 #ifdef HAVE_UTIME
24771     utime(zLockFile, NULL);
24772 #else
24773     utimes(zLockFile, NULL);
24774 #endif
24775     return SQLITE_OK;
24776   }
24777   
24778   /* grab an exclusive lock */
24779   rc = osMkdir(zLockFile, 0777);
24780   if( rc<0 ){
24781     /* failed to open/create the lock directory */
24782     int tErrno = errno;
24783     if( EEXIST == tErrno ){
24784       rc = SQLITE_BUSY;
24785     } else {
24786       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24787       if( IS_LOCK_ERROR(rc) ){
24788         pFile->lastErrno = tErrno;
24789       }
24790     }
24791     return rc;
24792   } 
24793   
24794   /* got it, set the type and return ok */
24795   pFile->eFileLock = eFileLock;
24796   return rc;
24797 }
24798
24799 /*
24800 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24801 ** must be either NO_LOCK or SHARED_LOCK.
24802 **
24803 ** If the locking level of the file descriptor is already at or below
24804 ** the requested locking level, this routine is a no-op.
24805 **
24806 ** When the locking level reaches NO_LOCK, delete the lock file.
24807 */
24808 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24809   unixFile *pFile = (unixFile*)id;
24810   char *zLockFile = (char *)pFile->lockingContext;
24811   int rc;
24812
24813   assert( pFile );
24814   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24815            pFile->eFileLock, getpid()));
24816   assert( eFileLock<=SHARED_LOCK );
24817   
24818   /* no-op if possible */
24819   if( pFile->eFileLock==eFileLock ){
24820     return SQLITE_OK;
24821   }
24822
24823   /* To downgrade to shared, simply update our internal notion of the
24824   ** lock state.  No need to mess with the file on disk.
24825   */
24826   if( eFileLock==SHARED_LOCK ){
24827     pFile->eFileLock = SHARED_LOCK;
24828     return SQLITE_OK;
24829   }
24830   
24831   /* To fully unlock the database, delete the lock file */
24832   assert( eFileLock==NO_LOCK );
24833   rc = osRmdir(zLockFile);
24834   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
24835   if( rc<0 ){
24836     int tErrno = errno;
24837     rc = 0;
24838     if( ENOENT != tErrno ){
24839       rc = SQLITE_IOERR_UNLOCK;
24840     }
24841     if( IS_LOCK_ERROR(rc) ){
24842       pFile->lastErrno = tErrno;
24843     }
24844     return rc; 
24845   }
24846   pFile->eFileLock = NO_LOCK;
24847   return SQLITE_OK;
24848 }
24849
24850 /*
24851 ** Close a file.  Make sure the lock has been released before closing.
24852 */
24853 static int dotlockClose(sqlite3_file *id) {
24854   int rc;
24855   if( id ){
24856     unixFile *pFile = (unixFile*)id;
24857     dotlockUnlock(id, NO_LOCK);
24858     sqlite3_free(pFile->lockingContext);
24859   }
24860   rc = closeUnixFile(id);
24861   return rc;
24862 }
24863 /****************** End of the dot-file lock implementation *******************
24864 ******************************************************************************/
24865
24866 /******************************************************************************
24867 ************************** Begin flock Locking ********************************
24868 **
24869 ** Use the flock() system call to do file locking.
24870 **
24871 ** flock() locking is like dot-file locking in that the various
24872 ** fine-grain locking levels supported by SQLite are collapsed into
24873 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24874 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24875 ** still works when you do this, but concurrency is reduced since
24876 ** only a single process can be reading the database at a time.
24877 **
24878 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24879 ** compiling for VXWORKS.
24880 */
24881 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24882
24883 /*
24884 ** Retry flock() calls that fail with EINTR
24885 */
24886 #ifdef EINTR
24887 static int robust_flock(int fd, int op){
24888   int rc;
24889   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
24890   return rc;
24891 }
24892 #else
24893 # define robust_flock(a,b) flock(a,b)
24894 #endif
24895      
24896
24897 /*
24898 ** This routine checks if there is a RESERVED lock held on the specified
24899 ** file by this or any other process. If such a lock is held, set *pResOut
24900 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24901 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24902 */
24903 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24904   int rc = SQLITE_OK;
24905   int reserved = 0;
24906   unixFile *pFile = (unixFile*)id;
24907   
24908   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24909   
24910   assert( pFile );
24911   
24912   /* Check if a thread in this process holds such a lock */
24913   if( pFile->eFileLock>SHARED_LOCK ){
24914     reserved = 1;
24915   }
24916   
24917   /* Otherwise see if some other process holds it. */
24918   if( !reserved ){
24919     /* attempt to get the lock */
24920     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
24921     if( !lrc ){
24922       /* got the lock, unlock it */
24923       lrc = robust_flock(pFile->h, LOCK_UN);
24924       if ( lrc ) {
24925         int tErrno = errno;
24926         /* unlock failed with an error */
24927         lrc = SQLITE_IOERR_UNLOCK; 
24928         if( IS_LOCK_ERROR(lrc) ){
24929           pFile->lastErrno = tErrno;
24930           rc = lrc;
24931         }
24932       }
24933     } else {
24934       int tErrno = errno;
24935       reserved = 1;
24936       /* someone else might have it reserved */
24937       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24938       if( IS_LOCK_ERROR(lrc) ){
24939         pFile->lastErrno = tErrno;
24940         rc = lrc;
24941       }
24942     }
24943   }
24944   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24945
24946 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24947   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24948     rc = SQLITE_OK;
24949     reserved=1;
24950   }
24951 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24952   *pResOut = reserved;
24953   return rc;
24954 }
24955
24956 /*
24957 ** Lock the file with the lock specified by parameter eFileLock - one
24958 ** of the following:
24959 **
24960 **     (1) SHARED_LOCK
24961 **     (2) RESERVED_LOCK
24962 **     (3) PENDING_LOCK
24963 **     (4) EXCLUSIVE_LOCK
24964 **
24965 ** Sometimes when requesting one lock state, additional lock states
24966 ** are inserted in between.  The locking might fail on one of the later
24967 ** transitions leaving the lock state different from what it started but
24968 ** still short of its goal.  The following chart shows the allowed
24969 ** transitions and the inserted intermediate states:
24970 **
24971 **    UNLOCKED -> SHARED
24972 **    SHARED -> RESERVED
24973 **    SHARED -> (PENDING) -> EXCLUSIVE
24974 **    RESERVED -> (PENDING) -> EXCLUSIVE
24975 **    PENDING -> EXCLUSIVE
24976 **
24977 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24978 ** lock states in the sqlite3_file structure, but all locks SHARED or
24979 ** above are really EXCLUSIVE locks and exclude all other processes from
24980 ** access the file.
24981 **
24982 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24983 ** routine to lower a locking level.
24984 */
24985 static int flockLock(sqlite3_file *id, int eFileLock) {
24986   int rc = SQLITE_OK;
24987   unixFile *pFile = (unixFile*)id;
24988
24989   assert( pFile );
24990
24991   /* if we already have a lock, it is exclusive.  
24992   ** Just adjust level and punt on outta here. */
24993   if (pFile->eFileLock > NO_LOCK) {
24994     pFile->eFileLock = eFileLock;
24995     return SQLITE_OK;
24996   }
24997   
24998   /* grab an exclusive lock */
24999   
25000   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25001     int tErrno = errno;
25002     /* didn't get, must be busy */
25003     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25004     if( IS_LOCK_ERROR(rc) ){
25005       pFile->lastErrno = tErrno;
25006     }
25007   } else {
25008     /* got it, set the type and return ok */
25009     pFile->eFileLock = eFileLock;
25010   }
25011   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
25012            rc==SQLITE_OK ? "ok" : "failed"));
25013 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25014   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25015     rc = SQLITE_BUSY;
25016   }
25017 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25018   return rc;
25019 }
25020
25021
25022 /*
25023 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25024 ** must be either NO_LOCK or SHARED_LOCK.
25025 **
25026 ** If the locking level of the file descriptor is already at or below
25027 ** the requested locking level, this routine is a no-op.
25028 */
25029 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25030   unixFile *pFile = (unixFile*)id;
25031   
25032   assert( pFile );
25033   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25034            pFile->eFileLock, getpid()));
25035   assert( eFileLock<=SHARED_LOCK );
25036   
25037   /* no-op if possible */
25038   if( pFile->eFileLock==eFileLock ){
25039     return SQLITE_OK;
25040   }
25041   
25042   /* shared can just be set because we always have an exclusive */
25043   if (eFileLock==SHARED_LOCK) {
25044     pFile->eFileLock = eFileLock;
25045     return SQLITE_OK;
25046   }
25047   
25048   /* no, really, unlock. */
25049   if( robust_flock(pFile->h, LOCK_UN) ){
25050 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25051     return SQLITE_OK;
25052 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25053     return SQLITE_IOERR_UNLOCK;
25054   }else{
25055     pFile->eFileLock = NO_LOCK;
25056     return SQLITE_OK;
25057   }
25058 }
25059
25060 /*
25061 ** Close a file.
25062 */
25063 static int flockClose(sqlite3_file *id) {
25064   if( id ){
25065     flockUnlock(id, NO_LOCK);
25066   }
25067   return closeUnixFile(id);
25068 }
25069
25070 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25071
25072 /******************* End of the flock lock implementation *********************
25073 ******************************************************************************/
25074
25075 /******************************************************************************
25076 ************************ Begin Named Semaphore Locking ************************
25077 **
25078 ** Named semaphore locking is only supported on VxWorks.
25079 **
25080 ** Semaphore locking is like dot-lock and flock in that it really only
25081 ** supports EXCLUSIVE locking.  Only a single process can read or write
25082 ** the database file at a time.  This reduces potential concurrency, but
25083 ** makes the lock implementation much easier.
25084 */
25085 #if OS_VXWORKS
25086
25087 /*
25088 ** This routine checks if there is a RESERVED lock held on the specified
25089 ** file by this or any other process. If such a lock is held, set *pResOut
25090 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25091 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25092 */
25093 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25094   int rc = SQLITE_OK;
25095   int reserved = 0;
25096   unixFile *pFile = (unixFile*)id;
25097
25098   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25099   
25100   assert( pFile );
25101
25102   /* Check if a thread in this process holds such a lock */
25103   if( pFile->eFileLock>SHARED_LOCK ){
25104     reserved = 1;
25105   }
25106   
25107   /* Otherwise see if some other process holds it. */
25108   if( !reserved ){
25109     sem_t *pSem = pFile->pInode->pSem;
25110     struct stat statBuf;
25111
25112     if( sem_trywait(pSem)==-1 ){
25113       int tErrno = errno;
25114       if( EAGAIN != tErrno ){
25115         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25116         pFile->lastErrno = tErrno;
25117       } else {
25118         /* someone else has the lock when we are in NO_LOCK */
25119         reserved = (pFile->eFileLock < SHARED_LOCK);
25120       }
25121     }else{
25122       /* we could have it if we want it */
25123       sem_post(pSem);
25124     }
25125   }
25126   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25127
25128   *pResOut = reserved;
25129   return rc;
25130 }
25131
25132 /*
25133 ** Lock the file with the lock specified by parameter eFileLock - one
25134 ** of the following:
25135 **
25136 **     (1) SHARED_LOCK
25137 **     (2) RESERVED_LOCK
25138 **     (3) PENDING_LOCK
25139 **     (4) EXCLUSIVE_LOCK
25140 **
25141 ** Sometimes when requesting one lock state, additional lock states
25142 ** are inserted in between.  The locking might fail on one of the later
25143 ** transitions leaving the lock state different from what it started but
25144 ** still short of its goal.  The following chart shows the allowed
25145 ** transitions and the inserted intermediate states:
25146 **
25147 **    UNLOCKED -> SHARED
25148 **    SHARED -> RESERVED
25149 **    SHARED -> (PENDING) -> EXCLUSIVE
25150 **    RESERVED -> (PENDING) -> EXCLUSIVE
25151 **    PENDING -> EXCLUSIVE
25152 **
25153 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25154 ** lock states in the sqlite3_file structure, but all locks SHARED or
25155 ** above are really EXCLUSIVE locks and exclude all other processes from
25156 ** access the file.
25157 **
25158 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25159 ** routine to lower a locking level.
25160 */
25161 static int semLock(sqlite3_file *id, int eFileLock) {
25162   unixFile *pFile = (unixFile*)id;
25163   int fd;
25164   sem_t *pSem = pFile->pInode->pSem;
25165   int rc = SQLITE_OK;
25166
25167   /* if we already have a lock, it is exclusive.  
25168   ** Just adjust level and punt on outta here. */
25169   if (pFile->eFileLock > NO_LOCK) {
25170     pFile->eFileLock = eFileLock;
25171     rc = SQLITE_OK;
25172     goto sem_end_lock;
25173   }
25174   
25175   /* lock semaphore now but bail out when already locked. */
25176   if( sem_trywait(pSem)==-1 ){
25177     rc = SQLITE_BUSY;
25178     goto sem_end_lock;
25179   }
25180
25181   /* got it, set the type and return ok */
25182   pFile->eFileLock = eFileLock;
25183
25184  sem_end_lock:
25185   return rc;
25186 }
25187
25188 /*
25189 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25190 ** must be either NO_LOCK or SHARED_LOCK.
25191 **
25192 ** If the locking level of the file descriptor is already at or below
25193 ** the requested locking level, this routine is a no-op.
25194 */
25195 static int semUnlock(sqlite3_file *id, int eFileLock) {
25196   unixFile *pFile = (unixFile*)id;
25197   sem_t *pSem = pFile->pInode->pSem;
25198
25199   assert( pFile );
25200   assert( pSem );
25201   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25202            pFile->eFileLock, getpid()));
25203   assert( eFileLock<=SHARED_LOCK );
25204   
25205   /* no-op if possible */
25206   if( pFile->eFileLock==eFileLock ){
25207     return SQLITE_OK;
25208   }
25209   
25210   /* shared can just be set because we always have an exclusive */
25211   if (eFileLock==SHARED_LOCK) {
25212     pFile->eFileLock = eFileLock;
25213     return SQLITE_OK;
25214   }
25215   
25216   /* no, really unlock. */
25217   if ( sem_post(pSem)==-1 ) {
25218     int rc, tErrno = errno;
25219     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25220     if( IS_LOCK_ERROR(rc) ){
25221       pFile->lastErrno = tErrno;
25222     }
25223     return rc; 
25224   }
25225   pFile->eFileLock = NO_LOCK;
25226   return SQLITE_OK;
25227 }
25228
25229 /*
25230  ** Close a file.
25231  */
25232 static int semClose(sqlite3_file *id) {
25233   if( id ){
25234     unixFile *pFile = (unixFile*)id;
25235     semUnlock(id, NO_LOCK);
25236     assert( pFile );
25237     unixEnterMutex();
25238     releaseInodeInfo(pFile);
25239     unixLeaveMutex();
25240     closeUnixFile(id);
25241   }
25242   return SQLITE_OK;
25243 }
25244
25245 #endif /* OS_VXWORKS */
25246 /*
25247 ** Named semaphore locking is only available on VxWorks.
25248 **
25249 *************** End of the named semaphore lock implementation ****************
25250 ******************************************************************************/
25251
25252
25253 /******************************************************************************
25254 *************************** Begin AFP Locking *********************************
25255 **
25256 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25257 ** on Apple Macintosh computers - both OS9 and OSX.
25258 **
25259 ** Third-party implementations of AFP are available.  But this code here
25260 ** only works on OSX.
25261 */
25262
25263 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25264 /*
25265 ** The afpLockingContext structure contains all afp lock specific state
25266 */
25267 typedef struct afpLockingContext afpLockingContext;
25268 struct afpLockingContext {
25269   int reserved;
25270   const char *dbPath;             /* Name of the open file */
25271 };
25272
25273 struct ByteRangeLockPB2
25274 {
25275   unsigned long long offset;        /* offset to first byte to lock */
25276   unsigned long long length;        /* nbr of bytes to lock */
25277   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25278   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25279   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25280   int fd;                           /* file desc to assoc this lock with */
25281 };
25282
25283 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25284
25285 /*
25286 ** This is a utility for setting or clearing a bit-range lock on an
25287 ** AFP filesystem.
25288 ** 
25289 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25290 */
25291 static int afpSetLock(
25292   const char *path,              /* Name of the file to be locked or unlocked */
25293   unixFile *pFile,               /* Open file descriptor on path */
25294   unsigned long long offset,     /* First byte to be locked */
25295   unsigned long long length,     /* Number of bytes to lock */
25296   int setLockFlag                /* True to set lock.  False to clear lock */
25297 ){
25298   struct ByteRangeLockPB2 pb;
25299   int err;
25300   
25301   pb.unLockFlag = setLockFlag ? 0 : 1;
25302   pb.startEndFlag = 0;
25303   pb.offset = offset;
25304   pb.length = length; 
25305   pb.fd = pFile->h;
25306   
25307   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25308     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25309     offset, length));
25310   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25311   if ( err==-1 ) {
25312     int rc;
25313     int tErrno = errno;
25314     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25315              path, tErrno, strerror(tErrno)));
25316 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25317     rc = SQLITE_BUSY;
25318 #else
25319     rc = sqliteErrorFromPosixError(tErrno,
25320                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25321 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25322     if( IS_LOCK_ERROR(rc) ){
25323       pFile->lastErrno = tErrno;
25324     }
25325     return rc;
25326   } else {
25327     return SQLITE_OK;
25328   }
25329 }
25330
25331 /*
25332 ** This routine checks if there is a RESERVED lock held on the specified
25333 ** file by this or any other process. If such a lock is held, set *pResOut
25334 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25335 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25336 */
25337 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25338   int rc = SQLITE_OK;
25339   int reserved = 0;
25340   unixFile *pFile = (unixFile*)id;
25341   afpLockingContext *context;
25342   
25343   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25344   
25345   assert( pFile );
25346   context = (afpLockingContext *) pFile->lockingContext;
25347   if( context->reserved ){
25348     *pResOut = 1;
25349     return SQLITE_OK;
25350   }
25351   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25352   
25353   /* Check if a thread in this process holds such a lock */
25354   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25355     reserved = 1;
25356   }
25357   
25358   /* Otherwise see if some other process holds it.
25359    */
25360   if( !reserved ){
25361     /* lock the RESERVED byte */
25362     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25363     if( SQLITE_OK==lrc ){
25364       /* if we succeeded in taking the reserved lock, unlock it to restore
25365       ** the original state */
25366       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25367     } else {
25368       /* if we failed to get the lock then someone else must have it */
25369       reserved = 1;
25370     }
25371     if( IS_LOCK_ERROR(lrc) ){
25372       rc=lrc;
25373     }
25374   }
25375   
25376   unixLeaveMutex();
25377   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25378   
25379   *pResOut = reserved;
25380   return rc;
25381 }
25382
25383 /*
25384 ** Lock the file with the lock specified by parameter eFileLock - one
25385 ** of the following:
25386 **
25387 **     (1) SHARED_LOCK
25388 **     (2) RESERVED_LOCK
25389 **     (3) PENDING_LOCK
25390 **     (4) EXCLUSIVE_LOCK
25391 **
25392 ** Sometimes when requesting one lock state, additional lock states
25393 ** are inserted in between.  The locking might fail on one of the later
25394 ** transitions leaving the lock state different from what it started but
25395 ** still short of its goal.  The following chart shows the allowed
25396 ** transitions and the inserted intermediate states:
25397 **
25398 **    UNLOCKED -> SHARED
25399 **    SHARED -> RESERVED
25400 **    SHARED -> (PENDING) -> EXCLUSIVE
25401 **    RESERVED -> (PENDING) -> EXCLUSIVE
25402 **    PENDING -> EXCLUSIVE
25403 **
25404 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25405 ** routine to lower a locking level.
25406 */
25407 static int afpLock(sqlite3_file *id, int eFileLock){
25408   int rc = SQLITE_OK;
25409   unixFile *pFile = (unixFile*)id;
25410   unixInodeInfo *pInode = pFile->pInode;
25411   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25412   
25413   assert( pFile );
25414   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25415            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25416            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25417
25418   /* If there is already a lock of this type or more restrictive on the
25419   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25420   ** unixEnterMutex() hasn't been called yet.
25421   */
25422   if( pFile->eFileLock>=eFileLock ){
25423     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25424            azFileLock(eFileLock)));
25425     return SQLITE_OK;
25426   }
25427
25428   /* Make sure the locking sequence is correct
25429   **  (1) We never move from unlocked to anything higher than shared lock.
25430   **  (2) SQLite never explicitly requests a pendig lock.
25431   **  (3) A shared lock is always held when a reserve lock is requested.
25432   */
25433   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25434   assert( eFileLock!=PENDING_LOCK );
25435   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25436   
25437   /* This mutex is needed because pFile->pInode is shared across threads
25438   */
25439   unixEnterMutex();
25440   pInode = pFile->pInode;
25441
25442   /* If some thread using this PID has a lock via a different unixFile*
25443   ** handle that precludes the requested lock, return BUSY.
25444   */
25445   if( (pFile->eFileLock!=pInode->eFileLock && 
25446        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25447      ){
25448     rc = SQLITE_BUSY;
25449     goto afp_end_lock;
25450   }
25451   
25452   /* If a SHARED lock is requested, and some thread using this PID already
25453   ** has a SHARED or RESERVED lock, then increment reference counts and
25454   ** return SQLITE_OK.
25455   */
25456   if( eFileLock==SHARED_LOCK && 
25457      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25458     assert( eFileLock==SHARED_LOCK );
25459     assert( pFile->eFileLock==0 );
25460     assert( pInode->nShared>0 );
25461     pFile->eFileLock = SHARED_LOCK;
25462     pInode->nShared++;
25463     pInode->nLock++;
25464     goto afp_end_lock;
25465   }
25466     
25467   /* A PENDING lock is needed before acquiring a SHARED lock and before
25468   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25469   ** be released.
25470   */
25471   if( eFileLock==SHARED_LOCK 
25472       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25473   ){
25474     int failed;
25475     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25476     if (failed) {
25477       rc = failed;
25478       goto afp_end_lock;
25479     }
25480   }
25481   
25482   /* If control gets to this point, then actually go ahead and make
25483   ** operating system calls for the specified lock.
25484   */
25485   if( eFileLock==SHARED_LOCK ){
25486     int lrc1, lrc2, lrc1Errno = 0;
25487     long lk, mask;
25488     
25489     assert( pInode->nShared==0 );
25490     assert( pInode->eFileLock==0 );
25491         
25492     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25493     /* Now get the read-lock SHARED_LOCK */
25494     /* note that the quality of the randomness doesn't matter that much */
25495     lk = random(); 
25496     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25497     lrc1 = afpSetLock(context->dbPath, pFile, 
25498           SHARED_FIRST+pInode->sharedByte, 1, 1);
25499     if( IS_LOCK_ERROR(lrc1) ){
25500       lrc1Errno = pFile->lastErrno;
25501     }
25502     /* Drop the temporary PENDING lock */
25503     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25504     
25505     if( IS_LOCK_ERROR(lrc1) ) {
25506       pFile->lastErrno = lrc1Errno;
25507       rc = lrc1;
25508       goto afp_end_lock;
25509     } else if( IS_LOCK_ERROR(lrc2) ){
25510       rc = lrc2;
25511       goto afp_end_lock;
25512     } else if( lrc1 != SQLITE_OK ) {
25513       rc = lrc1;
25514     } else {
25515       pFile->eFileLock = SHARED_LOCK;
25516       pInode->nLock++;
25517       pInode->nShared = 1;
25518     }
25519   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25520     /* We are trying for an exclusive lock but another thread in this
25521      ** same process is still holding a shared lock. */
25522     rc = SQLITE_BUSY;
25523   }else{
25524     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25525     ** assumed that there is a SHARED or greater lock on the file
25526     ** already.
25527     */
25528     int failed = 0;
25529     assert( 0!=pFile->eFileLock );
25530     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25531         /* Acquire a RESERVED lock */
25532         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25533       if( !failed ){
25534         context->reserved = 1;
25535       }
25536     }
25537     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25538       /* Acquire an EXCLUSIVE lock */
25539         
25540       /* Remove the shared lock before trying the range.  we'll need to 
25541       ** reestablish the shared lock if we can't get the  afpUnlock
25542       */
25543       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25544                          pInode->sharedByte, 1, 0)) ){
25545         int failed2 = SQLITE_OK;
25546         /* now attemmpt to get the exclusive lock range */
25547         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25548                                SHARED_SIZE, 1);
25549         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25550                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25551           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25552           ** a critical I/O error
25553           */
25554           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25555                SQLITE_IOERR_LOCK;
25556           goto afp_end_lock;
25557         } 
25558       }else{
25559         rc = failed; 
25560       }
25561     }
25562     if( failed ){
25563       rc = failed;
25564     }
25565   }
25566   
25567   if( rc==SQLITE_OK ){
25568     pFile->eFileLock = eFileLock;
25569     pInode->eFileLock = eFileLock;
25570   }else if( eFileLock==EXCLUSIVE_LOCK ){
25571     pFile->eFileLock = PENDING_LOCK;
25572     pInode->eFileLock = PENDING_LOCK;
25573   }
25574   
25575 afp_end_lock:
25576   unixLeaveMutex();
25577   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25578          rc==SQLITE_OK ? "ok" : "failed"));
25579   return rc;
25580 }
25581
25582 /*
25583 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25584 ** must be either NO_LOCK or SHARED_LOCK.
25585 **
25586 ** If the locking level of the file descriptor is already at or below
25587 ** the requested locking level, this routine is a no-op.
25588 */
25589 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25590   int rc = SQLITE_OK;
25591   unixFile *pFile = (unixFile*)id;
25592   unixInodeInfo *pInode;
25593   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25594   int skipShared = 0;
25595 #ifdef SQLITE_TEST
25596   int h = pFile->h;
25597 #endif
25598
25599   assert( pFile );
25600   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25601            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25602            getpid()));
25603
25604   assert( eFileLock<=SHARED_LOCK );
25605   if( pFile->eFileLock<=eFileLock ){
25606     return SQLITE_OK;
25607   }
25608   unixEnterMutex();
25609   pInode = pFile->pInode;
25610   assert( pInode->nShared!=0 );
25611   if( pFile->eFileLock>SHARED_LOCK ){
25612     assert( pInode->eFileLock==pFile->eFileLock );
25613     SimulateIOErrorBenign(1);
25614     SimulateIOError( h=(-1) )
25615     SimulateIOErrorBenign(0);
25616     
25617 #ifdef SQLITE_DEBUG
25618     /* When reducing a lock such that other processes can start
25619     ** reading the database file again, make sure that the
25620     ** transaction counter was updated if any part of the database
25621     ** file changed.  If the transaction counter is not updated,
25622     ** other connections to the same file might not realize that
25623     ** the file has changed and hence might not know to flush their
25624     ** cache.  The use of a stale cache can lead to database corruption.
25625     */
25626     assert( pFile->inNormalWrite==0
25627            || pFile->dbUpdate==0
25628            || pFile->transCntrChng==1 );
25629     pFile->inNormalWrite = 0;
25630 #endif
25631     
25632     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25633       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25634       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25635         /* only re-establish the shared lock if necessary */
25636         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25637         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25638       } else {
25639         skipShared = 1;
25640       }
25641     }
25642     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25643       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25644     } 
25645     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25646       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25647       if( !rc ){ 
25648         context->reserved = 0; 
25649       }
25650     }
25651     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25652       pInode->eFileLock = SHARED_LOCK;
25653     }
25654   }
25655   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25656
25657     /* Decrement the shared lock counter.  Release the lock using an
25658     ** OS call only when all threads in this same process have released
25659     ** the lock.
25660     */
25661     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25662     pInode->nShared--;
25663     if( pInode->nShared==0 ){
25664       SimulateIOErrorBenign(1);
25665       SimulateIOError( h=(-1) )
25666       SimulateIOErrorBenign(0);
25667       if( !skipShared ){
25668         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25669       }
25670       if( !rc ){
25671         pInode->eFileLock = NO_LOCK;
25672         pFile->eFileLock = NO_LOCK;
25673       }
25674     }
25675     if( rc==SQLITE_OK ){
25676       pInode->nLock--;
25677       assert( pInode->nLock>=0 );
25678       if( pInode->nLock==0 ){
25679         closePendingFds(pFile);
25680       }
25681     }
25682   }
25683   
25684   unixLeaveMutex();
25685   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25686   return rc;
25687 }
25688
25689 /*
25690 ** Close a file & cleanup AFP specific locking context 
25691 */
25692 static int afpClose(sqlite3_file *id) {
25693   int rc = SQLITE_OK;
25694   if( id ){
25695     unixFile *pFile = (unixFile*)id;
25696     afpUnlock(id, NO_LOCK);
25697     unixEnterMutex();
25698     if( pFile->pInode && pFile->pInode->nLock ){
25699       /* If there are outstanding locks, do not actually close the file just
25700       ** yet because that would clear those locks.  Instead, add the file
25701       ** descriptor to pInode->aPending.  It will be automatically closed when
25702       ** the last lock is cleared.
25703       */
25704       setPendingFd(pFile);
25705     }
25706     releaseInodeInfo(pFile);
25707     sqlite3_free(pFile->lockingContext);
25708     rc = closeUnixFile(id);
25709     unixLeaveMutex();
25710   }
25711   return rc;
25712 }
25713
25714 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25715 /*
25716 ** The code above is the AFP lock implementation.  The code is specific
25717 ** to MacOSX and does not work on other unix platforms.  No alternative
25718 ** is available.  If you don't compile for a mac, then the "unix-afp"
25719 ** VFS is not available.
25720 **
25721 ********************* End of the AFP lock implementation **********************
25722 ******************************************************************************/
25723
25724 /******************************************************************************
25725 *************************** Begin NFS Locking ********************************/
25726
25727 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25728 /*
25729  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25730  ** must be either NO_LOCK or SHARED_LOCK.
25731  **
25732  ** If the locking level of the file descriptor is already at or below
25733  ** the requested locking level, this routine is a no-op.
25734  */
25735 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25736   return posixUnlock(id, eFileLock, 1);
25737 }
25738
25739 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25740 /*
25741 ** The code above is the NFS lock implementation.  The code is specific
25742 ** to MacOSX and does not work on other unix platforms.  No alternative
25743 ** is available.  
25744 **
25745 ********************* End of the NFS lock implementation **********************
25746 ******************************************************************************/
25747
25748 /******************************************************************************
25749 **************** Non-locking sqlite3_file methods *****************************
25750 **
25751 ** The next division contains implementations for all methods of the 
25752 ** sqlite3_file object other than the locking methods.  The locking
25753 ** methods were defined in divisions above (one locking method per
25754 ** division).  Those methods that are common to all locking modes
25755 ** are gather together into this division.
25756 */
25757
25758 /*
25759 ** Seek to the offset passed as the second argument, then read cnt 
25760 ** bytes into pBuf. Return the number of bytes actually read.
25761 **
25762 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25763 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25764 ** one system to another.  Since SQLite does not define USE_PREAD
25765 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25766 ** See tickets #2741 and #2681.
25767 **
25768 ** To avoid stomping the errno value on a failed read the lastErrno value
25769 ** is set before returning.
25770 */
25771 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25772   int got;
25773   int prior = 0;
25774 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25775   i64 newOffset;
25776 #endif
25777   TIMER_START;
25778   do{
25779 #if defined(USE_PREAD)
25780     got = osPread(id->h, pBuf, cnt, offset);
25781     SimulateIOError( got = -1 );
25782 #elif defined(USE_PREAD64)
25783     got = osPread64(id->h, pBuf, cnt, offset);
25784     SimulateIOError( got = -1 );
25785 #else
25786     newOffset = lseek(id->h, offset, SEEK_SET);
25787     SimulateIOError( newOffset-- );
25788     if( newOffset!=offset ){
25789       if( newOffset == -1 ){
25790         ((unixFile*)id)->lastErrno = errno;
25791       }else{
25792         ((unixFile*)id)->lastErrno = 0;
25793       }
25794       return -1;
25795     }
25796     got = osRead(id->h, pBuf, cnt);
25797 #endif
25798     if( got==cnt ) break;
25799     if( got<0 ){
25800       if( errno==EINTR ){ got = 1; continue; }
25801       prior = 0;
25802       ((unixFile*)id)->lastErrno = errno;
25803       break;
25804     }else if( got>0 ){
25805       cnt -= got;
25806       offset += got;
25807       prior += got;
25808       pBuf = (void*)(got + (char*)pBuf);
25809     }
25810   }while( got>0 );
25811   TIMER_END;
25812   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
25813             id->h, got+prior, offset-prior, TIMER_ELAPSED));
25814   return got+prior;
25815 }
25816
25817 /*
25818 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25819 ** bytes were read successfully and SQLITE_IOERR if anything goes
25820 ** wrong.
25821 */
25822 static int unixRead(
25823   sqlite3_file *id, 
25824   void *pBuf, 
25825   int amt,
25826   sqlite3_int64 offset
25827 ){
25828   unixFile *pFile = (unixFile *)id;
25829   int got;
25830   assert( id );
25831
25832   /* If this is a database file (not a journal, master-journal or temp
25833   ** file), the bytes in the locking range should never be read or written. */
25834 #if 0
25835   assert( pFile->pUnused==0
25836        || offset>=PENDING_BYTE+512
25837        || offset+amt<=PENDING_BYTE 
25838   );
25839 #endif
25840
25841   got = seekAndRead(pFile, offset, pBuf, amt);
25842   if( got==amt ){
25843     return SQLITE_OK;
25844   }else if( got<0 ){
25845     /* lastErrno set by seekAndRead */
25846     return SQLITE_IOERR_READ;
25847   }else{
25848     pFile->lastErrno = 0; /* not a system error */
25849     /* Unread parts of the buffer must be zero-filled */
25850     memset(&((char*)pBuf)[got], 0, amt-got);
25851     return SQLITE_IOERR_SHORT_READ;
25852   }
25853 }
25854
25855 /*
25856 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25857 ** Return the number of bytes actually read.  Update the offset.
25858 **
25859 ** To avoid stomping the errno value on a failed write the lastErrno value
25860 ** is set before returning.
25861 */
25862 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25863   int got;
25864 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25865   i64 newOffset;
25866 #endif
25867   TIMER_START;
25868 #if defined(USE_PREAD)
25869   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
25870 #elif defined(USE_PREAD64)
25871   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
25872 #else
25873   do{
25874     newOffset = lseek(id->h, offset, SEEK_SET);
25875     SimulateIOError( newOffset-- );
25876     if( newOffset!=offset ){
25877       if( newOffset == -1 ){
25878         ((unixFile*)id)->lastErrno = errno;
25879       }else{
25880         ((unixFile*)id)->lastErrno = 0;
25881       }
25882       return -1;
25883     }
25884     got = osWrite(id->h, pBuf, cnt);
25885   }while( got<0 && errno==EINTR );
25886 #endif
25887   TIMER_END;
25888   if( got<0 ){
25889     ((unixFile*)id)->lastErrno = errno;
25890   }
25891
25892   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25893   return got;
25894 }
25895
25896
25897 /*
25898 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25899 ** or some other error code on failure.
25900 */
25901 static int unixWrite(
25902   sqlite3_file *id, 
25903   const void *pBuf, 
25904   int amt,
25905   sqlite3_int64 offset 
25906 ){
25907   unixFile *pFile = (unixFile*)id;
25908   int wrote = 0;
25909   assert( id );
25910   assert( amt>0 );
25911
25912   /* If this is a database file (not a journal, master-journal or temp
25913   ** file), the bytes in the locking range should never be read or written. */
25914 #if 0
25915   assert( pFile->pUnused==0
25916        || offset>=PENDING_BYTE+512
25917        || offset+amt<=PENDING_BYTE 
25918   );
25919 #endif
25920
25921 #ifdef SQLITE_DEBUG
25922   /* If we are doing a normal write to a database file (as opposed to
25923   ** doing a hot-journal rollback or a write to some file other than a
25924   ** normal database file) then record the fact that the database
25925   ** has changed.  If the transaction counter is modified, record that
25926   ** fact too.
25927   */
25928   if( pFile->inNormalWrite ){
25929     pFile->dbUpdate = 1;  /* The database has been modified */
25930     if( offset<=24 && offset+amt>=27 ){
25931       int rc;
25932       char oldCntr[4];
25933       SimulateIOErrorBenign(1);
25934       rc = seekAndRead(pFile, 24, oldCntr, 4);
25935       SimulateIOErrorBenign(0);
25936       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25937         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25938       }
25939     }
25940   }
25941 #endif
25942
25943   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25944     amt -= wrote;
25945     offset += wrote;
25946     pBuf = &((char*)pBuf)[wrote];
25947   }
25948   SimulateIOError(( wrote=(-1), amt=1 ));
25949   SimulateDiskfullError(( wrote=0, amt=1 ));
25950
25951   if( amt>0 ){
25952     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
25953       /* lastErrno set by seekAndWrite */
25954       return SQLITE_IOERR_WRITE;
25955     }else{
25956       pFile->lastErrno = 0; /* not a system error */
25957       return SQLITE_FULL;
25958     }
25959   }
25960
25961   return SQLITE_OK;
25962 }
25963
25964 #ifdef SQLITE_TEST
25965 /*
25966 ** Count the number of fullsyncs and normal syncs.  This is used to test
25967 ** that syncs and fullsyncs are occurring at the right times.
25968 */
25969 SQLITE_API int sqlite3_sync_count = 0;
25970 SQLITE_API int sqlite3_fullsync_count = 0;
25971 #endif
25972
25973 /*
25974 ** We do not trust systems to provide a working fdatasync().  Some do.
25975 ** Others do no.  To be safe, we will stick with the (slightly slower)
25976 ** fsync(). If you know that your system does support fdatasync() correctly,
25977 ** then simply compile with -Dfdatasync=fdatasync
25978 */
25979 #if !defined(fdatasync)
25980 # define fdatasync fsync
25981 #endif
25982
25983 /*
25984 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25985 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25986 ** only available on Mac OS X.  But that could change.
25987 */
25988 #ifdef F_FULLFSYNC
25989 # define HAVE_FULLFSYNC 1
25990 #else
25991 # define HAVE_FULLFSYNC 0
25992 #endif
25993
25994
25995 /*
25996 ** The fsync() system call does not work as advertised on many
25997 ** unix systems.  The following procedure is an attempt to make
25998 ** it work better.
25999 **
26000 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26001 ** for testing when we want to run through the test suite quickly.
26002 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26003 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26004 ** or power failure will likely corrupt the database file.
26005 **
26006 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26007 ** The idea behind dataOnly is that it should only write the file content
26008 ** to disk, not the inode.  We only set dataOnly if the file size is 
26009 ** unchanged since the file size is part of the inode.  However, 
26010 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26011 ** file size has changed.  The only real difference between fdatasync()
26012 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26013 ** inode if the mtime or owner or other inode attributes have changed.
26014 ** We only care about the file size, not the other file attributes, so
26015 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26016 ** So, we always use fdatasync() if it is available, regardless of
26017 ** the value of the dataOnly flag.
26018 */
26019 static int full_fsync(int fd, int fullSync, int dataOnly){
26020   int rc;
26021
26022   /* The following "ifdef/elif/else/" block has the same structure as
26023   ** the one below. It is replicated here solely to avoid cluttering 
26024   ** up the real code with the UNUSED_PARAMETER() macros.
26025   */
26026 #ifdef SQLITE_NO_SYNC
26027   UNUSED_PARAMETER(fd);
26028   UNUSED_PARAMETER(fullSync);
26029   UNUSED_PARAMETER(dataOnly);
26030 #elif HAVE_FULLFSYNC
26031   UNUSED_PARAMETER(dataOnly);
26032 #else
26033   UNUSED_PARAMETER(fullSync);
26034   UNUSED_PARAMETER(dataOnly);
26035 #endif
26036
26037   /* Record the number of times that we do a normal fsync() and 
26038   ** FULLSYNC.  This is used during testing to verify that this procedure
26039   ** gets called with the correct arguments.
26040   */
26041 #ifdef SQLITE_TEST
26042   if( fullSync ) sqlite3_fullsync_count++;
26043   sqlite3_sync_count++;
26044 #endif
26045
26046   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26047   ** no-op
26048   */
26049 #ifdef SQLITE_NO_SYNC
26050   rc = SQLITE_OK;
26051 #elif HAVE_FULLFSYNC
26052   if( fullSync ){
26053     rc = osFcntl(fd, F_FULLFSYNC, 0);
26054   }else{
26055     rc = 1;
26056   }
26057   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26058   ** It shouldn't be possible for fullfsync to fail on the local 
26059   ** file system (on OSX), so failure indicates that FULLFSYNC
26060   ** isn't supported for this file system. So, attempt an fsync 
26061   ** and (for now) ignore the overhead of a superfluous fcntl call.  
26062   ** It'd be better to detect fullfsync support once and avoid 
26063   ** the fcntl call every time sync is called.
26064   */
26065   if( rc ) rc = fsync(fd);
26066
26067 #elif defined(__APPLE__)
26068   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26069   ** so currently we default to the macro that redefines fdatasync to fsync
26070   */
26071   rc = fsync(fd);
26072 #else 
26073   rc = fdatasync(fd);
26074 #if OS_VXWORKS
26075   if( rc==-1 && errno==ENOTSUP ){
26076     rc = fsync(fd);
26077   }
26078 #endif /* OS_VXWORKS */
26079 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26080
26081   if( OS_VXWORKS && rc!= -1 ){
26082     rc = 0;
26083   }
26084   return rc;
26085 }
26086
26087 /*
26088 ** Open a file descriptor to the directory containing file zFilename.
26089 ** If successful, *pFd is set to the opened file descriptor and
26090 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26091 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26092 ** value.
26093 **
26094 ** The directory file descriptor is used for only one thing - to
26095 ** fsync() a directory to make sure file creation and deletion events
26096 ** are flushed to disk.  Such fsyncs are not needed on newer
26097 ** journaling filesystems, but are required on older filesystems.
26098 **
26099 ** This routine can be overridden using the xSetSysCall interface.
26100 ** The ability to override this routine was added in support of the
26101 ** chromium sandbox.  Opening a directory is a security risk (we are
26102 ** told) so making it overrideable allows the chromium sandbox to
26103 ** replace this routine with a harmless no-op.  To make this routine
26104 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26105 ** *pFd set to a negative number.
26106 **
26107 ** If SQLITE_OK is returned, the caller is responsible for closing
26108 ** the file descriptor *pFd using close().
26109 */
26110 static int openDirectory(const char *zFilename, int *pFd){
26111   int ii;
26112   int fd = -1;
26113   char zDirname[MAX_PATHNAME+1];
26114
26115   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26116   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26117   if( ii>0 ){
26118     zDirname[ii] = '\0';
26119     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26120     if( fd>=0 ){
26121       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26122     }
26123   }
26124   *pFd = fd;
26125   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26126 }
26127
26128 /*
26129 ** Make sure all writes to a particular file are committed to disk.
26130 **
26131 ** If dataOnly==0 then both the file itself and its metadata (file
26132 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26133 ** file data is synced.
26134 **
26135 ** Under Unix, also make sure that the directory entry for the file
26136 ** has been created by fsync-ing the directory that contains the file.
26137 ** If we do not do this and we encounter a power failure, the directory
26138 ** entry for the journal might not exist after we reboot.  The next
26139 ** SQLite to access the file will not know that the journal exists (because
26140 ** the directory entry for the journal was never created) and the transaction
26141 ** will not roll back - possibly leading to database corruption.
26142 */
26143 static int unixSync(sqlite3_file *id, int flags){
26144   int rc;
26145   unixFile *pFile = (unixFile*)id;
26146
26147   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26148   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26149
26150   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26151   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26152       || (flags&0x0F)==SQLITE_SYNC_FULL
26153   );
26154
26155   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26156   ** line is to test that doing so does not cause any problems.
26157   */
26158   SimulateDiskfullError( return SQLITE_FULL );
26159
26160   assert( pFile );
26161   OSTRACE(("SYNC    %-3d\n", pFile->h));
26162   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26163   SimulateIOError( rc=1 );
26164   if( rc ){
26165     pFile->lastErrno = errno;
26166     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26167   }
26168
26169   /* Also fsync the directory containing the file if the DIRSYNC flag
26170   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
26171   ** are unable to fsync a directory, so ignore errors on the fsync.
26172   */
26173   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26174     int dirfd;
26175     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26176             HAVE_FULLFSYNC, isFullsync));
26177     rc = osOpenDirectory(pFile->zPath, &dirfd);
26178     if( rc==SQLITE_OK && dirfd>=0 ){
26179       full_fsync(dirfd, 0, 0);
26180       robust_close(pFile, dirfd, __LINE__);
26181     }else if( rc==SQLITE_CANTOPEN ){
26182       rc = SQLITE_OK;
26183     }
26184     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26185   }
26186   return rc;
26187 }
26188
26189 /*
26190 ** Truncate an open file to a specified size
26191 */
26192 static int unixTruncate(sqlite3_file *id, i64 nByte){
26193   unixFile *pFile = (unixFile *)id;
26194   int rc;
26195   assert( pFile );
26196   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26197
26198   /* If the user has configured a chunk-size for this file, truncate the
26199   ** file so that it consists of an integer number of chunks (i.e. the
26200   ** actual file size after the operation may be larger than the requested
26201   ** size).
26202   */
26203   if( pFile->szChunk>0 ){
26204     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26205   }
26206
26207   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26208   if( rc ){
26209     pFile->lastErrno = errno;
26210     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26211   }else{
26212 #ifdef SQLITE_DEBUG
26213     /* If we are doing a normal write to a database file (as opposed to
26214     ** doing a hot-journal rollback or a write to some file other than a
26215     ** normal database file) and we truncate the file to zero length,
26216     ** that effectively updates the change counter.  This might happen
26217     ** when restoring a database using the backup API from a zero-length
26218     ** source.
26219     */
26220     if( pFile->inNormalWrite && nByte==0 ){
26221       pFile->transCntrChng = 1;
26222     }
26223 #endif
26224
26225     return SQLITE_OK;
26226   }
26227 }
26228
26229 /*
26230 ** Determine the current size of a file in bytes
26231 */
26232 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26233   int rc;
26234   struct stat buf;
26235   assert( id );
26236   rc = osFstat(((unixFile*)id)->h, &buf);
26237   SimulateIOError( rc=1 );
26238   if( rc!=0 ){
26239     ((unixFile*)id)->lastErrno = errno;
26240     return SQLITE_IOERR_FSTAT;
26241   }
26242   *pSize = buf.st_size;
26243
26244   /* When opening a zero-size database, the findInodeInfo() procedure
26245   ** writes a single byte into that file in order to work around a bug
26246   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26247   ** layers, we need to report this file size as zero even though it is
26248   ** really 1.   Ticket #3260.
26249   */
26250   if( *pSize==1 ) *pSize = 0;
26251
26252
26253   return SQLITE_OK;
26254 }
26255
26256 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26257 /*
26258 ** Handler for proxy-locking file-control verbs.  Defined below in the
26259 ** proxying locking division.
26260 */
26261 static int proxyFileControl(sqlite3_file*,int,void*);
26262 #endif
26263
26264 /* 
26265 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26266 ** file-control operation.  Enlarge the database to nBytes in size
26267 ** (rounded up to the next chunk-size).  If the database is already
26268 ** nBytes or larger, this routine is a no-op.
26269 */
26270 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26271   if( pFile->szChunk>0 ){
26272     i64 nSize;                    /* Required file size */
26273     struct stat buf;              /* Used to hold return values of fstat() */
26274    
26275     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26276
26277     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26278     if( nSize>(i64)buf.st_size ){
26279
26280 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26281       /* The code below is handling the return value of osFallocate() 
26282       ** correctly. posix_fallocate() is defined to "returns zero on success, 
26283       ** or an error number on  failure". See the manpage for details. */
26284       int err;
26285       do{
26286         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26287       }while( err==EINTR );
26288       if( err ) return SQLITE_IOERR_WRITE;
26289 #else
26290       /* If the OS does not have posix_fallocate(), fake it. First use
26291       ** ftruncate() to set the file size, then write a single byte to
26292       ** the last byte in each block within the extended region. This
26293       ** is the same technique used by glibc to implement posix_fallocate()
26294       ** on systems that do not have a real fallocate() system call.
26295       */
26296       int nBlk = buf.st_blksize;  /* File-system block size */
26297       i64 iWrite;                 /* Next offset to write to */
26298
26299       if( robust_ftruncate(pFile->h, nSize) ){
26300         pFile->lastErrno = errno;
26301         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26302       }
26303       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26304       while( iWrite<nSize ){
26305         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26306         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26307         iWrite += nBlk;
26308       }
26309 #endif
26310     }
26311   }
26312
26313   return SQLITE_OK;
26314 }
26315
26316 /*
26317 ** If *pArg is inititially negative then this is a query.  Set *pArg to
26318 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26319 **
26320 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26321 */
26322 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26323   if( *pArg<0 ){
26324     *pArg = (pFile->ctrlFlags & mask)!=0;
26325   }else if( (*pArg)==0 ){
26326     pFile->ctrlFlags &= ~mask;
26327   }else{
26328     pFile->ctrlFlags |= mask;
26329   }
26330 }
26331
26332 /*
26333 ** Information and control of an open file handle.
26334 */
26335 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26336   unixFile *pFile = (unixFile*)id;
26337   switch( op ){
26338     case SQLITE_FCNTL_LOCKSTATE: {
26339       *(int*)pArg = pFile->eFileLock;
26340       return SQLITE_OK;
26341     }
26342     case SQLITE_LAST_ERRNO: {
26343       *(int*)pArg = pFile->lastErrno;
26344       return SQLITE_OK;
26345     }
26346     case SQLITE_FCNTL_CHUNK_SIZE: {
26347       pFile->szChunk = *(int *)pArg;
26348       return SQLITE_OK;
26349     }
26350     case SQLITE_FCNTL_SIZE_HINT: {
26351       int rc;
26352       SimulateIOErrorBenign(1);
26353       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26354       SimulateIOErrorBenign(0);
26355       return rc;
26356     }
26357     case SQLITE_FCNTL_PERSIST_WAL: {
26358       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26359       return SQLITE_OK;
26360     }
26361     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26362       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26363       return SQLITE_OK;
26364     }
26365     case SQLITE_FCNTL_VFSNAME: {
26366       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26367       return SQLITE_OK;
26368     }
26369 #ifdef SQLITE_DEBUG
26370     /* The pager calls this method to signal that it has done
26371     ** a rollback and that the database is therefore unchanged and
26372     ** it hence it is OK for the transaction change counter to be
26373     ** unchanged.
26374     */
26375     case SQLITE_FCNTL_DB_UNCHANGED: {
26376       ((unixFile*)id)->dbUpdate = 0;
26377       return SQLITE_OK;
26378     }
26379 #endif
26380 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26381     case SQLITE_SET_LOCKPROXYFILE:
26382     case SQLITE_GET_LOCKPROXYFILE: {
26383       return proxyFileControl(id,op,pArg);
26384     }
26385 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26386   }
26387   return SQLITE_NOTFOUND;
26388 }
26389
26390 /*
26391 ** Return the sector size in bytes of the underlying block device for
26392 ** the specified file. This is almost always 512 bytes, but may be
26393 ** larger for some devices.
26394 **
26395 ** SQLite code assumes this function cannot fail. It also assumes that
26396 ** if two files are created in the same file-system directory (i.e.
26397 ** a database and its journal file) that the sector size will be the
26398 ** same for both.
26399 */
26400 static int unixSectorSize(sqlite3_file *pFile){
26401   (void)pFile;
26402   return SQLITE_DEFAULT_SECTOR_SIZE;
26403 }
26404
26405 /*
26406 ** Return the device characteristics for the file.
26407 **
26408 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
26409 ** However, that choice is contraversial since technically the underlying
26410 ** file system does not always provide powersafe overwrites.  (In other
26411 ** words, after a power-loss event, parts of the file that were never
26412 ** written might end up being altered.)  However, non-PSOW behavior is very,
26413 ** very rare.  And asserting PSOW makes a large reduction in the amount
26414 ** of required I/O for journaling, since a lot of padding is eliminated.
26415 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
26416 ** available to turn it off and URI query parameter available to turn it off.
26417 */
26418 static int unixDeviceCharacteristics(sqlite3_file *id){
26419   unixFile *p = (unixFile*)id;
26420   if( p->ctrlFlags & UNIXFILE_PSOW ){
26421     return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
26422   }else{
26423     return 0;
26424   }
26425 }
26426
26427 #ifndef SQLITE_OMIT_WAL
26428
26429
26430 /*
26431 ** Object used to represent an shared memory buffer.  
26432 **
26433 ** When multiple threads all reference the same wal-index, each thread
26434 ** has its own unixShm object, but they all point to a single instance
26435 ** of this unixShmNode object.  In other words, each wal-index is opened
26436 ** only once per process.
26437 **
26438 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26439 ** We could coalesce this object into unixInodeInfo, but that would mean
26440 ** every open file that does not use shared memory (in other words, most
26441 ** open files) would have to carry around this extra information.  So
26442 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26443 ** and the unixShmNode object is created only when needed.
26444 **
26445 ** unixMutexHeld() must be true when creating or destroying
26446 ** this object or while reading or writing the following fields:
26447 **
26448 **      nRef
26449 **
26450 ** The following fields are read-only after the object is created:
26451 ** 
26452 **      fid
26453 **      zFilename
26454 **
26455 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26456 ** unixMutexHeld() is true when reading or writing any other field
26457 ** in this structure.
26458 */
26459 struct unixShmNode {
26460   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26461   sqlite3_mutex *mutex;      /* Mutex to access this object */
26462   char *zFilename;           /* Name of the mmapped file */
26463   int h;                     /* Open file descriptor */
26464   int szRegion;              /* Size of shared-memory regions */
26465   u16 nRegion;               /* Size of array apRegion */
26466   u8 isReadonly;             /* True if read-only */
26467   char **apRegion;           /* Array of mapped shared-memory regions */
26468   int nRef;                  /* Number of unixShm objects pointing to this */
26469   unixShm *pFirst;           /* All unixShm objects pointing to this */
26470 #ifdef SQLITE_DEBUG
26471   u8 exclMask;               /* Mask of exclusive locks held */
26472   u8 sharedMask;             /* Mask of shared locks held */
26473   u8 nextShmId;              /* Next available unixShm.id value */
26474 #endif
26475 };
26476
26477 /*
26478 ** Structure used internally by this VFS to record the state of an
26479 ** open shared memory connection.
26480 **
26481 ** The following fields are initialized when this object is created and
26482 ** are read-only thereafter:
26483 **
26484 **    unixShm.pFile
26485 **    unixShm.id
26486 **
26487 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26488 ** while accessing any read/write fields.
26489 */
26490 struct unixShm {
26491   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26492   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26493   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26494   u8 id;                     /* Id of this connection within its unixShmNode */
26495   u16 sharedMask;            /* Mask of shared locks held */
26496   u16 exclMask;              /* Mask of exclusive locks held */
26497 };
26498
26499 /*
26500 ** Constants used for locking
26501 */
26502 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26503 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26504
26505 /*
26506 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26507 **
26508 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26509 ** otherwise.
26510 */
26511 static int unixShmSystemLock(
26512   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26513   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26514   int ofst,              /* First byte of the locking range */
26515   int n                  /* Number of bytes to lock */
26516 ){
26517   struct flock f;       /* The posix advisory locking structure */
26518   int rc = SQLITE_OK;   /* Result code form fcntl() */
26519
26520   /* Access to the unixShmNode object is serialized by the caller */
26521   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26522
26523   /* Shared locks never span more than one byte */
26524   assert( n==1 || lockType!=F_RDLCK );
26525
26526   /* Locks are within range */
26527   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26528
26529   if( pShmNode->h>=0 ){
26530     /* Initialize the locking parameters */
26531     memset(&f, 0, sizeof(f));
26532     f.l_type = lockType;
26533     f.l_whence = SEEK_SET;
26534     f.l_start = ofst;
26535     f.l_len = n;
26536
26537     rc = osFcntl(pShmNode->h, F_SETLK, &f);
26538     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26539   }
26540
26541   /* Update the global lock state and do debug tracing */
26542 #ifdef SQLITE_DEBUG
26543   { u16 mask;
26544   OSTRACE(("SHM-LOCK "));
26545   mask = (1<<(ofst+n)) - (1<<ofst);
26546   if( rc==SQLITE_OK ){
26547     if( lockType==F_UNLCK ){
26548       OSTRACE(("unlock %d ok", ofst));
26549       pShmNode->exclMask &= ~mask;
26550       pShmNode->sharedMask &= ~mask;
26551     }else if( lockType==F_RDLCK ){
26552       OSTRACE(("read-lock %d ok", ofst));
26553       pShmNode->exclMask &= ~mask;
26554       pShmNode->sharedMask |= mask;
26555     }else{
26556       assert( lockType==F_WRLCK );
26557       OSTRACE(("write-lock %d ok", ofst));
26558       pShmNode->exclMask |= mask;
26559       pShmNode->sharedMask &= ~mask;
26560     }
26561   }else{
26562     if( lockType==F_UNLCK ){
26563       OSTRACE(("unlock %d failed", ofst));
26564     }else if( lockType==F_RDLCK ){
26565       OSTRACE(("read-lock failed"));
26566     }else{
26567       assert( lockType==F_WRLCK );
26568       OSTRACE(("write-lock %d failed", ofst));
26569     }
26570   }
26571   OSTRACE((" - afterwards %03x,%03x\n",
26572            pShmNode->sharedMask, pShmNode->exclMask));
26573   }
26574 #endif
26575
26576   return rc;        
26577 }
26578
26579
26580 /*
26581 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26582 **
26583 ** This is not a VFS shared-memory method; it is a utility function called
26584 ** by VFS shared-memory methods.
26585 */
26586 static void unixShmPurge(unixFile *pFd){
26587   unixShmNode *p = pFd->pInode->pShmNode;
26588   assert( unixMutexHeld() );
26589   if( p && p->nRef==0 ){
26590     int i;
26591     assert( p->pInode==pFd->pInode );
26592     sqlite3_mutex_free(p->mutex);
26593     for(i=0; i<p->nRegion; i++){
26594       if( p->h>=0 ){
26595         munmap(p->apRegion[i], p->szRegion);
26596       }else{
26597         sqlite3_free(p->apRegion[i]);
26598       }
26599     }
26600     sqlite3_free(p->apRegion);
26601     if( p->h>=0 ){
26602       robust_close(pFd, p->h, __LINE__);
26603       p->h = -1;
26604     }
26605     p->pInode->pShmNode = 0;
26606     sqlite3_free(p);
26607   }
26608 }
26609
26610 /*
26611 ** Open a shared-memory area associated with open database file pDbFd.  
26612 ** This particular implementation uses mmapped files.
26613 **
26614 ** The file used to implement shared-memory is in the same directory
26615 ** as the open database file and has the same name as the open database
26616 ** file with the "-shm" suffix added.  For example, if the database file
26617 ** is "/home/user1/config.db" then the file that is created and mmapped
26618 ** for shared memory will be called "/home/user1/config.db-shm".  
26619 **
26620 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26621 ** some other tmpfs mount. But if a file in a different directory
26622 ** from the database file is used, then differing access permissions
26623 ** or a chroot() might cause two different processes on the same
26624 ** database to end up using different files for shared memory - 
26625 ** meaning that their memory would not really be shared - resulting
26626 ** in database corruption.  Nevertheless, this tmpfs file usage
26627 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26628 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26629 ** option results in an incompatible build of SQLite;  builds of SQLite
26630 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26631 ** same database file at the same time, database corruption will likely
26632 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26633 ** "unsupported" and may go away in a future SQLite release.
26634 **
26635 ** When opening a new shared-memory file, if no other instances of that
26636 ** file are currently open, in this process or in other processes, then
26637 ** the file must be truncated to zero length or have its header cleared.
26638 **
26639 ** If the original database file (pDbFd) is using the "unix-excl" VFS
26640 ** that means that an exclusive lock is held on the database file and
26641 ** that no other processes are able to read or write the database.  In
26642 ** that case, we do not really need shared memory.  No shared memory
26643 ** file is created.  The shared memory will be simulated with heap memory.
26644 */
26645 static int unixOpenSharedMemory(unixFile *pDbFd){
26646   struct unixShm *p = 0;          /* The connection to be opened */
26647   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26648   int rc;                         /* Result code */
26649   unixInodeInfo *pInode;          /* The inode of fd */
26650   char *zShmFilename;             /* Name of the file used for SHM */
26651   int nShmFilename;               /* Size of the SHM filename in bytes */
26652
26653   /* Allocate space for the new unixShm object. */
26654   p = sqlite3_malloc( sizeof(*p) );
26655   if( p==0 ) return SQLITE_NOMEM;
26656   memset(p, 0, sizeof(*p));
26657   assert( pDbFd->pShm==0 );
26658
26659   /* Check to see if a unixShmNode object already exists. Reuse an existing
26660   ** one if present. Create a new one if necessary.
26661   */
26662   unixEnterMutex();
26663   pInode = pDbFd->pInode;
26664   pShmNode = pInode->pShmNode;
26665   if( pShmNode==0 ){
26666     struct stat sStat;                 /* fstat() info for database file */
26667
26668     /* Call fstat() to figure out the permissions on the database file. If
26669     ** a new *-shm file is created, an attempt will be made to create it
26670     ** with the same permissions.
26671     */
26672     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
26673       rc = SQLITE_IOERR_FSTAT;
26674       goto shm_open_err;
26675     }
26676
26677 #ifdef SQLITE_SHM_DIRECTORY
26678     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
26679 #else
26680     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
26681 #endif
26682     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26683     if( pShmNode==0 ){
26684       rc = SQLITE_NOMEM;
26685       goto shm_open_err;
26686     }
26687     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
26688     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26689 #ifdef SQLITE_SHM_DIRECTORY
26690     sqlite3_snprintf(nShmFilename, zShmFilename, 
26691                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26692                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26693 #else
26694     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26695     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
26696 #endif
26697     pShmNode->h = -1;
26698     pDbFd->pInode->pShmNode = pShmNode;
26699     pShmNode->pInode = pDbFd->pInode;
26700     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26701     if( pShmNode->mutex==0 ){
26702       rc = SQLITE_NOMEM;
26703       goto shm_open_err;
26704     }
26705
26706     if( pInode->bProcessLock==0 ){
26707       int openFlags = O_RDWR | O_CREAT;
26708       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
26709         openFlags = O_RDONLY;
26710         pShmNode->isReadonly = 1;
26711       }
26712       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
26713       if( pShmNode->h<0 ){
26714         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
26715         goto shm_open_err;
26716       }
26717
26718       /* If this process is running as root, make sure that the SHM file
26719       ** is owned by the same user that owns the original database.  Otherwise,
26720       ** the original owner will not be able to connect.
26721       */
26722       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
26723   
26724       /* Check to see if another process is holding the dead-man switch.
26725       ** If not, truncate the file to zero length. 
26726       */
26727       rc = SQLITE_OK;
26728       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26729         if( robust_ftruncate(pShmNode->h, 0) ){
26730           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
26731         }
26732       }
26733       if( rc==SQLITE_OK ){
26734         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26735       }
26736       if( rc ) goto shm_open_err;
26737     }
26738   }
26739
26740   /* Make the new connection a child of the unixShmNode */
26741   p->pShmNode = pShmNode;
26742 #ifdef SQLITE_DEBUG
26743   p->id = pShmNode->nextShmId++;
26744 #endif
26745   pShmNode->nRef++;
26746   pDbFd->pShm = p;
26747   unixLeaveMutex();
26748
26749   /* The reference count on pShmNode has already been incremented under
26750   ** the cover of the unixEnterMutex() mutex and the pointer from the
26751   ** new (struct unixShm) object to the pShmNode has been set. All that is
26752   ** left to do is to link the new object into the linked list starting
26753   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26754   ** mutex.
26755   */
26756   sqlite3_mutex_enter(pShmNode->mutex);
26757   p->pNext = pShmNode->pFirst;
26758   pShmNode->pFirst = p;
26759   sqlite3_mutex_leave(pShmNode->mutex);
26760   return SQLITE_OK;
26761
26762   /* Jump here on any error */
26763 shm_open_err:
26764   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26765   sqlite3_free(p);
26766   unixLeaveMutex();
26767   return rc;
26768 }
26769
26770 /*
26771 ** This function is called to obtain a pointer to region iRegion of the 
26772 ** shared-memory associated with the database file fd. Shared-memory regions 
26773 ** are numbered starting from zero. Each shared-memory region is szRegion 
26774 ** bytes in size.
26775 **
26776 ** If an error occurs, an error code is returned and *pp is set to NULL.
26777 **
26778 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26779 ** region has not been allocated (by any client, including one running in a
26780 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
26781 ** bExtend is non-zero and the requested shared-memory region has not yet 
26782 ** been allocated, it is allocated by this function.
26783 **
26784 ** If the shared-memory region has already been allocated or is allocated by
26785 ** this call as described above, then it is mapped into this processes 
26786 ** address space (if it is not already), *pp is set to point to the mapped 
26787 ** memory and SQLITE_OK returned.
26788 */
26789 static int unixShmMap(
26790   sqlite3_file *fd,               /* Handle open on database file */
26791   int iRegion,                    /* Region to retrieve */
26792   int szRegion,                   /* Size of regions */
26793   int bExtend,                    /* True to extend file if necessary */
26794   void volatile **pp              /* OUT: Mapped memory */
26795 ){
26796   unixFile *pDbFd = (unixFile*)fd;
26797   unixShm *p;
26798   unixShmNode *pShmNode;
26799   int rc = SQLITE_OK;
26800
26801   /* If the shared-memory file has not yet been opened, open it now. */
26802   if( pDbFd->pShm==0 ){
26803     rc = unixOpenSharedMemory(pDbFd);
26804     if( rc!=SQLITE_OK ) return rc;
26805   }
26806
26807   p = pDbFd->pShm;
26808   pShmNode = p->pShmNode;
26809   sqlite3_mutex_enter(pShmNode->mutex);
26810   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26811   assert( pShmNode->pInode==pDbFd->pInode );
26812   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
26813   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
26814
26815   if( pShmNode->nRegion<=iRegion ){
26816     char **apNew;                      /* New apRegion[] array */
26817     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26818     struct stat sStat;                 /* Used by fstat() */
26819
26820     pShmNode->szRegion = szRegion;
26821
26822     if( pShmNode->h>=0 ){
26823       /* The requested region is not mapped into this processes address space.
26824       ** Check to see if it has been allocated (i.e. if the wal-index file is
26825       ** large enough to contain the requested region).
26826       */
26827       if( osFstat(pShmNode->h, &sStat) ){
26828         rc = SQLITE_IOERR_SHMSIZE;
26829         goto shmpage_out;
26830       }
26831   
26832       if( sStat.st_size<nByte ){
26833         /* The requested memory region does not exist. If bExtend is set to
26834         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26835         **
26836         ** Alternatively, if bExtend is true, use ftruncate() to allocate
26837         ** the requested memory region.
26838         */
26839         if( !bExtend ) goto shmpage_out;
26840         if( robust_ftruncate(pShmNode->h, nByte) ){
26841           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
26842                             pShmNode->zFilename);
26843           goto shmpage_out;
26844         }
26845       }
26846     }
26847
26848     /* Map the requested memory region into this processes address space. */
26849     apNew = (char **)sqlite3_realloc(
26850         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26851     );
26852     if( !apNew ){
26853       rc = SQLITE_IOERR_NOMEM;
26854       goto shmpage_out;
26855     }
26856     pShmNode->apRegion = apNew;
26857     while(pShmNode->nRegion<=iRegion){
26858       void *pMem;
26859       if( pShmNode->h>=0 ){
26860         pMem = mmap(0, szRegion,
26861             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
26862             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
26863         );
26864         if( pMem==MAP_FAILED ){
26865           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
26866           goto shmpage_out;
26867         }
26868       }else{
26869         pMem = sqlite3_malloc(szRegion);
26870         if( pMem==0 ){
26871           rc = SQLITE_NOMEM;
26872           goto shmpage_out;
26873         }
26874         memset(pMem, 0, szRegion);
26875       }
26876       pShmNode->apRegion[pShmNode->nRegion] = pMem;
26877       pShmNode->nRegion++;
26878     }
26879   }
26880
26881 shmpage_out:
26882   if( pShmNode->nRegion>iRegion ){
26883     *pp = pShmNode->apRegion[iRegion];
26884   }else{
26885     *pp = 0;
26886   }
26887   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
26888   sqlite3_mutex_leave(pShmNode->mutex);
26889   return rc;
26890 }
26891
26892 /*
26893 ** Change the lock state for a shared-memory segment.
26894 **
26895 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26896 ** different here than in posix.  In xShmLock(), one can go from unlocked
26897 ** to shared and back or from unlocked to exclusive and back.  But one may
26898 ** not go from shared to exclusive or from exclusive to shared.
26899 */
26900 static int unixShmLock(
26901   sqlite3_file *fd,          /* Database file holding the shared memory */
26902   int ofst,                  /* First lock to acquire or release */
26903   int n,                     /* Number of locks to acquire or release */
26904   int flags                  /* What to do with the lock */
26905 ){
26906   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26907   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26908   unixShm *pX;                          /* For looping over all siblings */
26909   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26910   int rc = SQLITE_OK;                   /* Result code */
26911   u16 mask;                             /* Mask of locks to take or release */
26912
26913   assert( pShmNode==pDbFd->pInode->pShmNode );
26914   assert( pShmNode->pInode==pDbFd->pInode );
26915   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26916   assert( n>=1 );
26917   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26918        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26919        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26920        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26921   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26922   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
26923   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
26924
26925   mask = (1<<(ofst+n)) - (1<<ofst);
26926   assert( n>1 || mask==(1<<ofst) );
26927   sqlite3_mutex_enter(pShmNode->mutex);
26928   if( flags & SQLITE_SHM_UNLOCK ){
26929     u16 allMask = 0; /* Mask of locks held by siblings */
26930
26931     /* See if any siblings hold this same lock */
26932     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26933       if( pX==p ) continue;
26934       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26935       allMask |= pX->sharedMask;
26936     }
26937
26938     /* Unlock the system-level locks */
26939     if( (mask & allMask)==0 ){
26940       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26941     }else{
26942       rc = SQLITE_OK;
26943     }
26944
26945     /* Undo the local locks */
26946     if( rc==SQLITE_OK ){
26947       p->exclMask &= ~mask;
26948       p->sharedMask &= ~mask;
26949     } 
26950   }else if( flags & SQLITE_SHM_SHARED ){
26951     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26952
26953     /* Find out which shared locks are already held by sibling connections.
26954     ** If any sibling already holds an exclusive lock, go ahead and return
26955     ** SQLITE_BUSY.
26956     */
26957     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26958       if( (pX->exclMask & mask)!=0 ){
26959         rc = SQLITE_BUSY;
26960         break;
26961       }
26962       allShared |= pX->sharedMask;
26963     }
26964
26965     /* Get shared locks at the system level, if necessary */
26966     if( rc==SQLITE_OK ){
26967       if( (allShared & mask)==0 ){
26968         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26969       }else{
26970         rc = SQLITE_OK;
26971       }
26972     }
26973
26974     /* Get the local shared locks */
26975     if( rc==SQLITE_OK ){
26976       p->sharedMask |= mask;
26977     }
26978   }else{
26979     /* Make sure no sibling connections hold locks that will block this
26980     ** lock.  If any do, return SQLITE_BUSY right away.
26981     */
26982     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26983       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26984         rc = SQLITE_BUSY;
26985         break;
26986       }
26987     }
26988   
26989     /* Get the exclusive locks at the system level.  Then if successful
26990     ** also mark the local connection as being locked.
26991     */
26992     if( rc==SQLITE_OK ){
26993       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26994       if( rc==SQLITE_OK ){
26995         assert( (p->sharedMask & mask)==0 );
26996         p->exclMask |= mask;
26997       }
26998     }
26999   }
27000   sqlite3_mutex_leave(pShmNode->mutex);
27001   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27002            p->id, getpid(), p->sharedMask, p->exclMask));
27003   return rc;
27004 }
27005
27006 /*
27007 ** Implement a memory barrier or memory fence on shared memory.  
27008 **
27009 ** All loads and stores begun before the barrier must complete before
27010 ** any load or store begun after the barrier.
27011 */
27012 static void unixShmBarrier(
27013   sqlite3_file *fd                /* Database file holding the shared memory */
27014 ){
27015   UNUSED_PARAMETER(fd);
27016   unixEnterMutex();
27017   unixLeaveMutex();
27018 }
27019
27020 /*
27021 ** Close a connection to shared-memory.  Delete the underlying 
27022 ** storage if deleteFlag is true.
27023 **
27024 ** If there is no shared memory associated with the connection then this
27025 ** routine is a harmless no-op.
27026 */
27027 static int unixShmUnmap(
27028   sqlite3_file *fd,               /* The underlying database file */
27029   int deleteFlag                  /* Delete shared-memory if true */
27030 ){
27031   unixShm *p;                     /* The connection to be closed */
27032   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27033   unixShm **pp;                   /* For looping over sibling connections */
27034   unixFile *pDbFd;                /* The underlying database file */
27035
27036   pDbFd = (unixFile*)fd;
27037   p = pDbFd->pShm;
27038   if( p==0 ) return SQLITE_OK;
27039   pShmNode = p->pShmNode;
27040
27041   assert( pShmNode==pDbFd->pInode->pShmNode );
27042   assert( pShmNode->pInode==pDbFd->pInode );
27043
27044   /* Remove connection p from the set of connections associated
27045   ** with pShmNode */
27046   sqlite3_mutex_enter(pShmNode->mutex);
27047   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27048   *pp = p->pNext;
27049
27050   /* Free the connection p */
27051   sqlite3_free(p);
27052   pDbFd->pShm = 0;
27053   sqlite3_mutex_leave(pShmNode->mutex);
27054
27055   /* If pShmNode->nRef has reached 0, then close the underlying
27056   ** shared-memory file, too */
27057   unixEnterMutex();
27058   assert( pShmNode->nRef>0 );
27059   pShmNode->nRef--;
27060   if( pShmNode->nRef==0 ){
27061     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27062     unixShmPurge(pDbFd);
27063   }
27064   unixLeaveMutex();
27065
27066   return SQLITE_OK;
27067 }
27068
27069
27070 #else
27071 # define unixShmMap     0
27072 # define unixShmLock    0
27073 # define unixShmBarrier 0
27074 # define unixShmUnmap   0
27075 #endif /* #ifndef SQLITE_OMIT_WAL */
27076
27077 /*
27078 ** Here ends the implementation of all sqlite3_file methods.
27079 **
27080 ********************** End sqlite3_file Methods *******************************
27081 ******************************************************************************/
27082
27083 /*
27084 ** This division contains definitions of sqlite3_io_methods objects that
27085 ** implement various file locking strategies.  It also contains definitions
27086 ** of "finder" functions.  A finder-function is used to locate the appropriate
27087 ** sqlite3_io_methods object for a particular database file.  The pAppData
27088 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27089 ** the correct finder-function for that VFS.
27090 **
27091 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27092 ** object.  The only interesting finder-function is autolockIoFinder, which
27093 ** looks at the filesystem type and tries to guess the best locking
27094 ** strategy from that.
27095 **
27096 ** For finder-funtion F, two objects are created:
27097 **
27098 **    (1) The real finder-function named "FImpt()".
27099 **
27100 **    (2) A constant pointer to this function named just "F".
27101 **
27102 **
27103 ** A pointer to the F pointer is used as the pAppData value for VFS
27104 ** objects.  We have to do this instead of letting pAppData point
27105 ** directly at the finder-function since C90 rules prevent a void*
27106 ** from be cast into a function pointer.
27107 **
27108 **
27109 ** Each instance of this macro generates two objects:
27110 **
27111 **   *  A constant sqlite3_io_methods object call METHOD that has locking
27112 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27113 **
27114 **   *  An I/O method finder function called FINDER that returns a pointer
27115 **      to the METHOD object in the previous bullet.
27116 */
27117 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27118 static const sqlite3_io_methods METHOD = {                                   \
27119    VERSION,                    /* iVersion */                                \
27120    CLOSE,                      /* xClose */                                  \
27121    unixRead,                   /* xRead */                                   \
27122    unixWrite,                  /* xWrite */                                  \
27123    unixTruncate,               /* xTruncate */                               \
27124    unixSync,                   /* xSync */                                   \
27125    unixFileSize,               /* xFileSize */                               \
27126    LOCK,                       /* xLock */                                   \
27127    UNLOCK,                     /* xUnlock */                                 \
27128    CKLOCK,                     /* xCheckReservedLock */                      \
27129    unixFileControl,            /* xFileControl */                            \
27130    unixSectorSize,             /* xSectorSize */                             \
27131    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27132    unixShmMap,                 /* xShmMap */                                 \
27133    unixShmLock,                /* xShmLock */                                \
27134    unixShmBarrier,             /* xShmBarrier */                             \
27135    unixShmUnmap                /* xShmUnmap */                               \
27136 };                                                                           \
27137 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27138   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27139   return &METHOD;                                                            \
27140 }                                                                            \
27141 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27142     = FINDER##Impl;
27143
27144 /*
27145 ** Here are all of the sqlite3_io_methods objects for each of the
27146 ** locking strategies.  Functions that return pointers to these methods
27147 ** are also created.
27148 */
27149 IOMETHODS(
27150   posixIoFinder,            /* Finder function name */
27151   posixIoMethods,           /* sqlite3_io_methods object name */
27152   2,                        /* shared memory is enabled */
27153   unixClose,                /* xClose method */
27154   unixLock,                 /* xLock method */
27155   unixUnlock,               /* xUnlock method */
27156   unixCheckReservedLock     /* xCheckReservedLock method */
27157 )
27158 IOMETHODS(
27159   nolockIoFinder,           /* Finder function name */
27160   nolockIoMethods,          /* sqlite3_io_methods object name */
27161   1,                        /* shared memory is disabled */
27162   nolockClose,              /* xClose method */
27163   nolockLock,               /* xLock method */
27164   nolockUnlock,             /* xUnlock method */
27165   nolockCheckReservedLock   /* xCheckReservedLock method */
27166 )
27167 IOMETHODS(
27168   dotlockIoFinder,          /* Finder function name */
27169   dotlockIoMethods,         /* sqlite3_io_methods object name */
27170   1,                        /* shared memory is disabled */
27171   dotlockClose,             /* xClose method */
27172   dotlockLock,              /* xLock method */
27173   dotlockUnlock,            /* xUnlock method */
27174   dotlockCheckReservedLock  /* xCheckReservedLock method */
27175 )
27176
27177 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27178 IOMETHODS(
27179   flockIoFinder,            /* Finder function name */
27180   flockIoMethods,           /* sqlite3_io_methods object name */
27181   1,                        /* shared memory is disabled */
27182   flockClose,               /* xClose method */
27183   flockLock,                /* xLock method */
27184   flockUnlock,              /* xUnlock method */
27185   flockCheckReservedLock    /* xCheckReservedLock method */
27186 )
27187 #endif
27188
27189 #if OS_VXWORKS
27190 IOMETHODS(
27191   semIoFinder,              /* Finder function name */
27192   semIoMethods,             /* sqlite3_io_methods object name */
27193   1,                        /* shared memory is disabled */
27194   semClose,                 /* xClose method */
27195   semLock,                  /* xLock method */
27196   semUnlock,                /* xUnlock method */
27197   semCheckReservedLock      /* xCheckReservedLock method */
27198 )
27199 #endif
27200
27201 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27202 IOMETHODS(
27203   afpIoFinder,              /* Finder function name */
27204   afpIoMethods,             /* sqlite3_io_methods object name */
27205   1,                        /* shared memory is disabled */
27206   afpClose,                 /* xClose method */
27207   afpLock,                  /* xLock method */
27208   afpUnlock,                /* xUnlock method */
27209   afpCheckReservedLock      /* xCheckReservedLock method */
27210 )
27211 #endif
27212
27213 /*
27214 ** The proxy locking method is a "super-method" in the sense that it
27215 ** opens secondary file descriptors for the conch and lock files and
27216 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
27217 ** secondary files.  For this reason, the division that implements
27218 ** proxy locking is located much further down in the file.  But we need
27219 ** to go ahead and define the sqlite3_io_methods and finder function
27220 ** for proxy locking here.  So we forward declare the I/O methods.
27221 */
27222 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27223 static int proxyClose(sqlite3_file*);
27224 static int proxyLock(sqlite3_file*, int);
27225 static int proxyUnlock(sqlite3_file*, int);
27226 static int proxyCheckReservedLock(sqlite3_file*, int*);
27227 IOMETHODS(
27228   proxyIoFinder,            /* Finder function name */
27229   proxyIoMethods,           /* sqlite3_io_methods object name */
27230   1,                        /* shared memory is disabled */
27231   proxyClose,               /* xClose method */
27232   proxyLock,                /* xLock method */
27233   proxyUnlock,              /* xUnlock method */
27234   proxyCheckReservedLock    /* xCheckReservedLock method */
27235 )
27236 #endif
27237
27238 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
27239 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27240 IOMETHODS(
27241   nfsIoFinder,               /* Finder function name */
27242   nfsIoMethods,              /* sqlite3_io_methods object name */
27243   1,                         /* shared memory is disabled */
27244   unixClose,                 /* xClose method */
27245   unixLock,                  /* xLock method */
27246   nfsUnlock,                 /* xUnlock method */
27247   unixCheckReservedLock      /* xCheckReservedLock method */
27248 )
27249 #endif
27250
27251 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27252 /* 
27253 ** This "finder" function attempts to determine the best locking strategy 
27254 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27255 ** object that implements that strategy.
27256 **
27257 ** This is for MacOSX only.
27258 */
27259 static const sqlite3_io_methods *autolockIoFinderImpl(
27260   const char *filePath,    /* name of the database file */
27261   unixFile *pNew           /* open file object for the database file */
27262 ){
27263   static const struct Mapping {
27264     const char *zFilesystem;              /* Filesystem type name */
27265     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
27266   } aMap[] = {
27267     { "hfs",    &posixIoMethods },
27268     { "ufs",    &posixIoMethods },
27269     { "afpfs",  &afpIoMethods },
27270     { "smbfs",  &afpIoMethods },
27271     { "webdav", &nolockIoMethods },
27272     { 0, 0 }
27273   };
27274   int i;
27275   struct statfs fsInfo;
27276   struct flock lockInfo;
27277
27278   if( !filePath ){
27279     /* If filePath==NULL that means we are dealing with a transient file
27280     ** that does not need to be locked. */
27281     return &nolockIoMethods;
27282   }
27283   if( statfs(filePath, &fsInfo) != -1 ){
27284     if( fsInfo.f_flags & MNT_RDONLY ){
27285       return &nolockIoMethods;
27286     }
27287     for(i=0; aMap[i].zFilesystem; i++){
27288       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
27289         return aMap[i].pMethods;
27290       }
27291     }
27292   }
27293
27294   /* Default case. Handles, amongst others, "nfs".
27295   ** Test byte-range lock using fcntl(). If the call succeeds, 
27296   ** assume that the file-system supports POSIX style locks. 
27297   */
27298   lockInfo.l_len = 1;
27299   lockInfo.l_start = 0;
27300   lockInfo.l_whence = SEEK_SET;
27301   lockInfo.l_type = F_RDLCK;
27302   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27303     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
27304       return &nfsIoMethods;
27305     } else {
27306       return &posixIoMethods;
27307     }
27308   }else{
27309     return &dotlockIoMethods;
27310   }
27311 }
27312 static const sqlite3_io_methods 
27313   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27314
27315 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27316
27317 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
27318 /* 
27319 ** This "finder" function attempts to determine the best locking strategy 
27320 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27321 ** object that implements that strategy.
27322 **
27323 ** This is for VXWorks only.
27324 */
27325 static const sqlite3_io_methods *autolockIoFinderImpl(
27326   const char *filePath,    /* name of the database file */
27327   unixFile *pNew           /* the open file object */
27328 ){
27329   struct flock lockInfo;
27330
27331   if( !filePath ){
27332     /* If filePath==NULL that means we are dealing with a transient file
27333     ** that does not need to be locked. */
27334     return &nolockIoMethods;
27335   }
27336
27337   /* Test if fcntl() is supported and use POSIX style locks.
27338   ** Otherwise fall back to the named semaphore method.
27339   */
27340   lockInfo.l_len = 1;
27341   lockInfo.l_start = 0;
27342   lockInfo.l_whence = SEEK_SET;
27343   lockInfo.l_type = F_RDLCK;
27344   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27345     return &posixIoMethods;
27346   }else{
27347     return &semIoMethods;
27348   }
27349 }
27350 static const sqlite3_io_methods 
27351   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27352
27353 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27354
27355 /*
27356 ** An abstract type for a pointer to a IO method finder function:
27357 */
27358 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27359
27360
27361 /****************************************************************************
27362 **************************** sqlite3_vfs methods ****************************
27363 **
27364 ** This division contains the implementation of methods on the
27365 ** sqlite3_vfs object.
27366 */
27367
27368 /*
27369 ** Initialize the contents of the unixFile structure pointed to by pId.
27370 */
27371 static int fillInUnixFile(
27372   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27373   int h,                  /* Open file descriptor of file being opened */
27374   sqlite3_file *pId,      /* Write to the unixFile structure here */
27375   const char *zFilename,  /* Name of the file being opened */
27376   int ctrlFlags           /* Zero or more UNIXFILE_* values */
27377 ){
27378   const sqlite3_io_methods *pLockingStyle;
27379   unixFile *pNew = (unixFile *)pId;
27380   int rc = SQLITE_OK;
27381
27382   assert( pNew->pInode==NULL );
27383
27384   /* Usually the path zFilename should not be a relative pathname. The
27385   ** exception is when opening the proxy "conch" file in builds that
27386   ** include the special Apple locking styles.
27387   */
27388 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27389   assert( zFilename==0 || zFilename[0]=='/' 
27390     || pVfs->pAppData==(void*)&autolockIoFinder );
27391 #else
27392   assert( zFilename==0 || zFilename[0]=='/' );
27393 #endif
27394
27395   /* No locking occurs in temporary files */
27396   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
27397
27398   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27399   pNew->h = h;
27400   pNew->pVfs = pVfs;
27401   pNew->zPath = zFilename;
27402   pNew->ctrlFlags = (u8)ctrlFlags;
27403   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
27404                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
27405     pNew->ctrlFlags |= UNIXFILE_PSOW;
27406   }
27407   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
27408     pNew->ctrlFlags |= UNIXFILE_EXCL;
27409   }
27410
27411 #if OS_VXWORKS
27412   pNew->pId = vxworksFindFileId(zFilename);
27413   if( pNew->pId==0 ){
27414     ctrlFlags |= UNIXFILE_NOLOCK;
27415     rc = SQLITE_NOMEM;
27416   }
27417 #endif
27418
27419   if( ctrlFlags & UNIXFILE_NOLOCK ){
27420     pLockingStyle = &nolockIoMethods;
27421   }else{
27422     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27423 #if SQLITE_ENABLE_LOCKING_STYLE
27424     /* Cache zFilename in the locking context (AFP and dotlock override) for
27425     ** proxyLock activation is possible (remote proxy is based on db name)
27426     ** zFilename remains valid until file is closed, to support */
27427     pNew->lockingContext = (void*)zFilename;
27428 #endif
27429   }
27430
27431   if( pLockingStyle == &posixIoMethods
27432 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27433     || pLockingStyle == &nfsIoMethods
27434 #endif
27435   ){
27436     unixEnterMutex();
27437     rc = findInodeInfo(pNew, &pNew->pInode);
27438     if( rc!=SQLITE_OK ){
27439       /* If an error occured in findInodeInfo(), close the file descriptor
27440       ** immediately, before releasing the mutex. findInodeInfo() may fail
27441       ** in two scenarios:
27442       **
27443       **   (a) A call to fstat() failed.
27444       **   (b) A malloc failed.
27445       **
27446       ** Scenario (b) may only occur if the process is holding no other
27447       ** file descriptors open on the same file. If there were other file
27448       ** descriptors on this file, then no malloc would be required by
27449       ** findInodeInfo(). If this is the case, it is quite safe to close
27450       ** handle h - as it is guaranteed that no posix locks will be released
27451       ** by doing so.
27452       **
27453       ** If scenario (a) caused the error then things are not so safe. The
27454       ** implicit assumption here is that if fstat() fails, things are in
27455       ** such bad shape that dropping a lock or two doesn't matter much.
27456       */
27457       robust_close(pNew, h, __LINE__);
27458       h = -1;
27459     }
27460     unixLeaveMutex();
27461   }
27462
27463 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27464   else if( pLockingStyle == &afpIoMethods ){
27465     /* AFP locking uses the file path so it needs to be included in
27466     ** the afpLockingContext.
27467     */
27468     afpLockingContext *pCtx;
27469     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27470     if( pCtx==0 ){
27471       rc = SQLITE_NOMEM;
27472     }else{
27473       /* NB: zFilename exists and remains valid until the file is closed
27474       ** according to requirement F11141.  So we do not need to make a
27475       ** copy of the filename. */
27476       pCtx->dbPath = zFilename;
27477       pCtx->reserved = 0;
27478       srandomdev();
27479       unixEnterMutex();
27480       rc = findInodeInfo(pNew, &pNew->pInode);
27481       if( rc!=SQLITE_OK ){
27482         sqlite3_free(pNew->lockingContext);
27483         robust_close(pNew, h, __LINE__);
27484         h = -1;
27485       }
27486       unixLeaveMutex();        
27487     }
27488   }
27489 #endif
27490
27491   else if( pLockingStyle == &dotlockIoMethods ){
27492     /* Dotfile locking uses the file path so it needs to be included in
27493     ** the dotlockLockingContext 
27494     */
27495     char *zLockFile;
27496     int nFilename;
27497     assert( zFilename!=0 );
27498     nFilename = (int)strlen(zFilename) + 6;
27499     zLockFile = (char *)sqlite3_malloc(nFilename);
27500     if( zLockFile==0 ){
27501       rc = SQLITE_NOMEM;
27502     }else{
27503       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27504     }
27505     pNew->lockingContext = zLockFile;
27506   }
27507
27508 #if OS_VXWORKS
27509   else if( pLockingStyle == &semIoMethods ){
27510     /* Named semaphore locking uses the file path so it needs to be
27511     ** included in the semLockingContext
27512     */
27513     unixEnterMutex();
27514     rc = findInodeInfo(pNew, &pNew->pInode);
27515     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27516       char *zSemName = pNew->pInode->aSemName;
27517       int n;
27518       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27519                        pNew->pId->zCanonicalName);
27520       for( n=1; zSemName[n]; n++ )
27521         if( zSemName[n]=='/' ) zSemName[n] = '_';
27522       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27523       if( pNew->pInode->pSem == SEM_FAILED ){
27524         rc = SQLITE_NOMEM;
27525         pNew->pInode->aSemName[0] = '\0';
27526       }
27527     }
27528     unixLeaveMutex();
27529   }
27530 #endif
27531   
27532   pNew->lastErrno = 0;
27533 #if OS_VXWORKS
27534   if( rc!=SQLITE_OK ){
27535     if( h>=0 ) robust_close(pNew, h, __LINE__);
27536     h = -1;
27537     osUnlink(zFilename);
27538     isDelete = 0;
27539   }
27540   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
27541 #endif
27542   if( rc!=SQLITE_OK ){
27543     if( h>=0 ) robust_close(pNew, h, __LINE__);
27544   }else{
27545     pNew->pMethod = pLockingStyle;
27546     OpenCounter(+1);
27547   }
27548   return rc;
27549 }
27550
27551 /*
27552 ** Return the name of a directory in which to put temporary files.
27553 ** If no suitable temporary file directory can be found, return NULL.
27554 */
27555 static const char *unixTempFileDir(void){
27556   static const char *azDirs[] = {
27557      0,
27558      0,
27559      "/var/tmp",
27560      "/usr/tmp",
27561      "/tmp",
27562      0        /* List terminator */
27563   };
27564   unsigned int i;
27565   struct stat buf;
27566   const char *zDir = 0;
27567
27568   azDirs[0] = sqlite3_temp_directory;
27569   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27570   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27571     if( zDir==0 ) continue;
27572     if( osStat(zDir, &buf) ) continue;
27573     if( !S_ISDIR(buf.st_mode) ) continue;
27574     if( osAccess(zDir, 07) ) continue;
27575     break;
27576   }
27577   return zDir;
27578 }
27579
27580 /*
27581 ** Create a temporary file name in zBuf.  zBuf must be allocated
27582 ** by the calling process and must be big enough to hold at least
27583 ** pVfs->mxPathname bytes.
27584 */
27585 static int unixGetTempname(int nBuf, char *zBuf){
27586   static const unsigned char zChars[] =
27587     "abcdefghijklmnopqrstuvwxyz"
27588     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27589     "0123456789";
27590   unsigned int i, j;
27591   const char *zDir;
27592
27593   /* It's odd to simulate an io-error here, but really this is just
27594   ** using the io-error infrastructure to test that SQLite handles this
27595   ** function failing. 
27596   */
27597   SimulateIOError( return SQLITE_IOERR );
27598
27599   zDir = unixTempFileDir();
27600   if( zDir==0 ) zDir = ".";
27601
27602   /* Check that the output buffer is large enough for the temporary file 
27603   ** name. If it is not, return SQLITE_ERROR.
27604   */
27605   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
27606     return SQLITE_ERROR;
27607   }
27608
27609   do{
27610     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27611     j = (int)strlen(zBuf);
27612     sqlite3_randomness(15, &zBuf[j]);
27613     for(i=0; i<15; i++, j++){
27614       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27615     }
27616     zBuf[j] = 0;
27617     zBuf[j+1] = 0;
27618   }while( osAccess(zBuf,0)==0 );
27619   return SQLITE_OK;
27620 }
27621
27622 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27623 /*
27624 ** Routine to transform a unixFile into a proxy-locking unixFile.
27625 ** Implementation in the proxy-lock division, but used by unixOpen()
27626 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27627 */
27628 static int proxyTransformUnixFile(unixFile*, const char*);
27629 #endif
27630
27631 /*
27632 ** Search for an unused file descriptor that was opened on the database 
27633 ** file (not a journal or master-journal file) identified by pathname
27634 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27635 ** argument to this function.
27636 **
27637 ** Such a file descriptor may exist if a database connection was closed
27638 ** but the associated file descriptor could not be closed because some
27639 ** other file descriptor open on the same file is holding a file-lock.
27640 ** Refer to comments in the unixClose() function and the lengthy comment
27641 ** describing "Posix Advisory Locking" at the start of this file for 
27642 ** further details. Also, ticket #4018.
27643 **
27644 ** If a suitable file descriptor is found, then it is returned. If no
27645 ** such file descriptor is located, -1 is returned.
27646 */
27647 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27648   UnixUnusedFd *pUnused = 0;
27649
27650   /* Do not search for an unused file descriptor on vxworks. Not because
27651   ** vxworks would not benefit from the change (it might, we're not sure),
27652   ** but because no way to test it is currently available. It is better 
27653   ** not to risk breaking vxworks support for the sake of such an obscure 
27654   ** feature.  */
27655 #if !OS_VXWORKS
27656   struct stat sStat;                   /* Results of stat() call */
27657
27658   /* A stat() call may fail for various reasons. If this happens, it is
27659   ** almost certain that an open() call on the same path will also fail.
27660   ** For this reason, if an error occurs in the stat() call here, it is
27661   ** ignored and -1 is returned. The caller will try to open a new file
27662   ** descriptor on the same path, fail, and return an error to SQLite.
27663   **
27664   ** Even if a subsequent open() call does succeed, the consequences of
27665   ** not searching for a resusable file descriptor are not dire.  */
27666   if( 0==osStat(zPath, &sStat) ){
27667     unixInodeInfo *pInode;
27668
27669     unixEnterMutex();
27670     pInode = inodeList;
27671     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27672                      || pInode->fileId.ino!=sStat.st_ino) ){
27673        pInode = pInode->pNext;
27674     }
27675     if( pInode ){
27676       UnixUnusedFd **pp;
27677       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27678       pUnused = *pp;
27679       if( pUnused ){
27680         *pp = pUnused->pNext;
27681       }
27682     }
27683     unixLeaveMutex();
27684   }
27685 #endif    /* if !OS_VXWORKS */
27686   return pUnused;
27687 }
27688
27689 /*
27690 ** This function is called by unixOpen() to determine the unix permissions
27691 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27692 ** and a value suitable for passing as the third argument to open(2) is
27693 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27694 ** returned and the value of *pMode is not modified.
27695 **
27696 ** In most cases cases, this routine sets *pMode to 0, which will become
27697 ** an indication to robust_open() to create the file using
27698 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
27699 ** But if the file being opened is a WAL or regular journal file, then 
27700 ** this function queries the file-system for the permissions on the 
27701 ** corresponding database file and sets *pMode to this value. Whenever 
27702 ** possible, WAL and journal files are created using the same permissions 
27703 ** as the associated database file.
27704 **
27705 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
27706 ** original filename is unavailable.  But 8_3_NAMES is only used for
27707 ** FAT filesystems and permissions do not matter there, so just use
27708 ** the default permissions.
27709 */
27710 static int findCreateFileMode(
27711   const char *zPath,              /* Path of file (possibly) being created */
27712   int flags,                      /* Flags passed as 4th argument to xOpen() */
27713   mode_t *pMode,                  /* OUT: Permissions to open file with */
27714   uid_t *pUid,                    /* OUT: uid to set on the file */
27715   gid_t *pGid                     /* OUT: gid to set on the file */
27716 ){
27717   int rc = SQLITE_OK;             /* Return Code */
27718   *pMode = 0;
27719   *pUid = 0;
27720   *pGid = 0;
27721   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27722     char zDb[MAX_PATHNAME+1];     /* Database file path */
27723     int nDb;                      /* Number of valid bytes in zDb */
27724     struct stat sStat;            /* Output of stat() on database file */
27725
27726     /* zPath is a path to a WAL or journal file. The following block derives
27727     ** the path to the associated database file from zPath. This block handles
27728     ** the following naming conventions:
27729     **
27730     **   "<path to db>-journal"
27731     **   "<path to db>-wal"
27732     **   "<path to db>-journalNN"
27733     **   "<path to db>-walNN"
27734     **
27735     ** where NN is a decimal number. The NN naming schemes are 
27736     ** used by the test_multiplex.c module.
27737     */
27738     nDb = sqlite3Strlen30(zPath) - 1; 
27739 #ifdef SQLITE_ENABLE_8_3_NAMES
27740     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
27741     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
27742 #else
27743     while( zPath[nDb]!='-' ){
27744       assert( nDb>0 );
27745       assert( zPath[nDb]!='\n' );
27746       nDb--;
27747     }
27748 #endif
27749     memcpy(zDb, zPath, nDb);
27750     zDb[nDb] = '\0';
27751
27752     if( 0==osStat(zDb, &sStat) ){
27753       *pMode = sStat.st_mode & 0777;
27754       *pUid = sStat.st_uid;
27755       *pGid = sStat.st_gid;
27756     }else{
27757       rc = SQLITE_IOERR_FSTAT;
27758     }
27759   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27760     *pMode = 0600;
27761   }
27762   return rc;
27763 }
27764
27765 /*
27766 ** Open the file zPath.
27767 ** 
27768 ** Previously, the SQLite OS layer used three functions in place of this
27769 ** one:
27770 **
27771 **     sqlite3OsOpenReadWrite();
27772 **     sqlite3OsOpenReadOnly();
27773 **     sqlite3OsOpenExclusive();
27774 **
27775 ** These calls correspond to the following combinations of flags:
27776 **
27777 **     ReadWrite() ->     (READWRITE | CREATE)
27778 **     ReadOnly()  ->     (READONLY) 
27779 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
27780 **
27781 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
27782 ** true, the file was configured to be automatically deleted when the
27783 ** file handle closed. To achieve the same effect using this new 
27784 ** interface, add the DELETEONCLOSE flag to those specified above for 
27785 ** OpenExclusive().
27786 */
27787 static int unixOpen(
27788   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
27789   const char *zPath,           /* Pathname of file to be opened */
27790   sqlite3_file *pFile,         /* The file descriptor to be filled in */
27791   int flags,                   /* Input flags to control the opening */
27792   int *pOutFlags               /* Output flags returned to SQLite core */
27793 ){
27794   unixFile *p = (unixFile *)pFile;
27795   int fd = -1;                   /* File descriptor returned by open() */
27796   int openFlags = 0;             /* Flags to pass to open() */
27797   int eType = flags&0xFFFFFF00;  /* Type of file to open */
27798   int noLock;                    /* True to omit locking primitives */
27799   int rc = SQLITE_OK;            /* Function Return Code */
27800   int ctrlFlags = 0;             /* UNIXFILE_* flags */
27801
27802   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
27803   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
27804   int isCreate     = (flags & SQLITE_OPEN_CREATE);
27805   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
27806   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
27807 #if SQLITE_ENABLE_LOCKING_STYLE
27808   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
27809 #endif
27810 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27811   struct statfs fsInfo;
27812 #endif
27813
27814   /* If creating a master or main-file journal, this function will open
27815   ** a file-descriptor on the directory too. The first time unixSync()
27816   ** is called the directory file descriptor will be fsync()ed and close()d.
27817   */
27818   int syncDir = (isCreate && (
27819         eType==SQLITE_OPEN_MASTER_JOURNAL 
27820      || eType==SQLITE_OPEN_MAIN_JOURNAL 
27821      || eType==SQLITE_OPEN_WAL
27822   ));
27823
27824   /* If argument zPath is a NULL pointer, this function is required to open
27825   ** a temporary file. Use this buffer to store the file name in.
27826   */
27827   char zTmpname[MAX_PATHNAME+2];
27828   const char *zName = zPath;
27829
27830   /* Check the following statements are true: 
27831   **
27832   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
27833   **   (b) if CREATE is set, then READWRITE must also be set, and
27834   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
27835   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
27836   */
27837   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
27838   assert(isCreate==0 || isReadWrite);
27839   assert(isExclusive==0 || isCreate);
27840   assert(isDelete==0 || isCreate);
27841
27842   /* The main DB, main journal, WAL file and master journal are never 
27843   ** automatically deleted. Nor are they ever temporary files.  */
27844   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27845   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27846   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27847   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
27848
27849   /* Assert that the upper layer has set one of the "file-type" flags. */
27850   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
27851        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
27852        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
27853        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
27854   );
27855
27856   memset(p, 0, sizeof(unixFile));
27857
27858   if( eType==SQLITE_OPEN_MAIN_DB ){
27859     UnixUnusedFd *pUnused;
27860     pUnused = findReusableFd(zName, flags);
27861     if( pUnused ){
27862       fd = pUnused->fd;
27863     }else{
27864       pUnused = sqlite3_malloc(sizeof(*pUnused));
27865       if( !pUnused ){
27866         return SQLITE_NOMEM;
27867       }
27868     }
27869     p->pUnused = pUnused;
27870
27871     /* Database filenames are double-zero terminated if they are not
27872     ** URIs with parameters.  Hence, they can always be passed into
27873     ** sqlite3_uri_parameter(). */
27874     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
27875
27876   }else if( !zName ){
27877     /* If zName is NULL, the upper layer is requesting a temp file. */
27878     assert(isDelete && !syncDir);
27879     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
27880     if( rc!=SQLITE_OK ){
27881       return rc;
27882     }
27883     zName = zTmpname;
27884
27885     /* Generated temporary filenames are always double-zero terminated
27886     ** for use by sqlite3_uri_parameter(). */
27887     assert( zName[strlen(zName)+1]==0 );
27888   }
27889
27890   /* Determine the value of the flags parameter passed to POSIX function
27891   ** open(). These must be calculated even if open() is not called, as
27892   ** they may be stored as part of the file handle and used by the 
27893   ** 'conch file' locking functions later on.  */
27894   if( isReadonly )  openFlags |= O_RDONLY;
27895   if( isReadWrite ) openFlags |= O_RDWR;
27896   if( isCreate )    openFlags |= O_CREAT;
27897   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
27898   openFlags |= (O_LARGEFILE|O_BINARY);
27899
27900   if( fd<0 ){
27901     mode_t openMode;              /* Permissions to create file with */
27902     uid_t uid;                    /* Userid for the file */
27903     gid_t gid;                    /* Groupid for the file */
27904     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
27905     if( rc!=SQLITE_OK ){
27906       assert( !p->pUnused );
27907       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27908       return rc;
27909     }
27910     fd = robust_open(zName, openFlags, openMode);
27911     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
27912     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27913       /* Failed to open the file for read/write access. Try read-only. */
27914       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27915       openFlags &= ~(O_RDWR|O_CREAT);
27916       flags |= SQLITE_OPEN_READONLY;
27917       openFlags |= O_RDONLY;
27918       isReadonly = 1;
27919       fd = robust_open(zName, openFlags, openMode);
27920     }
27921     if( fd<0 ){
27922       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
27923       goto open_finished;
27924     }
27925
27926     /* If this process is running as root and if creating a new rollback
27927     ** journal or WAL file, set the ownership of the journal or WAL to be
27928     ** the same as the original database.
27929     */
27930     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27931       osFchown(fd, uid, gid);
27932     }
27933   }
27934   assert( fd>=0 );
27935   if( pOutFlags ){
27936     *pOutFlags = flags;
27937   }
27938
27939   if( p->pUnused ){
27940     p->pUnused->fd = fd;
27941     p->pUnused->flags = flags;
27942   }
27943
27944   if( isDelete ){
27945 #if OS_VXWORKS
27946     zPath = zName;
27947 #else
27948     osUnlink(zName);
27949 #endif
27950   }
27951 #if SQLITE_ENABLE_LOCKING_STYLE
27952   else{
27953     p->openFlags = openFlags;
27954   }
27955 #endif
27956
27957   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27958
27959   
27960 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27961   if( fstatfs(fd, &fsInfo) == -1 ){
27962     ((unixFile*)pFile)->lastErrno = errno;
27963     robust_close(p, fd, __LINE__);
27964     return SQLITE_IOERR_ACCESS;
27965   }
27966   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27967     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27968   }
27969 #endif
27970
27971   /* Set up appropriate ctrlFlags */
27972   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
27973   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
27974   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
27975   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
27976   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
27977
27978 #if SQLITE_ENABLE_LOCKING_STYLE
27979 #if SQLITE_PREFER_PROXY_LOCKING
27980   isAutoProxy = 1;
27981 #endif
27982   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27983     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27984     int useProxy = 0;
27985
27986     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27987     ** never use proxy, NULL means use proxy for non-local files only.  */
27988     if( envforce!=NULL ){
27989       useProxy = atoi(envforce)>0;
27990     }else{
27991       if( statfs(zPath, &fsInfo) == -1 ){
27992         /* In theory, the close(fd) call is sub-optimal. If the file opened
27993         ** with fd is a database file, and there are other connections open
27994         ** on that file that are currently holding advisory locks on it,
27995         ** then the call to close() will cancel those locks. In practice,
27996         ** we're assuming that statfs() doesn't fail very often. At least
27997         ** not while other file descriptors opened by the same process on
27998         ** the same file are working.  */
27999         p->lastErrno = errno;
28000         robust_close(p, fd, __LINE__);
28001         rc = SQLITE_IOERR_ACCESS;
28002         goto open_finished;
28003       }
28004       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28005     }
28006     if( useProxy ){
28007       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28008       if( rc==SQLITE_OK ){
28009         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28010         if( rc!=SQLITE_OK ){
28011           /* Use unixClose to clean up the resources added in fillInUnixFile 
28012           ** and clear all the structure's references.  Specifically, 
28013           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
28014           */
28015           unixClose(pFile);
28016           return rc;
28017         }
28018       }
28019       goto open_finished;
28020     }
28021   }
28022 #endif
28023   
28024   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28025
28026 open_finished:
28027   if( rc!=SQLITE_OK ){
28028     sqlite3_free(p->pUnused);
28029   }
28030   return rc;
28031 }
28032
28033
28034 /*
28035 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28036 ** the directory after deleting the file.
28037 */
28038 static int unixDelete(
28039   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28040   const char *zPath,        /* Name of file to be deleted */
28041   int dirSync               /* If true, fsync() directory after deleting file */
28042 ){
28043   int rc = SQLITE_OK;
28044   UNUSED_PARAMETER(NotUsed);
28045   SimulateIOError(return SQLITE_IOERR_DELETE);
28046   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
28047     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28048   }
28049 #ifndef SQLITE_DISABLE_DIRSYNC
28050   if( (dirSync & 1)!=0 ){
28051     int fd;
28052     rc = osOpenDirectory(zPath, &fd);
28053     if( rc==SQLITE_OK ){
28054 #if OS_VXWORKS
28055       if( fsync(fd)==-1 )
28056 #else
28057       if( fsync(fd) )
28058 #endif
28059       {
28060         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28061       }
28062       robust_close(0, fd, __LINE__);
28063     }else if( rc==SQLITE_CANTOPEN ){
28064       rc = SQLITE_OK;
28065     }
28066   }
28067 #endif
28068   return rc;
28069 }
28070
28071 /*
28072 ** Test the existance of or access permissions of file zPath. The
28073 ** test performed depends on the value of flags:
28074 **
28075 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28076 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28077 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28078 **
28079 ** Otherwise return 0.
28080 */
28081 static int unixAccess(
28082   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28083   const char *zPath,      /* Path of the file to examine */
28084   int flags,              /* What do we want to learn about the zPath file? */
28085   int *pResOut            /* Write result boolean here */
28086 ){
28087   int amode = 0;
28088   UNUSED_PARAMETER(NotUsed);
28089   SimulateIOError( return SQLITE_IOERR_ACCESS; );
28090   switch( flags ){
28091     case SQLITE_ACCESS_EXISTS:
28092       amode = F_OK;
28093       break;
28094     case SQLITE_ACCESS_READWRITE:
28095       amode = W_OK|R_OK;
28096       break;
28097     case SQLITE_ACCESS_READ:
28098       amode = R_OK;
28099       break;
28100
28101     default:
28102       assert(!"Invalid flags argument");
28103   }
28104   *pResOut = (osAccess(zPath, amode)==0);
28105   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28106     struct stat buf;
28107     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28108       *pResOut = 0;
28109     }
28110   }
28111   return SQLITE_OK;
28112 }
28113
28114
28115 /*
28116 ** Turn a relative pathname into a full pathname. The relative path
28117 ** is stored as a nul-terminated string in the buffer pointed to by
28118 ** zPath. 
28119 **
28120 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
28121 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28122 ** this buffer before returning.
28123 */
28124 static int unixFullPathname(
28125   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28126   const char *zPath,            /* Possibly relative input path */
28127   int nOut,                     /* Size of output buffer in bytes */
28128   char *zOut                    /* Output buffer */
28129 ){
28130
28131   /* It's odd to simulate an io-error here, but really this is just
28132   ** using the io-error infrastructure to test that SQLite handles this
28133   ** function failing. This function could fail if, for example, the
28134   ** current working directory has been unlinked.
28135   */
28136   SimulateIOError( return SQLITE_ERROR );
28137
28138   assert( pVfs->mxPathname==MAX_PATHNAME );
28139   UNUSED_PARAMETER(pVfs);
28140
28141   zOut[nOut-1] = '\0';
28142   if( zPath[0]=='/' ){
28143     sqlite3_snprintf(nOut, zOut, "%s", zPath);
28144   }else{
28145     int nCwd;
28146     if( osGetcwd(zOut, nOut-1)==0 ){
28147       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
28148     }
28149     nCwd = (int)strlen(zOut);
28150     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
28151   }
28152   return SQLITE_OK;
28153 }
28154
28155
28156 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28157 /*
28158 ** Interfaces for opening a shared library, finding entry points
28159 ** within the shared library, and closing the shared library.
28160 */
28161 #include <dlfcn.h>
28162 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
28163   UNUSED_PARAMETER(NotUsed);
28164   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
28165 }
28166
28167 /*
28168 ** SQLite calls this function immediately after a call to unixDlSym() or
28169 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
28170 ** message is available, it is written to zBufOut. If no error message
28171 ** is available, zBufOut is left unmodified and SQLite uses a default
28172 ** error message.
28173 */
28174 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
28175   const char *zErr;
28176   UNUSED_PARAMETER(NotUsed);
28177   unixEnterMutex();
28178   zErr = dlerror();
28179   if( zErr ){
28180     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
28181   }
28182   unixLeaveMutex();
28183 }
28184 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
28185   /* 
28186   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
28187   ** cast into a pointer to a function.  And yet the library dlsym() routine
28188   ** returns a void* which is really a pointer to a function.  So how do we
28189   ** use dlsym() with -pedantic-errors?
28190   **
28191   ** Variable x below is defined to be a pointer to a function taking
28192   ** parameters void* and const char* and returning a pointer to a function.
28193   ** We initialize x by assigning it a pointer to the dlsym() function.
28194   ** (That assignment requires a cast.)  Then we call the function that
28195   ** x points to.  
28196   **
28197   ** This work-around is unlikely to work correctly on any system where
28198   ** you really cannot cast a function pointer into void*.  But then, on the
28199   ** other hand, dlsym() will not work on such a system either, so we have
28200   ** not really lost anything.
28201   */
28202   void (*(*x)(void*,const char*))(void);
28203   UNUSED_PARAMETER(NotUsed);
28204   x = (void(*(*)(void*,const char*))(void))dlsym;
28205   return (*x)(p, zSym);
28206 }
28207 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
28208   UNUSED_PARAMETER(NotUsed);
28209   dlclose(pHandle);
28210 }
28211 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28212   #define unixDlOpen  0
28213   #define unixDlError 0
28214   #define unixDlSym   0
28215   #define unixDlClose 0
28216 #endif
28217
28218 /*
28219 ** Write nBuf bytes of random data to the supplied buffer zBuf.
28220 */
28221 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
28222   UNUSED_PARAMETER(NotUsed);
28223   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
28224
28225   /* We have to initialize zBuf to prevent valgrind from reporting
28226   ** errors.  The reports issued by valgrind are incorrect - we would
28227   ** prefer that the randomness be increased by making use of the
28228   ** uninitialized space in zBuf - but valgrind errors tend to worry
28229   ** some users.  Rather than argue, it seems easier just to initialize
28230   ** the whole array and silence valgrind, even if that means less randomness
28231   ** in the random seed.
28232   **
28233   ** When testing, initializing zBuf[] to zero is all we do.  That means
28234   ** that we always use the same random number sequence.  This makes the
28235   ** tests repeatable.
28236   */
28237   memset(zBuf, 0, nBuf);
28238 #if !defined(SQLITE_TEST)
28239   {
28240     int pid, fd, got;
28241     fd = robust_open("/dev/urandom", O_RDONLY, 0);
28242     if( fd<0 ){
28243       time_t t;
28244       time(&t);
28245       memcpy(zBuf, &t, sizeof(t));
28246       pid = getpid();
28247       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
28248       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
28249       nBuf = sizeof(t) + sizeof(pid);
28250     }else{
28251       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
28252       robust_close(0, fd, __LINE__);
28253     }
28254   }
28255 #endif
28256   return nBuf;
28257 }
28258
28259
28260 /*
28261 ** Sleep for a little while.  Return the amount of time slept.
28262 ** The argument is the number of microseconds we want to sleep.
28263 ** The return value is the number of microseconds of sleep actually
28264 ** requested from the underlying operating system, a number which
28265 ** might be greater than or equal to the argument, but not less
28266 ** than the argument.
28267 */
28268 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
28269 #if OS_VXWORKS
28270   struct timespec sp;
28271
28272   sp.tv_sec = microseconds / 1000000;
28273   sp.tv_nsec = (microseconds % 1000000) * 1000;
28274   nanosleep(&sp, NULL);
28275   UNUSED_PARAMETER(NotUsed);
28276   return microseconds;
28277 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
28278   usleep(microseconds);
28279   UNUSED_PARAMETER(NotUsed);
28280   return microseconds;
28281 #else
28282   int seconds = (microseconds+999999)/1000000;
28283   sleep(seconds);
28284   UNUSED_PARAMETER(NotUsed);
28285   return seconds*1000000;
28286 #endif
28287 }
28288
28289 /*
28290 ** The following variable, if set to a non-zero value, is interpreted as
28291 ** the number of seconds since 1970 and is used to set the result of
28292 ** sqlite3OsCurrentTime() during testing.
28293 */
28294 #ifdef SQLITE_TEST
28295 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
28296 #endif
28297
28298 /*
28299 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
28300 ** the current time and date as a Julian Day number times 86_400_000.  In
28301 ** other words, write into *piNow the number of milliseconds since the Julian
28302 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
28303 ** proleptic Gregorian calendar.
28304 **
28305 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
28306 ** cannot be found.
28307 */
28308 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
28309   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
28310   int rc = SQLITE_OK;
28311 #if defined(NO_GETTOD)
28312   time_t t;
28313   time(&t);
28314   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
28315 #elif OS_VXWORKS
28316   struct timespec sNow;
28317   clock_gettime(CLOCK_REALTIME, &sNow);
28318   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
28319 #else
28320   struct timeval sNow;
28321   if( gettimeofday(&sNow, 0)==0 ){
28322     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28323   }else{
28324     rc = SQLITE_ERROR;
28325   }
28326 #endif
28327
28328 #ifdef SQLITE_TEST
28329   if( sqlite3_current_time ){
28330     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28331   }
28332 #endif
28333   UNUSED_PARAMETER(NotUsed);
28334   return rc;
28335 }
28336
28337 /*
28338 ** Find the current time (in Universal Coordinated Time).  Write the
28339 ** current time and date as a Julian Day number into *prNow and
28340 ** return 0.  Return 1 if the time and date cannot be found.
28341 */
28342 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28343   sqlite3_int64 i = 0;
28344   int rc;
28345   UNUSED_PARAMETER(NotUsed);
28346   rc = unixCurrentTimeInt64(0, &i);
28347   *prNow = i/86400000.0;
28348   return rc;
28349 }
28350
28351 /*
28352 ** We added the xGetLastError() method with the intention of providing
28353 ** better low-level error messages when operating-system problems come up
28354 ** during SQLite operation.  But so far, none of that has been implemented
28355 ** in the core.  So this routine is never called.  For now, it is merely
28356 ** a place-holder.
28357 */
28358 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28359   UNUSED_PARAMETER(NotUsed);
28360   UNUSED_PARAMETER(NotUsed2);
28361   UNUSED_PARAMETER(NotUsed3);
28362   return 0;
28363 }
28364
28365
28366 /*
28367 ************************ End of sqlite3_vfs methods ***************************
28368 ******************************************************************************/
28369
28370 /******************************************************************************
28371 ************************** Begin Proxy Locking ********************************
28372 **
28373 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28374 ** other locking methods on secondary lock files.  Proxy locking is a
28375 ** meta-layer over top of the primitive locking implemented above.  For
28376 ** this reason, the division that implements of proxy locking is deferred
28377 ** until late in the file (here) after all of the other I/O methods have
28378 ** been defined - so that the primitive locking methods are available
28379 ** as services to help with the implementation of proxy locking.
28380 **
28381 ****
28382 **
28383 ** The default locking schemes in SQLite use byte-range locks on the
28384 ** database file to coordinate safe, concurrent access by multiple readers
28385 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28386 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28387 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28388 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28389 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28390 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28391 ** address in the shared range is taken for a SHARED lock, the entire
28392 ** shared range is taken for an EXCLUSIVE lock):
28393 **
28394 **      PENDING_BYTE        0x40000000
28395 **      RESERVED_BYTE       0x40000001
28396 **      SHARED_RANGE        0x40000002 -> 0x40000200
28397 **
28398 ** This works well on the local file system, but shows a nearly 100x
28399 ** slowdown in read performance on AFP because the AFP client disables
28400 ** the read cache when byte-range locks are present.  Enabling the read
28401 ** cache exposes a cache coherency problem that is present on all OS X
28402 ** supported network file systems.  NFS and AFP both observe the
28403 ** close-to-open semantics for ensuring cache coherency
28404 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28405 ** address the requirements for concurrent database access by multiple
28406 ** readers and writers
28407 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28408 **
28409 ** To address the performance and cache coherency issues, proxy file locking
28410 ** changes the way database access is controlled by limiting access to a
28411 ** single host at a time and moving file locks off of the database file
28412 ** and onto a proxy file on the local file system.  
28413 **
28414 **
28415 ** Using proxy locks
28416 ** -----------------
28417 **
28418 ** C APIs
28419 **
28420 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28421 **                       <proxy_path> | ":auto:");
28422 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28423 **
28424 **
28425 ** SQL pragmas
28426 **
28427 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28428 **  PRAGMA [database.]lock_proxy_file
28429 **
28430 ** Specifying ":auto:" means that if there is a conch file with a matching
28431 ** host ID in it, the proxy path in the conch file will be used, otherwise
28432 ** a proxy path based on the user's temp dir
28433 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28434 ** actual proxy file name is generated from the name and path of the
28435 ** database file.  For example:
28436 **
28437 **       For database path "/Users/me/foo.db" 
28438 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28439 **
28440 ** Once a lock proxy is configured for a database connection, it can not
28441 ** be removed, however it may be switched to a different proxy path via
28442 ** the above APIs (assuming the conch file is not being held by another
28443 ** connection or process). 
28444 **
28445 **
28446 ** How proxy locking works
28447 ** -----------------------
28448 **
28449 ** Proxy file locking relies primarily on two new supporting files: 
28450 **
28451 **   *  conch file to limit access to the database file to a single host
28452 **      at a time
28453 **
28454 **   *  proxy file to act as a proxy for the advisory locks normally
28455 **      taken on the database
28456 **
28457 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28458 ** by taking an sqlite-style shared lock on the conch file, reading the
28459 ** contents and comparing the host's unique host ID (see below) and lock
28460 ** proxy path against the values stored in the conch.  The conch file is
28461 ** stored in the same directory as the database file and the file name
28462 ** is patterned after the database file name as ".<databasename>-conch".
28463 ** If the conch file does not exist, or it's contents do not match the
28464 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28465 ** lock and the conch file contents is updated with the host ID and proxy
28466 ** path and the lock is downgraded to a shared lock again.  If the conch
28467 ** is held by another process (with a shared lock), the exclusive lock
28468 ** will fail and SQLITE_BUSY is returned.
28469 **
28470 ** The proxy file - a single-byte file used for all advisory file locks
28471 ** normally taken on the database file.   This allows for safe sharing
28472 ** of the database file for multiple readers and writers on the same
28473 ** host (the conch ensures that they all use the same local lock file).
28474 **
28475 ** Requesting the lock proxy does not immediately take the conch, it is
28476 ** only taken when the first request to lock database file is made.  
28477 ** This matches the semantics of the traditional locking behavior, where
28478 ** opening a connection to a database file does not take a lock on it.
28479 ** The shared lock and an open file descriptor are maintained until 
28480 ** the connection to the database is closed. 
28481 **
28482 ** The proxy file and the lock file are never deleted so they only need
28483 ** to be created the first time they are used.
28484 **
28485 ** Configuration options
28486 ** ---------------------
28487 **
28488 **  SQLITE_PREFER_PROXY_LOCKING
28489 **
28490 **       Database files accessed on non-local file systems are
28491 **       automatically configured for proxy locking, lock files are
28492 **       named automatically using the same logic as
28493 **       PRAGMA lock_proxy_file=":auto:"
28494 **    
28495 **  SQLITE_PROXY_DEBUG
28496 **
28497 **       Enables the logging of error messages during host id file
28498 **       retrieval and creation
28499 **
28500 **  LOCKPROXYDIR
28501 **
28502 **       Overrides the default directory used for lock proxy files that
28503 **       are named automatically via the ":auto:" setting
28504 **
28505 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28506 **
28507 **       Permissions to use when creating a directory for storing the
28508 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28509 **    
28510 **    
28511 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28512 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28513 ** force proxy locking to be used for every database file opened, and 0
28514 ** will force automatic proxy locking to be disabled for all database
28515 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28516 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28517 */
28518
28519 /*
28520 ** Proxy locking is only available on MacOSX 
28521 */
28522 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28523
28524 /*
28525 ** The proxyLockingContext has the path and file structures for the remote 
28526 ** and local proxy files in it
28527 */
28528 typedef struct proxyLockingContext proxyLockingContext;
28529 struct proxyLockingContext {
28530   unixFile *conchFile;         /* Open conch file */
28531   char *conchFilePath;         /* Name of the conch file */
28532   unixFile *lockProxy;         /* Open proxy lock file */
28533   char *lockProxyPath;         /* Name of the proxy lock file */
28534   char *dbPath;                /* Name of the open file */
28535   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28536   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28537   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28538 };
28539
28540 /* 
28541 ** The proxy lock file path for the database at dbPath is written into lPath, 
28542 ** which must point to valid, writable memory large enough for a maxLen length
28543 ** file path. 
28544 */
28545 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28546   int len;
28547   int dbLen;
28548   int i;
28549
28550 #ifdef LOCKPROXYDIR
28551   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28552 #else
28553 # ifdef _CS_DARWIN_USER_TEMP_DIR
28554   {
28555     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28556       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28557                lPath, errno, getpid()));
28558       return SQLITE_IOERR_LOCK;
28559     }
28560     len = strlcat(lPath, "sqliteplocks", maxLen);    
28561   }
28562 # else
28563   len = strlcpy(lPath, "/tmp/", maxLen);
28564 # endif
28565 #endif
28566
28567   if( lPath[len-1]!='/' ){
28568     len = strlcat(lPath, "/", maxLen);
28569   }
28570   
28571   /* transform the db path to a unique cache name */
28572   dbLen = (int)strlen(dbPath);
28573   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28574     char c = dbPath[i];
28575     lPath[i+len] = (c=='/')?'_':c;
28576   }
28577   lPath[i+len]='\0';
28578   strlcat(lPath, ":auto:", maxLen);
28579   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28580   return SQLITE_OK;
28581 }
28582
28583 /* 
28584  ** Creates the lock file and any missing directories in lockPath
28585  */
28586 static int proxyCreateLockPath(const char *lockPath){
28587   int i, len;
28588   char buf[MAXPATHLEN];
28589   int start = 0;
28590   
28591   assert(lockPath!=NULL);
28592   /* try to create all the intermediate directories */
28593   len = (int)strlen(lockPath);
28594   buf[0] = lockPath[0];
28595   for( i=1; i<len; i++ ){
28596     if( lockPath[i] == '/' && (i - start > 0) ){
28597       /* only mkdir if leaf dir != "." or "/" or ".." */
28598       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28599          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28600         buf[i]='\0';
28601         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28602           int err=errno;
28603           if( err!=EEXIST ) {
28604             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28605                      "'%s' proxy lock path=%s pid=%d\n",
28606                      buf, strerror(err), lockPath, getpid()));
28607             return err;
28608           }
28609         }
28610       }
28611       start=i+1;
28612     }
28613     buf[i] = lockPath[i];
28614   }
28615   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28616   return 0;
28617 }
28618
28619 /*
28620 ** Create a new VFS file descriptor (stored in memory obtained from
28621 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28622 **
28623 ** The caller is responsible not only for closing the file descriptor
28624 ** but also for freeing the memory associated with the file descriptor.
28625 */
28626 static int proxyCreateUnixFile(
28627     const char *path,        /* path for the new unixFile */
28628     unixFile **ppFile,       /* unixFile created and returned by ref */
28629     int islockfile           /* if non zero missing dirs will be created */
28630 ) {
28631   int fd = -1;
28632   unixFile *pNew;
28633   int rc = SQLITE_OK;
28634   int openFlags = O_RDWR | O_CREAT;
28635   sqlite3_vfs dummyVfs;
28636   int terrno = 0;
28637   UnixUnusedFd *pUnused = NULL;
28638
28639   /* 1. first try to open/create the file
28640   ** 2. if that fails, and this is a lock file (not-conch), try creating
28641   ** the parent directories and then try again.
28642   ** 3. if that fails, try to open the file read-only
28643   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28644   */
28645   pUnused = findReusableFd(path, openFlags);
28646   if( pUnused ){
28647     fd = pUnused->fd;
28648   }else{
28649     pUnused = sqlite3_malloc(sizeof(*pUnused));
28650     if( !pUnused ){
28651       return SQLITE_NOMEM;
28652     }
28653   }
28654   if( fd<0 ){
28655     fd = robust_open(path, openFlags, 0);
28656     terrno = errno;
28657     if( fd<0 && errno==ENOENT && islockfile ){
28658       if( proxyCreateLockPath(path) == SQLITE_OK ){
28659         fd = robust_open(path, openFlags, 0);
28660       }
28661     }
28662   }
28663   if( fd<0 ){
28664     openFlags = O_RDONLY;
28665     fd = robust_open(path, openFlags, 0);
28666     terrno = errno;
28667   }
28668   if( fd<0 ){
28669     if( islockfile ){
28670       return SQLITE_BUSY;
28671     }
28672     switch (terrno) {
28673       case EACCES:
28674         return SQLITE_PERM;
28675       case EIO: 
28676         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28677       default:
28678         return SQLITE_CANTOPEN_BKPT;
28679     }
28680   }
28681   
28682   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28683   if( pNew==NULL ){
28684     rc = SQLITE_NOMEM;
28685     goto end_create_proxy;
28686   }
28687   memset(pNew, 0, sizeof(unixFile));
28688   pNew->openFlags = openFlags;
28689   memset(&dummyVfs, 0, sizeof(dummyVfs));
28690   dummyVfs.pAppData = (void*)&autolockIoFinder;
28691   dummyVfs.zName = "dummy";
28692   pUnused->fd = fd;
28693   pUnused->flags = openFlags;
28694   pNew->pUnused = pUnused;
28695   
28696   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
28697   if( rc==SQLITE_OK ){
28698     *ppFile = pNew;
28699     return SQLITE_OK;
28700   }
28701 end_create_proxy:    
28702   robust_close(pNew, fd, __LINE__);
28703   sqlite3_free(pNew);
28704   sqlite3_free(pUnused);
28705   return rc;
28706 }
28707
28708 #ifdef SQLITE_TEST
28709 /* simulate multiple hosts by creating unique hostid file paths */
28710 SQLITE_API int sqlite3_hostid_num = 0;
28711 #endif
28712
28713 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
28714
28715 /* Not always defined in the headers as it ought to be */
28716 extern int gethostuuid(uuid_t id, const struct timespec *wait);
28717
28718 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28719 ** bytes of writable memory.
28720 */
28721 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28722   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28723   memset(pHostID, 0, PROXY_HOSTIDLEN);
28724 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28725                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28726   {
28727     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
28728     if( gethostuuid(pHostID, &timeout) ){
28729       int err = errno;
28730       if( pError ){
28731         *pError = err;
28732       }
28733       return SQLITE_IOERR;
28734     }
28735   }
28736 #else
28737   UNUSED_PARAMETER(pError);
28738 #endif
28739 #ifdef SQLITE_TEST
28740   /* simulate multiple hosts by creating unique hostid file paths */
28741   if( sqlite3_hostid_num != 0){
28742     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28743   }
28744 #endif
28745   
28746   return SQLITE_OK;
28747 }
28748
28749 /* The conch file contains the header, host id and lock file path
28750  */
28751 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28752 #define PROXY_HEADERLEN    1   /* conch file header length */
28753 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28754 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28755
28756 /* 
28757 ** Takes an open conch file, copies the contents to a new path and then moves 
28758 ** it back.  The newly created file's file descriptor is assigned to the
28759 ** conch file structure and finally the original conch file descriptor is 
28760 ** closed.  Returns zero if successful.
28761 */
28762 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
28763   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28764   unixFile *conchFile = pCtx->conchFile;
28765   char tPath[MAXPATHLEN];
28766   char buf[PROXY_MAXCONCHLEN];
28767   char *cPath = pCtx->conchFilePath;
28768   size_t readLen = 0;
28769   size_t pathLen = 0;
28770   char errmsg[64] = "";
28771   int fd = -1;
28772   int rc = -1;
28773   UNUSED_PARAMETER(myHostID);
28774
28775   /* create a new path by replace the trailing '-conch' with '-break' */
28776   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28777   if( pathLen>MAXPATHLEN || pathLen<6 || 
28778      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
28779     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
28780     goto end_breaklock;
28781   }
28782   /* read the conch content */
28783   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
28784   if( readLen<PROXY_PATHINDEX ){
28785     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
28786     goto end_breaklock;
28787   }
28788   /* write it out to the temporary break file */
28789   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
28790   if( fd<0 ){
28791     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
28792     goto end_breaklock;
28793   }
28794   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
28795     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
28796     goto end_breaklock;
28797   }
28798   if( rename(tPath, cPath) ){
28799     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
28800     goto end_breaklock;
28801   }
28802   rc = 0;
28803   fprintf(stderr, "broke stale lock on %s\n", cPath);
28804   robust_close(pFile, conchFile->h, __LINE__);
28805   conchFile->h = fd;
28806   conchFile->openFlags = O_RDWR | O_CREAT;
28807
28808 end_breaklock:
28809   if( rc ){
28810     if( fd>=0 ){
28811       osUnlink(tPath);
28812       robust_close(pFile, fd, __LINE__);
28813     }
28814     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
28815   }
28816   return rc;
28817 }
28818
28819 /* Take the requested lock on the conch file and break a stale lock if the 
28820 ** host id matches.
28821 */
28822 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
28823   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28824   unixFile *conchFile = pCtx->conchFile;
28825   int rc = SQLITE_OK;
28826   int nTries = 0;
28827   struct timespec conchModTime;
28828   
28829   memset(&conchModTime, 0, sizeof(conchModTime));
28830   do {
28831     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28832     nTries ++;
28833     if( rc==SQLITE_BUSY ){
28834       /* If the lock failed (busy):
28835        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
28836        * 2nd try: fail if the mod time changed or host id is different, wait 
28837        *           10 sec and try again
28838        * 3rd try: break the lock unless the mod time has changed.
28839        */
28840       struct stat buf;
28841       if( osFstat(conchFile->h, &buf) ){
28842         pFile->lastErrno = errno;
28843         return SQLITE_IOERR_LOCK;
28844       }
28845       
28846       if( nTries==1 ){
28847         conchModTime = buf.st_mtimespec;
28848         usleep(500000); /* wait 0.5 sec and try the lock again*/
28849         continue;  
28850       }
28851
28852       assert( nTries>1 );
28853       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
28854          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
28855         return SQLITE_BUSY;
28856       }
28857       
28858       if( nTries==2 ){  
28859         char tBuf[PROXY_MAXCONCHLEN];
28860         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
28861         if( len<0 ){
28862           pFile->lastErrno = errno;
28863           return SQLITE_IOERR_LOCK;
28864         }
28865         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
28866           /* don't break the lock if the host id doesn't match */
28867           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
28868             return SQLITE_BUSY;
28869           }
28870         }else{
28871           /* don't break the lock on short read or a version mismatch */
28872           return SQLITE_BUSY;
28873         }
28874         usleep(10000000); /* wait 10 sec and try the lock again */
28875         continue; 
28876       }
28877       
28878       assert( nTries==3 );
28879       if( 0==proxyBreakConchLock(pFile, myHostID) ){
28880         rc = SQLITE_OK;
28881         if( lockType==EXCLUSIVE_LOCK ){
28882           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
28883         }
28884         if( !rc ){
28885           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28886         }
28887       }
28888     }
28889   } while( rc==SQLITE_BUSY && nTries<3 );
28890   
28891   return rc;
28892 }
28893
28894 /* Takes the conch by taking a shared lock and read the contents conch, if 
28895 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
28896 ** lockPath means that the lockPath in the conch file will be used if the 
28897 ** host IDs match, or a new lock path will be generated automatically 
28898 ** and written to the conch file.
28899 */
28900 static int proxyTakeConch(unixFile *pFile){
28901   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28902   
28903   if( pCtx->conchHeld!=0 ){
28904     return SQLITE_OK;
28905   }else{
28906     unixFile *conchFile = pCtx->conchFile;
28907     uuid_t myHostID;
28908     int pError = 0;
28909     char readBuf[PROXY_MAXCONCHLEN];
28910     char lockPath[MAXPATHLEN];
28911     char *tempLockPath = NULL;
28912     int rc = SQLITE_OK;
28913     int createConch = 0;
28914     int hostIdMatch = 0;
28915     int readLen = 0;
28916     int tryOldLockPath = 0;
28917     int forceNewLockPath = 0;
28918     
28919     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28920              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
28921
28922     rc = proxyGetHostID(myHostID, &pError);
28923     if( (rc&0xff)==SQLITE_IOERR ){
28924       pFile->lastErrno = pError;
28925       goto end_takeconch;
28926     }
28927     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
28928     if( rc!=SQLITE_OK ){
28929       goto end_takeconch;
28930     }
28931     /* read the existing conch file */
28932     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
28933     if( readLen<0 ){
28934       /* I/O error: lastErrno set by seekAndRead */
28935       pFile->lastErrno = conchFile->lastErrno;
28936       rc = SQLITE_IOERR_READ;
28937       goto end_takeconch;
28938     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
28939              readBuf[0]!=(char)PROXY_CONCHVERSION ){
28940       /* a short read or version format mismatch means we need to create a new 
28941       ** conch file. 
28942       */
28943       createConch = 1;
28944     }
28945     /* if the host id matches and the lock path already exists in the conch
28946     ** we'll try to use the path there, if we can't open that path, we'll 
28947     ** retry with a new auto-generated path 
28948     */
28949     do { /* in case we need to try again for an :auto: named lock file */
28950
28951       if( !createConch && !forceNewLockPath ){
28952         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
28953                                   PROXY_HOSTIDLEN);
28954         /* if the conch has data compare the contents */
28955         if( !pCtx->lockProxyPath ){
28956           /* for auto-named local lock file, just check the host ID and we'll
28957            ** use the local lock file path that's already in there
28958            */
28959           if( hostIdMatch ){
28960             size_t pathLen = (readLen - PROXY_PATHINDEX);
28961             
28962             if( pathLen>=MAXPATHLEN ){
28963               pathLen=MAXPATHLEN-1;
28964             }
28965             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28966             lockPath[pathLen] = 0;
28967             tempLockPath = lockPath;
28968             tryOldLockPath = 1;
28969             /* create a copy of the lock path if the conch is taken */
28970             goto end_takeconch;
28971           }
28972         }else if( hostIdMatch
28973                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28974                            readLen-PROXY_PATHINDEX)
28975         ){
28976           /* conch host and lock path match */
28977           goto end_takeconch; 
28978         }
28979       }
28980       
28981       /* if the conch isn't writable and doesn't match, we can't take it */
28982       if( (conchFile->openFlags&O_RDWR) == 0 ){
28983         rc = SQLITE_BUSY;
28984         goto end_takeconch;
28985       }
28986       
28987       /* either the conch didn't match or we need to create a new one */
28988       if( !pCtx->lockProxyPath ){
28989         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28990         tempLockPath = lockPath;
28991         /* create a copy of the lock path _only_ if the conch is taken */
28992       }
28993       
28994       /* update conch with host and path (this will fail if other process
28995       ** has a shared lock already), if the host id matches, use the big
28996       ** stick.
28997       */
28998       futimes(conchFile->h, NULL);
28999       if( hostIdMatch && !createConch ){
29000         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29001           /* We are trying for an exclusive lock but another thread in this
29002            ** same process is still holding a shared lock. */
29003           rc = SQLITE_BUSY;
29004         } else {          
29005           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29006         }
29007       }else{
29008         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29009       }
29010       if( rc==SQLITE_OK ){
29011         char writeBuffer[PROXY_MAXCONCHLEN];
29012         int writeSize = 0;
29013         
29014         writeBuffer[0] = (char)PROXY_CONCHVERSION;
29015         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29016         if( pCtx->lockProxyPath!=NULL ){
29017           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29018         }else{
29019           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29020         }
29021         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29022         robust_ftruncate(conchFile->h, writeSize);
29023         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29024         fsync(conchFile->h);
29025         /* If we created a new conch file (not just updated the contents of a 
29026          ** valid conch file), try to match the permissions of the database 
29027          */
29028         if( rc==SQLITE_OK && createConch ){
29029           struct stat buf;
29030           int err = osFstat(pFile->h, &buf);
29031           if( err==0 ){
29032             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29033                                         S_IROTH|S_IWOTH);
29034             /* try to match the database file R/W permissions, ignore failure */
29035 #ifndef SQLITE_PROXY_DEBUG
29036             osFchmod(conchFile->h, cmode);
29037 #else
29038             do{
29039               rc = osFchmod(conchFile->h, cmode);
29040             }while( rc==(-1) && errno==EINTR );
29041             if( rc!=0 ){
29042               int code = errno;
29043               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29044                       cmode, code, strerror(code));
29045             } else {
29046               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29047             }
29048           }else{
29049             int code = errno;
29050             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
29051                     err, code, strerror(code));
29052 #endif
29053           }
29054         }
29055       }
29056       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29057       
29058     end_takeconch:
29059       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29060       if( rc==SQLITE_OK && pFile->openFlags ){
29061         int fd;
29062         if( pFile->h>=0 ){
29063           robust_close(pFile, pFile->h, __LINE__);
29064         }
29065         pFile->h = -1;
29066         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29067         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29068         if( fd>=0 ){
29069           pFile->h = fd;
29070         }else{
29071           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29072            during locking */
29073         }
29074       }
29075       if( rc==SQLITE_OK && !pCtx->lockProxy ){
29076         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29077         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29078         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29079           /* we couldn't create the proxy lock file with the old lock file path
29080            ** so try again via auto-naming 
29081            */
29082           forceNewLockPath = 1;
29083           tryOldLockPath = 0;
29084           continue; /* go back to the do {} while start point, try again */
29085         }
29086       }
29087       if( rc==SQLITE_OK ){
29088         /* Need to make a copy of path if we extracted the value
29089          ** from the conch file or the path was allocated on the stack
29090          */
29091         if( tempLockPath ){
29092           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29093           if( !pCtx->lockProxyPath ){
29094             rc = SQLITE_NOMEM;
29095           }
29096         }
29097       }
29098       if( rc==SQLITE_OK ){
29099         pCtx->conchHeld = 1;
29100         
29101         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29102           afpLockingContext *afpCtx;
29103           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29104           afpCtx->dbPath = pCtx->lockProxyPath;
29105         }
29106       } else {
29107         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29108       }
29109       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29110                rc==SQLITE_OK?"ok":"failed"));
29111       return rc;
29112     } while (1); /* in case we need to retry the :auto: lock file - 
29113                  ** we should never get here except via the 'continue' call. */
29114   }
29115 }
29116
29117 /*
29118 ** If pFile holds a lock on a conch file, then release that lock.
29119 */
29120 static int proxyReleaseConch(unixFile *pFile){
29121   int rc = SQLITE_OK;         /* Subroutine return code */
29122   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29123   unixFile *conchFile;        /* Name of the conch file */
29124
29125   pCtx = (proxyLockingContext *)pFile->lockingContext;
29126   conchFile = pCtx->conchFile;
29127   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29128            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
29129            getpid()));
29130   if( pCtx->conchHeld>0 ){
29131     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29132   }
29133   pCtx->conchHeld = 0;
29134   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29135            (rc==SQLITE_OK ? "ok" : "failed")));
29136   return rc;
29137 }
29138
29139 /*
29140 ** Given the name of a database file, compute the name of its conch file.
29141 ** Store the conch filename in memory obtained from sqlite3_malloc().
29142 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29143 ** or SQLITE_NOMEM if unable to obtain memory.
29144 **
29145 ** The caller is responsible for ensuring that the allocated memory
29146 ** space is eventually freed.
29147 **
29148 ** *pConchPath is set to NULL if a memory allocation error occurs.
29149 */
29150 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
29151   int i;                        /* Loop counter */
29152   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
29153   char *conchPath;              /* buffer in which to construct conch name */
29154
29155   /* Allocate space for the conch filename and initialize the name to
29156   ** the name of the original database file. */  
29157   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
29158   if( conchPath==0 ){
29159     return SQLITE_NOMEM;
29160   }
29161   memcpy(conchPath, dbPath, len+1);
29162   
29163   /* now insert a "." before the last / character */
29164   for( i=(len-1); i>=0; i-- ){
29165     if( conchPath[i]=='/' ){
29166       i++;
29167       break;
29168     }
29169   }
29170   conchPath[i]='.';
29171   while ( i<len ){
29172     conchPath[i+1]=dbPath[i];
29173     i++;
29174   }
29175
29176   /* append the "-conch" suffix to the file */
29177   memcpy(&conchPath[i+1], "-conch", 7);
29178   assert( (int)strlen(conchPath) == len+7 );
29179
29180   return SQLITE_OK;
29181 }
29182
29183
29184 /* Takes a fully configured proxy locking-style unix file and switches
29185 ** the local lock file path 
29186 */
29187 static int switchLockProxyPath(unixFile *pFile, const char *path) {
29188   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29189   char *oldPath = pCtx->lockProxyPath;
29190   int rc = SQLITE_OK;
29191
29192   if( pFile->eFileLock!=NO_LOCK ){
29193     return SQLITE_BUSY;
29194   }  
29195
29196   /* nothing to do if the path is NULL, :auto: or matches the existing path */
29197   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
29198     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
29199     return SQLITE_OK;
29200   }else{
29201     unixFile *lockProxy = pCtx->lockProxy;
29202     pCtx->lockProxy=NULL;
29203     pCtx->conchHeld = 0;
29204     if( lockProxy!=NULL ){
29205       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
29206       if( rc ) return rc;
29207       sqlite3_free(lockProxy);
29208     }
29209     sqlite3_free(oldPath);
29210     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
29211   }
29212   
29213   return rc;
29214 }
29215
29216 /*
29217 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
29218 ** is a string buffer at least MAXPATHLEN+1 characters in size.
29219 **
29220 ** This routine find the filename associated with pFile and writes it
29221 ** int dbPath.
29222 */
29223 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
29224 #if defined(__APPLE__)
29225   if( pFile->pMethod == &afpIoMethods ){
29226     /* afp style keeps a reference to the db path in the filePath field 
29227     ** of the struct */
29228     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29229     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
29230   } else
29231 #endif
29232   if( pFile->pMethod == &dotlockIoMethods ){
29233     /* dot lock style uses the locking context to store the dot lock
29234     ** file path */
29235     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
29236     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
29237   }else{
29238     /* all other styles use the locking context to store the db file path */
29239     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29240     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
29241   }
29242   return SQLITE_OK;
29243 }
29244
29245 /*
29246 ** Takes an already filled in unix file and alters it so all file locking 
29247 ** will be performed on the local proxy lock file.  The following fields
29248 ** are preserved in the locking context so that they can be restored and 
29249 ** the unix structure properly cleaned up at close time:
29250 **  ->lockingContext
29251 **  ->pMethod
29252 */
29253 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
29254   proxyLockingContext *pCtx;
29255   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
29256   char *lockPath=NULL;
29257   int rc = SQLITE_OK;
29258   
29259   if( pFile->eFileLock!=NO_LOCK ){
29260     return SQLITE_BUSY;
29261   }
29262   proxyGetDbPathForUnixFile(pFile, dbPath);
29263   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
29264     lockPath=NULL;
29265   }else{
29266     lockPath=(char *)path;
29267   }
29268   
29269   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
29270            (lockPath ? lockPath : ":auto:"), getpid()));
29271
29272   pCtx = sqlite3_malloc( sizeof(*pCtx) );
29273   if( pCtx==0 ){
29274     return SQLITE_NOMEM;
29275   }
29276   memset(pCtx, 0, sizeof(*pCtx));
29277
29278   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
29279   if( rc==SQLITE_OK ){
29280     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
29281     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
29282       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
29283       ** (c) the file system is read-only, then enable no-locking access.
29284       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
29285       ** that openFlags will have only one of O_RDONLY or O_RDWR.
29286       */
29287       struct statfs fsInfo;
29288       struct stat conchInfo;
29289       int goLockless = 0;
29290
29291       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
29292         int err = errno;
29293         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
29294           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
29295         }
29296       }
29297       if( goLockless ){
29298         pCtx->conchHeld = -1; /* read only FS/ lockless */
29299         rc = SQLITE_OK;
29300       }
29301     }
29302   }  
29303   if( rc==SQLITE_OK && lockPath ){
29304     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
29305   }
29306
29307   if( rc==SQLITE_OK ){
29308     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
29309     if( pCtx->dbPath==NULL ){
29310       rc = SQLITE_NOMEM;
29311     }
29312   }
29313   if( rc==SQLITE_OK ){
29314     /* all memory is allocated, proxys are created and assigned, 
29315     ** switch the locking context and pMethod then return.
29316     */
29317     pCtx->oldLockingContext = pFile->lockingContext;
29318     pFile->lockingContext = pCtx;
29319     pCtx->pOldMethod = pFile->pMethod;
29320     pFile->pMethod = &proxyIoMethods;
29321   }else{
29322     if( pCtx->conchFile ){ 
29323       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
29324       sqlite3_free(pCtx->conchFile);
29325     }
29326     sqlite3DbFree(0, pCtx->lockProxyPath);
29327     sqlite3_free(pCtx->conchFilePath); 
29328     sqlite3_free(pCtx);
29329   }
29330   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29331            (rc==SQLITE_OK ? "ok" : "failed")));
29332   return rc;
29333 }
29334
29335
29336 /*
29337 ** This routine handles sqlite3_file_control() calls that are specific
29338 ** to proxy locking.
29339 */
29340 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29341   switch( op ){
29342     case SQLITE_GET_LOCKPROXYFILE: {
29343       unixFile *pFile = (unixFile*)id;
29344       if( pFile->pMethod == &proxyIoMethods ){
29345         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29346         proxyTakeConch(pFile);
29347         if( pCtx->lockProxyPath ){
29348           *(const char **)pArg = pCtx->lockProxyPath;
29349         }else{
29350           *(const char **)pArg = ":auto: (not held)";
29351         }
29352       } else {
29353         *(const char **)pArg = NULL;
29354       }
29355       return SQLITE_OK;
29356     }
29357     case SQLITE_SET_LOCKPROXYFILE: {
29358       unixFile *pFile = (unixFile*)id;
29359       int rc = SQLITE_OK;
29360       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29361       if( pArg==NULL || (const char *)pArg==0 ){
29362         if( isProxyStyle ){
29363           /* turn off proxy locking - not supported */
29364           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29365         }else{
29366           /* turn off proxy locking - already off - NOOP */
29367           rc = SQLITE_OK;
29368         }
29369       }else{
29370         const char *proxyPath = (const char *)pArg;
29371         if( isProxyStyle ){
29372           proxyLockingContext *pCtx = 
29373             (proxyLockingContext*)pFile->lockingContext;
29374           if( !strcmp(pArg, ":auto:") 
29375            || (pCtx->lockProxyPath &&
29376                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29377           ){
29378             rc = SQLITE_OK;
29379           }else{
29380             rc = switchLockProxyPath(pFile, proxyPath);
29381           }
29382         }else{
29383           /* turn on proxy file locking */
29384           rc = proxyTransformUnixFile(pFile, proxyPath);
29385         }
29386       }
29387       return rc;
29388     }
29389     default: {
29390       assert( 0 );  /* The call assures that only valid opcodes are sent */
29391     }
29392   }
29393   /*NOTREACHED*/
29394   return SQLITE_ERROR;
29395 }
29396
29397 /*
29398 ** Within this division (the proxying locking implementation) the procedures
29399 ** above this point are all utilities.  The lock-related methods of the
29400 ** proxy-locking sqlite3_io_method object follow.
29401 */
29402
29403
29404 /*
29405 ** This routine checks if there is a RESERVED lock held on the specified
29406 ** file by this or any other process. If such a lock is held, set *pResOut
29407 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29408 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29409 */
29410 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29411   unixFile *pFile = (unixFile*)id;
29412   int rc = proxyTakeConch(pFile);
29413   if( rc==SQLITE_OK ){
29414     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29415     if( pCtx->conchHeld>0 ){
29416       unixFile *proxy = pCtx->lockProxy;
29417       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29418     }else{ /* conchHeld < 0 is lockless */
29419       pResOut=0;
29420     }
29421   }
29422   return rc;
29423 }
29424
29425 /*
29426 ** Lock the file with the lock specified by parameter eFileLock - one
29427 ** of the following:
29428 **
29429 **     (1) SHARED_LOCK
29430 **     (2) RESERVED_LOCK
29431 **     (3) PENDING_LOCK
29432 **     (4) EXCLUSIVE_LOCK
29433 **
29434 ** Sometimes when requesting one lock state, additional lock states
29435 ** are inserted in between.  The locking might fail on one of the later
29436 ** transitions leaving the lock state different from what it started but
29437 ** still short of its goal.  The following chart shows the allowed
29438 ** transitions and the inserted intermediate states:
29439 **
29440 **    UNLOCKED -> SHARED
29441 **    SHARED -> RESERVED
29442 **    SHARED -> (PENDING) -> EXCLUSIVE
29443 **    RESERVED -> (PENDING) -> EXCLUSIVE
29444 **    PENDING -> EXCLUSIVE
29445 **
29446 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29447 ** routine to lower a locking level.
29448 */
29449 static int proxyLock(sqlite3_file *id, int eFileLock) {
29450   unixFile *pFile = (unixFile*)id;
29451   int rc = proxyTakeConch(pFile);
29452   if( rc==SQLITE_OK ){
29453     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29454     if( pCtx->conchHeld>0 ){
29455       unixFile *proxy = pCtx->lockProxy;
29456       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29457       pFile->eFileLock = proxy->eFileLock;
29458     }else{
29459       /* conchHeld < 0 is lockless */
29460     }
29461   }
29462   return rc;
29463 }
29464
29465
29466 /*
29467 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29468 ** must be either NO_LOCK or SHARED_LOCK.
29469 **
29470 ** If the locking level of the file descriptor is already at or below
29471 ** the requested locking level, this routine is a no-op.
29472 */
29473 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29474   unixFile *pFile = (unixFile*)id;
29475   int rc = proxyTakeConch(pFile);
29476   if( rc==SQLITE_OK ){
29477     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29478     if( pCtx->conchHeld>0 ){
29479       unixFile *proxy = pCtx->lockProxy;
29480       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29481       pFile->eFileLock = proxy->eFileLock;
29482     }else{
29483       /* conchHeld < 0 is lockless */
29484     }
29485   }
29486   return rc;
29487 }
29488
29489 /*
29490 ** Close a file that uses proxy locks.
29491 */
29492 static int proxyClose(sqlite3_file *id) {
29493   if( id ){
29494     unixFile *pFile = (unixFile*)id;
29495     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29496     unixFile *lockProxy = pCtx->lockProxy;
29497     unixFile *conchFile = pCtx->conchFile;
29498     int rc = SQLITE_OK;
29499     
29500     if( lockProxy ){
29501       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29502       if( rc ) return rc;
29503       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29504       if( rc ) return rc;
29505       sqlite3_free(lockProxy);
29506       pCtx->lockProxy = 0;
29507     }
29508     if( conchFile ){
29509       if( pCtx->conchHeld ){
29510         rc = proxyReleaseConch(pFile);
29511         if( rc ) return rc;
29512       }
29513       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29514       if( rc ) return rc;
29515       sqlite3_free(conchFile);
29516     }
29517     sqlite3DbFree(0, pCtx->lockProxyPath);
29518     sqlite3_free(pCtx->conchFilePath);
29519     sqlite3DbFree(0, pCtx->dbPath);
29520     /* restore the original locking context and pMethod then close it */
29521     pFile->lockingContext = pCtx->oldLockingContext;
29522     pFile->pMethod = pCtx->pOldMethod;
29523     sqlite3_free(pCtx);
29524     return pFile->pMethod->xClose(id);
29525   }
29526   return SQLITE_OK;
29527 }
29528
29529
29530
29531 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29532 /*
29533 ** The proxy locking style is intended for use with AFP filesystems.
29534 ** And since AFP is only supported on MacOSX, the proxy locking is also
29535 ** restricted to MacOSX.
29536 ** 
29537 **
29538 ******************* End of the proxy lock implementation **********************
29539 ******************************************************************************/
29540
29541 /*
29542 ** Initialize the operating system interface.
29543 **
29544 ** This routine registers all VFS implementations for unix-like operating
29545 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29546 ** should be the only routines in this file that are visible from other
29547 ** files.
29548 **
29549 ** This routine is called once during SQLite initialization and by a
29550 ** single thread.  The memory allocation and mutex subsystems have not
29551 ** necessarily been initialized when this routine is called, and so they
29552 ** should not be used.
29553 */
29554 SQLITE_API int sqlite3_os_init(void){ 
29555   /* 
29556   ** The following macro defines an initializer for an sqlite3_vfs object.
29557   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29558   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29559   ** silly C90 rules prohibit a void* from being cast to a function pointer
29560   ** and so we have to go through the intermediate pointer to avoid problems
29561   ** when compiling with -pedantic-errors on GCC.)
29562   **
29563   ** The FINDER parameter to this macro is the name of the pointer to the
29564   ** finder-function.  The finder-function returns a pointer to the
29565   ** sqlite_io_methods object that implements the desired locking
29566   ** behaviors.  See the division above that contains the IOMETHODS
29567   ** macro for addition information on finder-functions.
29568   **
29569   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29570   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29571   ** more than that; it looks at the filesystem type that hosts the 
29572   ** database file and tries to choose an locking method appropriate for
29573   ** that filesystem time.
29574   */
29575   #define UNIXVFS(VFSNAME, FINDER) {                        \
29576     3,                    /* iVersion */                    \
29577     sizeof(unixFile),     /* szOsFile */                    \
29578     MAX_PATHNAME,         /* mxPathname */                  \
29579     0,                    /* pNext */                       \
29580     VFSNAME,              /* zName */                       \
29581     (void*)&FINDER,       /* pAppData */                    \
29582     unixOpen,             /* xOpen */                       \
29583     unixDelete,           /* xDelete */                     \
29584     unixAccess,           /* xAccess */                     \
29585     unixFullPathname,     /* xFullPathname */               \
29586     unixDlOpen,           /* xDlOpen */                     \
29587     unixDlError,          /* xDlError */                    \
29588     unixDlSym,            /* xDlSym */                      \
29589     unixDlClose,          /* xDlClose */                    \
29590     unixRandomness,       /* xRandomness */                 \
29591     unixSleep,            /* xSleep */                      \
29592     unixCurrentTime,      /* xCurrentTime */                \
29593     unixGetLastError,     /* xGetLastError */               \
29594     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29595     unixSetSystemCall,    /* xSetSystemCall */              \
29596     unixGetSystemCall,    /* xGetSystemCall */              \
29597     unixNextSystemCall,   /* xNextSystemCall */             \
29598   }
29599
29600   /*
29601   ** All default VFSes for unix are contained in the following array.
29602   **
29603   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29604   ** by the SQLite core when the VFS is registered.  So the following
29605   ** array cannot be const.
29606   */
29607   static sqlite3_vfs aVfs[] = {
29608 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29609     UNIXVFS("unix",          autolockIoFinder ),
29610 #else
29611     UNIXVFS("unix",          posixIoFinder ),
29612 #endif
29613     UNIXVFS("unix-none",     nolockIoFinder ),
29614     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29615     UNIXVFS("unix-excl",     posixIoFinder ),
29616 #if OS_VXWORKS
29617     UNIXVFS("unix-namedsem", semIoFinder ),
29618 #endif
29619 #if SQLITE_ENABLE_LOCKING_STYLE
29620     UNIXVFS("unix-posix",    posixIoFinder ),
29621 #if !OS_VXWORKS
29622     UNIXVFS("unix-flock",    flockIoFinder ),
29623 #endif
29624 #endif
29625 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29626     UNIXVFS("unix-afp",      afpIoFinder ),
29627     UNIXVFS("unix-nfs",      nfsIoFinder ),
29628     UNIXVFS("unix-proxy",    proxyIoFinder ),
29629 #endif
29630   };
29631   unsigned int i;          /* Loop counter */
29632
29633   /* Double-check that the aSyscall[] array has been constructed
29634   ** correctly.  See ticket [bb3a86e890c8e96ab] */
29635   assert( ArraySize(aSyscall)==22 );
29636
29637   /* Register all VFSes defined in the aVfs[] array */
29638   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29639     sqlite3_vfs_register(&aVfs[i], i==0);
29640   }
29641   return SQLITE_OK; 
29642 }
29643
29644 /*
29645 ** Shutdown the operating system interface.
29646 **
29647 ** Some operating systems might need to do some cleanup in this routine,
29648 ** to release dynamically allocated objects.  But not on unix.
29649 ** This routine is a no-op for unix.
29650 */
29651 SQLITE_API int sqlite3_os_end(void){ 
29652   return SQLITE_OK; 
29653 }
29654  
29655 #endif /* SQLITE_OS_UNIX */
29656
29657 /************** End of os_unix.c *********************************************/
29658 /************** Begin file os_win.c ******************************************/
29659 /*
29660 ** 2004 May 22
29661 **
29662 ** The author disclaims copyright to this source code.  In place of
29663 ** a legal notice, here is a blessing:
29664 **
29665 **    May you do good and not evil.
29666 **    May you find forgiveness for yourself and forgive others.
29667 **    May you share freely, never taking more than you give.
29668 **
29669 ******************************************************************************
29670 **
29671 ** This file contains code that is specific to Windows.
29672 */
29673 #if SQLITE_OS_WIN               /* This file is used for Windows only */
29674
29675 #ifdef __CYGWIN__
29676 # include <sys/cygwin.h>
29677 #endif
29678
29679 /*
29680 ** Include code that is common to all os_*.c files
29681 */
29682 /************** Include os_common.h in the middle of os_win.c ****************/
29683 /************** Begin file os_common.h ***************************************/
29684 /*
29685 ** 2004 May 22
29686 **
29687 ** The author disclaims copyright to this source code.  In place of
29688 ** a legal notice, here is a blessing:
29689 **
29690 **    May you do good and not evil.
29691 **    May you find forgiveness for yourself and forgive others.
29692 **    May you share freely, never taking more than you give.
29693 **
29694 ******************************************************************************
29695 **
29696 ** This file contains macros and a little bit of code that is common to
29697 ** all of the platform-specific files (os_*.c) and is #included into those
29698 ** files.
29699 **
29700 ** This file should be #included by the os_*.c files only.  It is not a
29701 ** general purpose header file.
29702 */
29703 #ifndef _OS_COMMON_H_
29704 #define _OS_COMMON_H_
29705
29706 /*
29707 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29708 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29709 ** switch.  The following code should catch this problem at compile-time.
29710 */
29711 #ifdef MEMORY_DEBUG
29712 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29713 #endif
29714
29715 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
29716 # ifndef SQLITE_DEBUG_OS_TRACE
29717 #   define SQLITE_DEBUG_OS_TRACE 0
29718 # endif
29719   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
29720 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29721 #else
29722 # define OSTRACE(X)
29723 #endif
29724
29725 /*
29726 ** Macros for performance tracing.  Normally turned off.  Only works
29727 ** on i486 hardware.
29728 */
29729 #ifdef SQLITE_PERFORMANCE_TRACE
29730
29731 /* 
29732 ** hwtime.h contains inline assembler code for implementing 
29733 ** high-performance timing routines.
29734 */
29735 /************** Include hwtime.h in the middle of os_common.h ****************/
29736 /************** Begin file hwtime.h ******************************************/
29737 /*
29738 ** 2008 May 27
29739 **
29740 ** The author disclaims copyright to this source code.  In place of
29741 ** a legal notice, here is a blessing:
29742 **
29743 **    May you do good and not evil.
29744 **    May you find forgiveness for yourself and forgive others.
29745 **    May you share freely, never taking more than you give.
29746 **
29747 ******************************************************************************
29748 **
29749 ** This file contains inline asm code for retrieving "high-performance"
29750 ** counters for x86 class CPUs.
29751 */
29752 #ifndef _HWTIME_H_
29753 #define _HWTIME_H_
29754
29755 /*
29756 ** The following routine only works on pentium-class (or newer) processors.
29757 ** It uses the RDTSC opcode to read the cycle count value out of the
29758 ** processor and returns that value.  This can be used for high-res
29759 ** profiling.
29760 */
29761 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29762       (defined(i386) || defined(__i386__) || defined(_M_IX86))
29763
29764   #if defined(__GNUC__)
29765
29766   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29767      unsigned int lo, hi;
29768      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29769      return (sqlite_uint64)hi << 32 | lo;
29770   }
29771
29772   #elif defined(_MSC_VER)
29773
29774   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29775      __asm {
29776         rdtsc
29777         ret       ; return value at EDX:EAX
29778      }
29779   }
29780
29781   #endif
29782
29783 #elif (defined(__GNUC__) && defined(__x86_64__))
29784
29785   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29786       unsigned long val;
29787       __asm__ __volatile__ ("rdtsc" : "=A" (val));
29788       return val;
29789   }
29790  
29791 #elif (defined(__GNUC__) && defined(__ppc__))
29792
29793   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29794       unsigned long long retval;
29795       unsigned long junk;
29796       __asm__ __volatile__ ("\n\
29797           1:      mftbu   %1\n\
29798                   mftb    %L0\n\
29799                   mftbu   %0\n\
29800                   cmpw    %0,%1\n\
29801                   bne     1b"
29802                   : "=r" (retval), "=r" (junk));
29803       return retval;
29804   }
29805
29806 #else
29807
29808   #error Need implementation of sqlite3Hwtime() for your platform.
29809
29810   /*
29811   ** To compile without implementing sqlite3Hwtime() for your platform,
29812   ** you can remove the above #error and use the following
29813   ** stub function.  You will lose timing support for many
29814   ** of the debugging and testing utilities, but it should at
29815   ** least compile and run.
29816   */
29817 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29818
29819 #endif
29820
29821 #endif /* !defined(_HWTIME_H_) */
29822
29823 /************** End of hwtime.h **********************************************/
29824 /************** Continuing where we left off in os_common.h ******************/
29825
29826 static sqlite_uint64 g_start;
29827 static sqlite_uint64 g_elapsed;
29828 #define TIMER_START       g_start=sqlite3Hwtime()
29829 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29830 #define TIMER_ELAPSED     g_elapsed
29831 #else
29832 #define TIMER_START
29833 #define TIMER_END
29834 #define TIMER_ELAPSED     ((sqlite_uint64)0)
29835 #endif
29836
29837 /*
29838 ** If we compile with the SQLITE_TEST macro set, then the following block
29839 ** of code will give us the ability to simulate a disk I/O error.  This
29840 ** is used for testing the I/O recovery logic.
29841 */
29842 #ifdef SQLITE_TEST
29843 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
29844 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
29845 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
29846 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
29847 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
29848 SQLITE_API int sqlite3_diskfull_pending = 0;
29849 SQLITE_API int sqlite3_diskfull = 0;
29850 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29851 #define SimulateIOError(CODE)  \
29852   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29853        || sqlite3_io_error_pending-- == 1 )  \
29854               { local_ioerr(); CODE; }
29855 static void local_ioerr(){
29856   IOTRACE(("IOERR\n"));
29857   sqlite3_io_error_hit++;
29858   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29859 }
29860 #define SimulateDiskfullError(CODE) \
29861    if( sqlite3_diskfull_pending ){ \
29862      if( sqlite3_diskfull_pending == 1 ){ \
29863        local_ioerr(); \
29864        sqlite3_diskfull = 1; \
29865        sqlite3_io_error_hit = 1; \
29866        CODE; \
29867      }else{ \
29868        sqlite3_diskfull_pending--; \
29869      } \
29870    }
29871 #else
29872 #define SimulateIOErrorBenign(X)
29873 #define SimulateIOError(A)
29874 #define SimulateDiskfullError(A)
29875 #endif
29876
29877 /*
29878 ** When testing, keep a count of the number of open files.
29879 */
29880 #ifdef SQLITE_TEST
29881 SQLITE_API int sqlite3_open_file_count = 0;
29882 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
29883 #else
29884 #define OpenCounter(X)
29885 #endif
29886
29887 #endif /* !defined(_OS_COMMON_H_) */
29888
29889 /************** End of os_common.h *******************************************/
29890 /************** Continuing where we left off in os_win.c *********************/
29891
29892 /*
29893 ** Macro to find the minimum of two numeric values.
29894 */
29895 #ifndef MIN
29896 # define MIN(x,y) ((x)<(y)?(x):(y))
29897 #endif
29898
29899 /*
29900 ** Some Microsoft compilers lack this definition.
29901 */
29902 #ifndef INVALID_FILE_ATTRIBUTES
29903 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
29904 #endif
29905
29906 #ifndef FILE_FLAG_MASK
29907 # define FILE_FLAG_MASK          (0xFF3C0000)
29908 #endif
29909
29910 #ifndef FILE_ATTRIBUTE_MASK
29911 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
29912 #endif
29913
29914 #ifndef SQLITE_OMIT_WAL
29915 /* Forward references */
29916 typedef struct winShm winShm;           /* A connection to shared-memory */
29917 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29918 #endif
29919
29920 /*
29921 ** WinCE lacks native support for file locking so we have to fake it
29922 ** with some code of our own.
29923 */
29924 #if SQLITE_OS_WINCE
29925 typedef struct winceLock {
29926   int nReaders;       /* Number of reader locks obtained */
29927   BOOL bPending;      /* Indicates a pending lock has been obtained */
29928   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
29929   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
29930 } winceLock;
29931 #endif
29932
29933 /*
29934 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
29935 ** portability layer.
29936 */
29937 typedef struct winFile winFile;
29938 struct winFile {
29939   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29940   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29941   HANDLE h;               /* Handle for accessing the file */
29942   u8 locktype;            /* Type of lock currently held on this file */
29943   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29944   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
29945   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29946 #ifndef SQLITE_OMIT_WAL
29947   winShm *pShm;           /* Instance of shared memory on this file */
29948 #endif
29949   const char *zPath;      /* Full pathname of this file */
29950   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
29951 #if SQLITE_OS_WINCE
29952   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
29953   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29954   HANDLE hShared;         /* Shared memory segment used for locking */
29955   winceLock local;        /* Locks obtained by this instance of winFile */
29956   winceLock *shared;      /* Global shared lock memory for the file  */
29957 #endif
29958 };
29959
29960 /*
29961 ** Allowed values for winFile.ctrlFlags
29962 */
29963 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
29964 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29965
29966 /*
29967  * The size of the buffer used by sqlite3_win32_write_debug().
29968  */
29969 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
29970 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
29971 #endif
29972
29973 /*
29974  * The value used with sqlite3_win32_set_directory() to specify that
29975  * the data directory should be changed.
29976  */
29977 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
29978 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
29979 #endif
29980
29981 /*
29982  * The value used with sqlite3_win32_set_directory() to specify that
29983  * the temporary directory should be changed.
29984  */
29985 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
29986 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
29987 #endif
29988
29989 /*
29990  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
29991  * various Win32 API heap functions instead of our own.
29992  */
29993 #ifdef SQLITE_WIN32_MALLOC
29994
29995 /*
29996  * If this is non-zero, an isolated heap will be created by the native Win32
29997  * allocator subsystem; otherwise, the default process heap will be used.  This
29998  * setting has no effect when compiling for WinRT.  By default, this is enabled
29999  * and an isolated heap will be created to store all allocated data.
30000  *
30001  ******************************************************************************
30002  * WARNING: It is important to note that when this setting is non-zero and the
30003  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30004  *          function), all data that was allocated using the isolated heap will
30005  *          be freed immediately and any attempt to access any of that freed
30006  *          data will almost certainly result in an immediate access violation.
30007  ******************************************************************************
30008  */
30009 #ifndef SQLITE_WIN32_HEAP_CREATE
30010 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30011 #endif
30012
30013 /*
30014  * The initial size of the Win32-specific heap.  This value may be zero.
30015  */
30016 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30017 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30018                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30019 #endif
30020
30021 /*
30022  * The maximum size of the Win32-specific heap.  This value may be zero.
30023  */
30024 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30025 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30026 #endif
30027
30028 /*
30029  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30030  * zero for the default behavior.
30031  */
30032 #ifndef SQLITE_WIN32_HEAP_FLAGS
30033 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
30034 #endif
30035
30036 /*
30037 ** The winMemData structure stores information required by the Win32-specific
30038 ** sqlite3_mem_methods implementation.
30039 */
30040 typedef struct winMemData winMemData;
30041 struct winMemData {
30042 #ifndef NDEBUG
30043   u32 magic;    /* Magic number to detect structure corruption. */
30044 #endif
30045   HANDLE hHeap; /* The handle to our heap. */
30046   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30047 };
30048
30049 #ifndef NDEBUG
30050 #define WINMEM_MAGIC     0x42b2830b
30051 #endif
30052
30053 static struct winMemData win_mem_data = {
30054 #ifndef NDEBUG
30055   WINMEM_MAGIC,
30056 #endif
30057   NULL, FALSE
30058 };
30059
30060 #ifndef NDEBUG
30061 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30062 #else
30063 #define winMemAssertMagic()
30064 #endif
30065
30066 #define winMemGetHeap() win_mem_data.hHeap
30067
30068 static void *winMemMalloc(int nBytes);
30069 static void winMemFree(void *pPrior);
30070 static void *winMemRealloc(void *pPrior, int nBytes);
30071 static int winMemSize(void *p);
30072 static int winMemRoundup(int n);
30073 static int winMemInit(void *pAppData);
30074 static void winMemShutdown(void *pAppData);
30075
30076 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30077 #endif /* SQLITE_WIN32_MALLOC */
30078
30079 /*
30080 ** The following variable is (normally) set once and never changes
30081 ** thereafter.  It records whether the operating system is Win9x
30082 ** or WinNT.
30083 **
30084 ** 0:   Operating system unknown.
30085 ** 1:   Operating system is Win9x.
30086 ** 2:   Operating system is WinNT.
30087 **
30088 ** In order to facilitate testing on a WinNT system, the test fixture
30089 ** can manually set this value to 1 to emulate Win98 behavior.
30090 */
30091 #ifdef SQLITE_TEST
30092 SQLITE_API int sqlite3_os_type = 0;
30093 #else
30094 static int sqlite3_os_type = 0;
30095 #endif
30096
30097 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30098 #  define SQLITE_WIN32_HAS_ANSI
30099 #endif
30100
30101 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30102 #  define SQLITE_WIN32_HAS_WIDE
30103 #endif
30104
30105 #ifndef SYSCALL
30106 #  define SYSCALL sqlite3_syscall_ptr
30107 #endif
30108
30109 /*
30110 ** This function is not available on Windows CE or WinRT.
30111  */
30112
30113 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30114 #  define osAreFileApisANSI()       1
30115 #endif
30116
30117 /*
30118 ** Many system calls are accessed through pointer-to-functions so that
30119 ** they may be overridden at runtime to facilitate fault injection during
30120 ** testing and sandboxing.  The following array holds the names and pointers
30121 ** to all overrideable system calls.
30122 */
30123 static struct win_syscall {
30124   const char *zName;            /* Name of the sytem call */
30125   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30126   sqlite3_syscall_ptr pDefault; /* Default value */
30127 } aSyscall[] = {
30128 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30129   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
30130 #else
30131   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
30132 #endif
30133
30134 #ifndef osAreFileApisANSI
30135 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
30136 #endif
30137
30138 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30139   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
30140 #else
30141   { "CharLowerW",              (SYSCALL)0,                       0 },
30142 #endif
30143
30144 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
30145
30146 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30147   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
30148 #else
30149   { "CharUpperW",              (SYSCALL)0,                       0 },
30150 #endif
30151
30152 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
30153
30154   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
30155
30156 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
30157
30158 #if defined(SQLITE_WIN32_HAS_ANSI)
30159   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
30160 #else
30161   { "CreateFileA",             (SYSCALL)0,                       0 },
30162 #endif
30163
30164 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
30165         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
30166
30167 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30168   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
30169 #else
30170   { "CreateFileW",             (SYSCALL)0,                       0 },
30171 #endif
30172
30173 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
30174         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
30175
30176 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30177         !defined(SQLITE_OMIT_WAL))
30178   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
30179 #else
30180   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
30181 #endif
30182
30183 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30184         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[6].pCurrent)
30185
30186 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30187   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
30188 #else
30189   { "CreateMutexW",            (SYSCALL)0,                       0 },
30190 #endif
30191
30192 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
30193         LPCWSTR))aSyscall[7].pCurrent)
30194
30195 #if defined(SQLITE_WIN32_HAS_ANSI)
30196   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
30197 #else
30198   { "DeleteFileA",             (SYSCALL)0,                       0 },
30199 #endif
30200
30201 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[8].pCurrent)
30202
30203 #if defined(SQLITE_WIN32_HAS_WIDE)
30204   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
30205 #else
30206   { "DeleteFileW",             (SYSCALL)0,                       0 },
30207 #endif
30208
30209 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[9].pCurrent)
30210
30211 #if SQLITE_OS_WINCE
30212   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
30213 #else
30214   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
30215 #endif
30216
30217 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30218         LPFILETIME))aSyscall[10].pCurrent)
30219
30220 #if SQLITE_OS_WINCE
30221   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
30222 #else
30223   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
30224 #endif
30225
30226 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30227         LPSYSTEMTIME))aSyscall[11].pCurrent)
30228
30229   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
30230
30231 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[12].pCurrent)
30232
30233 #if defined(SQLITE_WIN32_HAS_ANSI)
30234   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
30235 #else
30236   { "FormatMessageA",          (SYSCALL)0,                       0 },
30237 #endif
30238
30239 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
30240         DWORD,va_list*))aSyscall[13].pCurrent)
30241
30242 #if defined(SQLITE_WIN32_HAS_WIDE)
30243   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
30244 #else
30245   { "FormatMessageW",          (SYSCALL)0,                       0 },
30246 #endif
30247
30248 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
30249         DWORD,va_list*))aSyscall[14].pCurrent)
30250
30251   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
30252
30253 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[15].pCurrent)
30254
30255   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
30256
30257 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[16].pCurrent)
30258
30259 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30260   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
30261 #else
30262   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
30263 #endif
30264
30265 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
30266         LPDWORD))aSyscall[17].pCurrent)
30267
30268 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30269   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
30270 #else
30271   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
30272 #endif
30273
30274 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
30275         LPDWORD))aSyscall[18].pCurrent)
30276
30277 #if defined(SQLITE_WIN32_HAS_ANSI)
30278   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
30279 #else
30280   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
30281 #endif
30282
30283 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[19].pCurrent)
30284
30285 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30286   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
30287 #else
30288   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
30289 #endif
30290
30291 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[20].pCurrent)
30292
30293 #if defined(SQLITE_WIN32_HAS_WIDE)
30294   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
30295 #else
30296   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
30297 #endif
30298
30299 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
30300         LPVOID))aSyscall[21].pCurrent)
30301
30302 #if !SQLITE_OS_WINRT
30303   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
30304 #else
30305   { "GetFileSize",             (SYSCALL)0,                       0 },
30306 #endif
30307
30308 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[22].pCurrent)
30309
30310 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30311   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
30312 #else
30313   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
30314 #endif
30315
30316 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
30317         LPSTR*))aSyscall[23].pCurrent)
30318
30319 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30320   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
30321 #else
30322   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
30323 #endif
30324
30325 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
30326         LPWSTR*))aSyscall[24].pCurrent)
30327
30328   { "GetLastError",            (SYSCALL)GetLastError,            0 },
30329
30330 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[25].pCurrent)
30331
30332 #if SQLITE_OS_WINCE
30333   /* The GetProcAddressA() routine is only available on Windows CE. */
30334   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
30335 #else
30336   /* All other Windows platforms expect GetProcAddress() to take
30337   ** an ANSI string regardless of the _UNICODE setting */
30338   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
30339 #endif
30340
30341 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
30342         LPCSTR))aSyscall[26].pCurrent)
30343
30344 #if !SQLITE_OS_WINRT
30345   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
30346 #else
30347   { "GetSystemInfo",           (SYSCALL)0,                       0 },
30348 #endif
30349
30350 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[27].pCurrent)
30351
30352   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
30353
30354 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[28].pCurrent)
30355
30356 #if !SQLITE_OS_WINCE
30357   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
30358 #else
30359   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
30360 #endif
30361
30362 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
30363         LPFILETIME))aSyscall[29].pCurrent)
30364
30365 #if defined(SQLITE_WIN32_HAS_ANSI)
30366   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
30367 #else
30368   { "GetTempPathA",            (SYSCALL)0,                       0 },
30369 #endif
30370
30371 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[30].pCurrent)
30372
30373 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30374   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
30375 #else
30376   { "GetTempPathW",            (SYSCALL)0,                       0 },
30377 #endif
30378
30379 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[31].pCurrent)
30380
30381 #if !SQLITE_OS_WINRT
30382   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
30383 #else
30384   { "GetTickCount",            (SYSCALL)0,                       0 },
30385 #endif
30386
30387 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[32].pCurrent)
30388
30389 #if defined(SQLITE_WIN32_HAS_ANSI)
30390   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
30391 #else
30392   { "GetVersionExA",           (SYSCALL)0,                       0 },
30393 #endif
30394
30395 #define osGetVersionExA ((BOOL(WINAPI*)( \
30396         LPOSVERSIONINFOA))aSyscall[33].pCurrent)
30397
30398   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
30399
30400 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
30401         SIZE_T))aSyscall[34].pCurrent)
30402
30403 #if !SQLITE_OS_WINRT
30404   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
30405 #else
30406   { "HeapCreate",              (SYSCALL)0,                       0 },
30407 #endif
30408
30409 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
30410         SIZE_T))aSyscall[35].pCurrent)
30411
30412 #if !SQLITE_OS_WINRT
30413   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
30414 #else
30415   { "HeapDestroy",             (SYSCALL)0,                       0 },
30416 #endif
30417
30418 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[36].pCurrent)
30419
30420   { "HeapFree",                (SYSCALL)HeapFree,                0 },
30421
30422 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[37].pCurrent)
30423
30424   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
30425
30426 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
30427         SIZE_T))aSyscall[38].pCurrent)
30428
30429   { "HeapSize",                (SYSCALL)HeapSize,                0 },
30430
30431 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
30432         LPCVOID))aSyscall[39].pCurrent)
30433
30434 #if !SQLITE_OS_WINRT
30435   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
30436 #else
30437   { "HeapValidate",            (SYSCALL)0,                       0 },
30438 #endif
30439
30440 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
30441         LPCVOID))aSyscall[40].pCurrent)
30442
30443 #if defined(SQLITE_WIN32_HAS_ANSI)
30444   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
30445 #else
30446   { "LoadLibraryA",            (SYSCALL)0,                       0 },
30447 #endif
30448
30449 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[41].pCurrent)
30450
30451 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30452   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
30453 #else
30454   { "LoadLibraryW",            (SYSCALL)0,                       0 },
30455 #endif
30456
30457 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[42].pCurrent)
30458
30459 #if !SQLITE_OS_WINRT
30460   { "LocalFree",               (SYSCALL)LocalFree,               0 },
30461 #else
30462   { "LocalFree",               (SYSCALL)0,                       0 },
30463 #endif
30464
30465 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[43].pCurrent)
30466
30467 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30468   { "LockFile",                (SYSCALL)LockFile,                0 },
30469 #else
30470   { "LockFile",                (SYSCALL)0,                       0 },
30471 #endif
30472
30473 #ifndef osLockFile
30474 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30475         DWORD))aSyscall[44].pCurrent)
30476 #endif
30477
30478 #if !SQLITE_OS_WINCE
30479   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
30480 #else
30481   { "LockFileEx",              (SYSCALL)0,                       0 },
30482 #endif
30483
30484 #ifndef osLockFileEx
30485 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
30486         LPOVERLAPPED))aSyscall[45].pCurrent)
30487 #endif
30488
30489 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
30490   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
30491 #else
30492   { "MapViewOfFile",           (SYSCALL)0,                       0 },
30493 #endif
30494
30495 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30496         SIZE_T))aSyscall[46].pCurrent)
30497
30498   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
30499
30500 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
30501         int))aSyscall[47].pCurrent)
30502
30503   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
30504
30505 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
30506         LARGE_INTEGER*))aSyscall[48].pCurrent)
30507
30508   { "ReadFile",                (SYSCALL)ReadFile,                0 },
30509
30510 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
30511         LPOVERLAPPED))aSyscall[49].pCurrent)
30512
30513   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
30514
30515 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[50].pCurrent)
30516
30517 #if !SQLITE_OS_WINRT
30518   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
30519 #else
30520   { "SetFilePointer",          (SYSCALL)0,                       0 },
30521 #endif
30522
30523 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
30524         DWORD))aSyscall[51].pCurrent)
30525
30526 #if !SQLITE_OS_WINRT
30527   { "Sleep",                   (SYSCALL)Sleep,                   0 },
30528 #else
30529   { "Sleep",                   (SYSCALL)0,                       0 },
30530 #endif
30531
30532 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[52].pCurrent)
30533
30534   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
30535
30536 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
30537         LPFILETIME))aSyscall[53].pCurrent)
30538
30539 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30540   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
30541 #else
30542   { "UnlockFile",              (SYSCALL)0,                       0 },
30543 #endif
30544
30545 #ifndef osUnlockFile
30546 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30547         DWORD))aSyscall[54].pCurrent)
30548 #endif
30549
30550 #if !SQLITE_OS_WINCE
30551   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
30552 #else
30553   { "UnlockFileEx",            (SYSCALL)0,                       0 },
30554 #endif
30555
30556 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30557         LPOVERLAPPED))aSyscall[55].pCurrent)
30558
30559 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
30560   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
30561 #else
30562   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
30563 #endif
30564
30565 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[56].pCurrent)
30566
30567   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
30568
30569 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
30570         LPCSTR,LPBOOL))aSyscall[57].pCurrent)
30571
30572   { "WriteFile",               (SYSCALL)WriteFile,               0 },
30573
30574 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
30575         LPOVERLAPPED))aSyscall[58].pCurrent)
30576
30577 #if SQLITE_OS_WINRT
30578   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
30579 #else
30580   { "CreateEventExW",          (SYSCALL)0,                       0 },
30581 #endif
30582
30583 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
30584         DWORD,DWORD))aSyscall[59].pCurrent)
30585
30586 #if !SQLITE_OS_WINRT
30587   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
30588 #else
30589   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
30590 #endif
30591
30592 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
30593         DWORD))aSyscall[60].pCurrent)
30594
30595 #if SQLITE_OS_WINRT
30596   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
30597 #else
30598   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
30599 #endif
30600
30601 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
30602         BOOL))aSyscall[61].pCurrent)
30603
30604 #if SQLITE_OS_WINRT
30605   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
30606 #else
30607   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
30608 #endif
30609
30610 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
30611         PLARGE_INTEGER,DWORD))aSyscall[62].pCurrent)
30612
30613 #if SQLITE_OS_WINRT
30614   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
30615 #else
30616   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
30617 #endif
30618
30619 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
30620         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[63].pCurrent)
30621
30622 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
30623   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
30624 #else
30625   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
30626 #endif
30627
30628 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
30629         SIZE_T))aSyscall[64].pCurrent)
30630
30631 #if SQLITE_OS_WINRT
30632   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
30633 #else
30634   { "CreateFile2",             (SYSCALL)0,                       0 },
30635 #endif
30636
30637 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
30638         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[65].pCurrent)
30639
30640 #if SQLITE_OS_WINRT
30641   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
30642 #else
30643   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
30644 #endif
30645
30646 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
30647         DWORD))aSyscall[66].pCurrent)
30648
30649 #if SQLITE_OS_WINRT
30650   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
30651 #else
30652   { "GetTickCount64",          (SYSCALL)0,                       0 },
30653 #endif
30654
30655 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[67].pCurrent)
30656
30657 #if SQLITE_OS_WINRT
30658   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
30659 #else
30660   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
30661 #endif
30662
30663 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
30664         LPSYSTEM_INFO))aSyscall[68].pCurrent)
30665
30666 #if defined(SQLITE_WIN32_HAS_ANSI)
30667   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
30668 #else
30669   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
30670 #endif
30671
30672 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[69].pCurrent)
30673
30674 #if defined(SQLITE_WIN32_HAS_WIDE)
30675   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
30676 #else
30677   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
30678 #endif
30679
30680 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[70].pCurrent)
30681
30682   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
30683
30684 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[71].pCurrent)
30685
30686 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
30687   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
30688 #else
30689   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
30690 #endif
30691
30692 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
30693         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[72].pCurrent)
30694
30695 }; /* End of the overrideable system calls */
30696
30697 /*
30698 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
30699 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
30700 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
30701 ** system call named zName.
30702 */
30703 static int winSetSystemCall(
30704   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
30705   const char *zName,            /* Name of system call to override */
30706   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
30707 ){
30708   unsigned int i;
30709   int rc = SQLITE_NOTFOUND;
30710
30711   UNUSED_PARAMETER(pNotUsed);
30712   if( zName==0 ){
30713     /* If no zName is given, restore all system calls to their default
30714     ** settings and return NULL
30715     */
30716     rc = SQLITE_OK;
30717     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30718       if( aSyscall[i].pDefault ){
30719         aSyscall[i].pCurrent = aSyscall[i].pDefault;
30720       }
30721     }
30722   }else{
30723     /* If zName is specified, operate on only the one system call
30724     ** specified.
30725     */
30726     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30727       if( strcmp(zName, aSyscall[i].zName)==0 ){
30728         if( aSyscall[i].pDefault==0 ){
30729           aSyscall[i].pDefault = aSyscall[i].pCurrent;
30730         }
30731         rc = SQLITE_OK;
30732         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
30733         aSyscall[i].pCurrent = pNewFunc;
30734         break;
30735       }
30736     }
30737   }
30738   return rc;
30739 }
30740
30741 /*
30742 ** Return the value of a system call.  Return NULL if zName is not a
30743 ** recognized system call name.  NULL is also returned if the system call
30744 ** is currently undefined.
30745 */
30746 static sqlite3_syscall_ptr winGetSystemCall(
30747   sqlite3_vfs *pNotUsed,
30748   const char *zName
30749 ){
30750   unsigned int i;
30751
30752   UNUSED_PARAMETER(pNotUsed);
30753   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30754     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
30755   }
30756   return 0;
30757 }
30758
30759 /*
30760 ** Return the name of the first system call after zName.  If zName==NULL
30761 ** then return the name of the first system call.  Return NULL if zName
30762 ** is the last system call or if zName is not the name of a valid
30763 ** system call.
30764 */
30765 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
30766   int i = -1;
30767
30768   UNUSED_PARAMETER(p);
30769   if( zName ){
30770     for(i=0; i<ArraySize(aSyscall)-1; i++){
30771       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
30772     }
30773   }
30774   for(i++; i<ArraySize(aSyscall); i++){
30775     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
30776   }
30777   return 0;
30778 }
30779
30780 /*
30781 ** This function outputs the specified (ANSI) string to the Win32 debugger
30782 ** (if available).
30783 */
30784
30785 SQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){
30786   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
30787   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
30788   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
30789   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
30790 #if defined(SQLITE_WIN32_HAS_ANSI)
30791   if( nMin>0 ){
30792     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
30793     memcpy(zDbgBuf, zBuf, nMin);
30794     osOutputDebugStringA(zDbgBuf);
30795   }else{
30796     osOutputDebugStringA(zBuf);
30797   }
30798 #elif defined(SQLITE_WIN32_HAS_WIDE)
30799   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
30800   if ( osMultiByteToWideChar(
30801           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
30802           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
30803     return;
30804   }
30805   osOutputDebugStringW((LPCWSTR)zDbgBuf);
30806 #else
30807   if( nMin>0 ){
30808     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
30809     memcpy(zDbgBuf, zBuf, nMin);
30810     fprintf(stderr, "%s", zDbgBuf);
30811   }else{
30812     fprintf(stderr, "%s", zBuf);
30813   }
30814 #endif
30815 }
30816
30817 /*
30818 ** The following routine suspends the current thread for at least ms
30819 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
30820 */
30821 #if SQLITE_OS_WINRT
30822 static HANDLE sleepObj = NULL;
30823 #endif
30824
30825 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
30826 #if SQLITE_OS_WINRT
30827   if ( sleepObj==NULL ){
30828     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
30829                                 SYNCHRONIZE);
30830   }
30831   assert( sleepObj!=NULL );
30832   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
30833 #else
30834   osSleep(milliseconds);
30835 #endif
30836 }
30837
30838 /*
30839 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
30840 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
30841 **
30842 ** Here is an interesting observation:  Win95, Win98, and WinME lack
30843 ** the LockFileEx() API.  But we can still statically link against that
30844 ** API as long as we don't call it when running Win95/98/ME.  A call to
30845 ** this routine is used to determine if the host is Win95/98/ME or
30846 ** WinNT/2K/XP so that we will know whether or not we can safely call
30847 ** the LockFileEx() API.
30848 */
30849 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30850 # define isNT()  (1)
30851 #else
30852   static int isNT(void){
30853     if( sqlite3_os_type==0 ){
30854       OSVERSIONINFOA sInfo;
30855       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
30856       osGetVersionExA(&sInfo);
30857       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
30858     }
30859     return sqlite3_os_type==2;
30860   }
30861 #endif /* SQLITE_OS_WINCE */
30862
30863 #ifdef SQLITE_WIN32_MALLOC
30864 /*
30865 ** Allocate nBytes of memory.
30866 */
30867 static void *winMemMalloc(int nBytes){
30868   HANDLE hHeap;
30869   void *p;
30870
30871   winMemAssertMagic();
30872   hHeap = winMemGetHeap();
30873   assert( hHeap!=0 );
30874   assert( hHeap!=INVALID_HANDLE_VALUE );
30875 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
30876   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
30877 #endif
30878   assert( nBytes>=0 );
30879   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
30880   if( !p ){
30881     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
30882                 nBytes, osGetLastError(), (void*)hHeap);
30883   }
30884   return p;
30885 }
30886
30887 /*
30888 ** Free memory.
30889 */
30890 static void winMemFree(void *pPrior){
30891   HANDLE hHeap;
30892
30893   winMemAssertMagic();
30894   hHeap = winMemGetHeap();
30895   assert( hHeap!=0 );
30896   assert( hHeap!=INVALID_HANDLE_VALUE );
30897 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
30898   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
30899 #endif
30900   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
30901   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
30902     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
30903                 pPrior, osGetLastError(), (void*)hHeap);
30904   }
30905 }
30906
30907 /*
30908 ** Change the size of an existing memory allocation
30909 */
30910 static void *winMemRealloc(void *pPrior, int nBytes){
30911   HANDLE hHeap;
30912   void *p;
30913
30914   winMemAssertMagic();
30915   hHeap = winMemGetHeap();
30916   assert( hHeap!=0 );
30917   assert( hHeap!=INVALID_HANDLE_VALUE );
30918 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
30919   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
30920 #endif
30921   assert( nBytes>=0 );
30922   if( !pPrior ){
30923     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
30924   }else{
30925     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
30926   }
30927   if( !p ){
30928     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
30929                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
30930                 (void*)hHeap);
30931   }
30932   return p;
30933 }
30934
30935 /*
30936 ** Return the size of an outstanding allocation, in bytes.
30937 */
30938 static int winMemSize(void *p){
30939   HANDLE hHeap;
30940   SIZE_T n;
30941
30942   winMemAssertMagic();
30943   hHeap = winMemGetHeap();
30944   assert( hHeap!=0 );
30945   assert( hHeap!=INVALID_HANDLE_VALUE );
30946 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
30947   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
30948 #endif
30949   if( !p ) return 0;
30950   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
30951   if( n==(SIZE_T)-1 ){
30952     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
30953                 p, osGetLastError(), (void*)hHeap);
30954     return 0;
30955   }
30956   return (int)n;
30957 }
30958
30959 /*
30960 ** Round up a request size to the next valid allocation size.
30961 */
30962 static int winMemRoundup(int n){
30963   return n;
30964 }
30965
30966 /*
30967 ** Initialize this module.
30968 */
30969 static int winMemInit(void *pAppData){
30970   winMemData *pWinMemData = (winMemData *)pAppData;
30971
30972   if( !pWinMemData ) return SQLITE_ERROR;
30973   assert( pWinMemData->magic==WINMEM_MAGIC );
30974
30975 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
30976   if( !pWinMemData->hHeap ){
30977     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
30978                                       SQLITE_WIN32_HEAP_INIT_SIZE,
30979                                       SQLITE_WIN32_HEAP_MAX_SIZE);
30980     if( !pWinMemData->hHeap ){
30981       sqlite3_log(SQLITE_NOMEM,
30982           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
30983           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
30984           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
30985       return SQLITE_NOMEM;
30986     }
30987     pWinMemData->bOwned = TRUE;
30988     assert( pWinMemData->bOwned );
30989   }
30990 #else
30991   pWinMemData->hHeap = osGetProcessHeap();
30992   if( !pWinMemData->hHeap ){
30993     sqlite3_log(SQLITE_NOMEM,
30994         "failed to GetProcessHeap (%d)", osGetLastError());
30995     return SQLITE_NOMEM;
30996   }
30997   pWinMemData->bOwned = FALSE;
30998   assert( !pWinMemData->bOwned );
30999 #endif
31000   assert( pWinMemData->hHeap!=0 );
31001   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31002 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31003   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31004 #endif
31005   return SQLITE_OK;
31006 }
31007
31008 /*
31009 ** Deinitialize this module.
31010 */
31011 static void winMemShutdown(void *pAppData){
31012   winMemData *pWinMemData = (winMemData *)pAppData;
31013
31014   if( !pWinMemData ) return;
31015   if( pWinMemData->hHeap ){
31016     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31017 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31018     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31019 #endif
31020     if( pWinMemData->bOwned ){
31021       if( !osHeapDestroy(pWinMemData->hHeap) ){
31022         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31023                     osGetLastError(), (void*)pWinMemData->hHeap);
31024       }
31025       pWinMemData->bOwned = FALSE;
31026     }
31027     pWinMemData->hHeap = NULL;
31028   }
31029 }
31030
31031 /*
31032 ** Populate the low-level memory allocation function pointers in
31033 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31034 ** arguments specify the block of memory to manage.
31035 **
31036 ** This routine is only called by sqlite3_config(), and therefore
31037 ** is not required to be threadsafe (it is not).
31038 */
31039 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31040   static const sqlite3_mem_methods winMemMethods = {
31041     winMemMalloc,
31042     winMemFree,
31043     winMemRealloc,
31044     winMemSize,
31045     winMemRoundup,
31046     winMemInit,
31047     winMemShutdown,
31048     &win_mem_data
31049   };
31050   return &winMemMethods;
31051 }
31052
31053 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31054   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31055 }
31056 #endif /* SQLITE_WIN32_MALLOC */
31057
31058 /*
31059 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
31060 **
31061 ** Space to hold the returned string is obtained from malloc.
31062 */
31063 static LPWSTR utf8ToUnicode(const char *zFilename){
31064   int nChar;
31065   LPWSTR zWideFilename;
31066
31067   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31068   if( nChar==0 ){
31069     return 0;
31070   }
31071   zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
31072   if( zWideFilename==0 ){
31073     return 0;
31074   }
31075   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
31076                                 nChar);
31077   if( nChar==0 ){
31078     sqlite3_free(zWideFilename);
31079     zWideFilename = 0;
31080   }
31081   return zWideFilename;
31082 }
31083
31084 /*
31085 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
31086 ** obtained from sqlite3_malloc().
31087 */
31088 static char *unicodeToUtf8(LPCWSTR zWideFilename){
31089   int nByte;
31090   char *zFilename;
31091
31092   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31093   if( nByte == 0 ){
31094     return 0;
31095   }
31096   zFilename = sqlite3_malloc( nByte );
31097   if( zFilename==0 ){
31098     return 0;
31099   }
31100   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31101                                 0, 0);
31102   if( nByte == 0 ){
31103     sqlite3_free(zFilename);
31104     zFilename = 0;
31105   }
31106   return zFilename;
31107 }
31108
31109 /*
31110 ** Convert an ANSI string to Microsoft Unicode, based on the
31111 ** current codepage settings for file apis.
31112 ** 
31113 ** Space to hold the returned string is obtained
31114 ** from sqlite3_malloc.
31115 */
31116 static LPWSTR mbcsToUnicode(const char *zFilename){
31117   int nByte;
31118   LPWSTR zMbcsFilename;
31119   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31120
31121   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
31122                                 0)*sizeof(WCHAR);
31123   if( nByte==0 ){
31124     return 0;
31125   }
31126   zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
31127   if( zMbcsFilename==0 ){
31128     return 0;
31129   }
31130   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
31131                                 nByte);
31132   if( nByte==0 ){
31133     sqlite3_free(zMbcsFilename);
31134     zMbcsFilename = 0;
31135   }
31136   return zMbcsFilename;
31137 }
31138
31139 /*
31140 ** Convert Microsoft Unicode to multi-byte character string, based on the
31141 ** user's ANSI codepage.
31142 **
31143 ** Space to hold the returned string is obtained from
31144 ** sqlite3_malloc().
31145 */
31146 static char *unicodeToMbcs(LPCWSTR zWideFilename){
31147   int nByte;
31148   char *zFilename;
31149   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31150
31151   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31152   if( nByte == 0 ){
31153     return 0;
31154   }
31155   zFilename = sqlite3_malloc( nByte );
31156   if( zFilename==0 ){
31157     return 0;
31158   }
31159   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
31160                                 nByte, 0, 0);
31161   if( nByte == 0 ){
31162     sqlite3_free(zFilename);
31163     zFilename = 0;
31164   }
31165   return zFilename;
31166 }
31167
31168 /*
31169 ** Convert multibyte character string to UTF-8.  Space to hold the
31170 ** returned string is obtained from sqlite3_malloc().
31171 */
31172 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31173   char *zFilenameUtf8;
31174   LPWSTR zTmpWide;
31175
31176   zTmpWide = mbcsToUnicode(zFilename);
31177   if( zTmpWide==0 ){
31178     return 0;
31179   }
31180   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31181   sqlite3_free(zTmpWide);
31182   return zFilenameUtf8;
31183 }
31184
31185 /*
31186 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31187 ** returned string is obtained from sqlite3_malloc().
31188 */
31189 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
31190   char *zFilenameMbcs;
31191   LPWSTR zTmpWide;
31192
31193   zTmpWide = utf8ToUnicode(zFilename);
31194   if( zTmpWide==0 ){
31195     return 0;
31196   }
31197   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31198   sqlite3_free(zTmpWide);
31199   return zFilenameMbcs;
31200 }
31201
31202 /*
31203 ** This function sets the data directory or the temporary directory based on
31204 ** the provided arguments.  The type argument must be 1 in order to set the
31205 ** data directory or 2 in order to set the temporary directory.  The zValue
31206 ** argument is the name of the directory to use.  The return value will be
31207 ** SQLITE_OK if successful.
31208 */
31209 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
31210   char **ppDirectory = 0;
31211 #ifndef SQLITE_OMIT_AUTOINIT
31212   int rc = sqlite3_initialize();
31213   if( rc ) return rc;
31214 #endif
31215   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
31216     ppDirectory = &sqlite3_data_directory;
31217   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
31218     ppDirectory = &sqlite3_temp_directory;
31219   }
31220   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
31221           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31222   );
31223   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
31224   if( ppDirectory ){
31225     char *zValueUtf8 = 0;
31226     if( zValue && zValue[0] ){
31227       zValueUtf8 = unicodeToUtf8(zValue);
31228       if ( zValueUtf8==0 ){
31229         return SQLITE_NOMEM;
31230       }
31231     }
31232     sqlite3_free(*ppDirectory);
31233     *ppDirectory = zValueUtf8;
31234     return SQLITE_OK;
31235   }
31236   return SQLITE_ERROR;
31237 }
31238
31239 /*
31240 ** The return value of getLastErrorMsg
31241 ** is zero if the error message fits in the buffer, or non-zero
31242 ** otherwise (if the message was truncated).
31243 */
31244 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
31245   /* FormatMessage returns 0 on failure.  Otherwise it
31246   ** returns the number of TCHARs written to the output
31247   ** buffer, excluding the terminating null char.
31248   */
31249   DWORD dwLen = 0;
31250   char *zOut = 0;
31251
31252   if( isNT() ){
31253 #if SQLITE_OS_WINRT
31254     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
31255     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
31256                              FORMAT_MESSAGE_IGNORE_INSERTS,
31257                              NULL,
31258                              lastErrno,
31259                              0,
31260                              zTempWide,
31261                              MAX_PATH,
31262                              0);
31263 #else
31264     LPWSTR zTempWide = NULL;
31265     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31266                              FORMAT_MESSAGE_FROM_SYSTEM |
31267                              FORMAT_MESSAGE_IGNORE_INSERTS,
31268                              NULL,
31269                              lastErrno,
31270                              0,
31271                              (LPWSTR) &zTempWide,
31272                              0,
31273                              0);
31274 #endif
31275     if( dwLen > 0 ){
31276       /* allocate a buffer and convert to UTF8 */
31277       sqlite3BeginBenignMalloc();
31278       zOut = unicodeToUtf8(zTempWide);
31279       sqlite3EndBenignMalloc();
31280 #if !SQLITE_OS_WINRT
31281       /* free the system buffer allocated by FormatMessage */
31282       osLocalFree(zTempWide);
31283 #endif
31284     }
31285   }
31286 #ifdef SQLITE_WIN32_HAS_ANSI
31287   else{
31288     char *zTemp = NULL;
31289     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31290                              FORMAT_MESSAGE_FROM_SYSTEM |
31291                              FORMAT_MESSAGE_IGNORE_INSERTS,
31292                              NULL,
31293                              lastErrno,
31294                              0,
31295                              (LPSTR) &zTemp,
31296                              0,
31297                              0);
31298     if( dwLen > 0 ){
31299       /* allocate a buffer and convert to UTF8 */
31300       sqlite3BeginBenignMalloc();
31301       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31302       sqlite3EndBenignMalloc();
31303       /* free the system buffer allocated by FormatMessage */
31304       osLocalFree(zTemp);
31305     }
31306   }
31307 #endif
31308   if( 0 == dwLen ){
31309     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
31310   }else{
31311     /* copy a maximum of nBuf chars to output buffer */
31312     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31313     /* free the UTF8 buffer */
31314     sqlite3_free(zOut);
31315   }
31316   return 0;
31317 }
31318
31319 /*
31320 **
31321 ** This function - winLogErrorAtLine() - is only ever called via the macro
31322 ** winLogError().
31323 **
31324 ** This routine is invoked after an error occurs in an OS function.
31325 ** It logs a message using sqlite3_log() containing the current value of
31326 ** error code and, if possible, the human-readable equivalent from 
31327 ** FormatMessage.
31328 **
31329 ** The first argument passed to the macro should be the error code that
31330 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
31331 ** The two subsequent arguments should be the name of the OS function that
31332 ** failed and the associated file-system path, if any.
31333 */
31334 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
31335 static int winLogErrorAtLine(
31336   int errcode,                    /* SQLite error code */
31337   DWORD lastErrno,                /* Win32 last error */
31338   const char *zFunc,              /* Name of OS function that failed */
31339   const char *zPath,              /* File path associated with error */
31340   int iLine                       /* Source line number where error occurred */
31341 ){
31342   char zMsg[500];                 /* Human readable error text */
31343   int i;                          /* Loop counter */
31344
31345   zMsg[0] = 0;
31346   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
31347   assert( errcode!=SQLITE_OK );
31348   if( zPath==0 ) zPath = "";
31349   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
31350   zMsg[i] = 0;
31351   sqlite3_log(errcode,
31352       "os_win.c:%d: (%d) %s(%s) - %s",
31353       iLine, lastErrno, zFunc, zPath, zMsg
31354   );
31355
31356   return errcode;
31357 }
31358
31359 /*
31360 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
31361 ** will be retried following a locking error - probably caused by 
31362 ** antivirus software.  Also the initial delay before the first retry.
31363 ** The delay increases linearly with each retry.
31364 */
31365 #ifndef SQLITE_WIN32_IOERR_RETRY
31366 # define SQLITE_WIN32_IOERR_RETRY 10
31367 #endif
31368 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
31369 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
31370 #endif
31371 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
31372 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
31373
31374 /*
31375 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
31376 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
31377 ** to give up with an error.
31378 */
31379 static int retryIoerr(int *pnRetry, DWORD *pError){
31380   DWORD e = osGetLastError();
31381   if( *pnRetry>=win32IoerrRetry ){
31382     if( pError ){
31383       *pError = e;
31384     }
31385     return 0;
31386   }
31387   if( e==ERROR_ACCESS_DENIED ||
31388       e==ERROR_LOCK_VIOLATION ||
31389       e==ERROR_SHARING_VIOLATION ){
31390     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
31391     ++*pnRetry;
31392     return 1;
31393   }
31394   if( pError ){
31395     *pError = e;
31396   }
31397   return 0;
31398 }
31399
31400 /*
31401 ** Log a I/O error retry episode.
31402 */
31403 static void logIoerr(int nRetry){
31404   if( nRetry ){
31405     sqlite3_log(SQLITE_IOERR, 
31406       "delayed %dms for lock/sharing conflict",
31407       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
31408     );
31409   }
31410 }
31411
31412 #if SQLITE_OS_WINCE
31413 /*************************************************************************
31414 ** This section contains code for WinCE only.
31415 */
31416 /*
31417 ** Windows CE does not have a localtime() function.  So create a
31418 ** substitute.
31419 */
31420 /* #include <time.h> */
31421 struct tm *__cdecl localtime(const time_t *t)
31422 {
31423   static struct tm y;
31424   FILETIME uTm, lTm;
31425   SYSTEMTIME pTm;
31426   sqlite3_int64 t64;
31427   t64 = *t;
31428   t64 = (t64 + 11644473600)*10000000;
31429   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31430   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31431   osFileTimeToLocalFileTime(&uTm,&lTm);
31432   osFileTimeToSystemTime(&lTm,&pTm);
31433   y.tm_year = pTm.wYear - 1900;
31434   y.tm_mon = pTm.wMonth - 1;
31435   y.tm_wday = pTm.wDayOfWeek;
31436   y.tm_mday = pTm.wDay;
31437   y.tm_hour = pTm.wHour;
31438   y.tm_min = pTm.wMinute;
31439   y.tm_sec = pTm.wSecond;
31440   return &y;
31441 }
31442
31443 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31444
31445 /*
31446 ** Acquire a lock on the handle h
31447 */
31448 static void winceMutexAcquire(HANDLE h){
31449    DWORD dwErr;
31450    do {
31451      dwErr = osWaitForSingleObject(h, INFINITE);
31452    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31453 }
31454 /*
31455 ** Release a lock acquired by winceMutexAcquire()
31456 */
31457 #define winceMutexRelease(h) ReleaseMutex(h)
31458
31459 /*
31460 ** Create the mutex and shared memory used for locking in the file
31461 ** descriptor pFile
31462 */
31463 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31464   LPWSTR zTok;
31465   LPWSTR zName;
31466   BOOL bInit = TRUE;
31467
31468   zName = utf8ToUnicode(zFilename);
31469   if( zName==0 ){
31470     /* out of memory */
31471     return FALSE;
31472   }
31473
31474   /* Initialize the local lockdata */
31475   memset(&pFile->local, 0, sizeof(pFile->local));
31476
31477   /* Replace the backslashes from the filename and lowercase it
31478   ** to derive a mutex name. */
31479   zTok = osCharLowerW(zName);
31480   for (;*zTok;zTok++){
31481     if (*zTok == '\\') *zTok = '_';
31482   }
31483
31484   /* Create/open the named mutex */
31485   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
31486   if (!pFile->hMutex){
31487     pFile->lastErrno = osGetLastError();
31488     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
31489     sqlite3_free(zName);
31490     return FALSE;
31491   }
31492
31493   /* Acquire the mutex before continuing */
31494   winceMutexAcquire(pFile->hMutex);
31495   
31496   /* Since the names of named mutexes, semaphores, file mappings etc are 
31497   ** case-sensitive, take advantage of that by uppercasing the mutex name
31498   ** and using that as the shared filemapping name.
31499   */
31500   osCharUpperW(zName);
31501   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31502                                         PAGE_READWRITE, 0, sizeof(winceLock),
31503                                         zName);  
31504
31505   /* Set a flag that indicates we're the first to create the memory so it 
31506   ** must be zero-initialized */
31507   if (osGetLastError() == ERROR_ALREADY_EXISTS){
31508     bInit = FALSE;
31509   }
31510
31511   sqlite3_free(zName);
31512
31513   /* If we succeeded in making the shared memory handle, map it. */
31514   if (pFile->hShared){
31515     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
31516              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31517     /* If mapping failed, close the shared memory handle and erase it */
31518     if (!pFile->shared){
31519       pFile->lastErrno = osGetLastError();
31520       winLogError(SQLITE_ERROR, pFile->lastErrno,
31521                "winceCreateLock2", zFilename);
31522       osCloseHandle(pFile->hShared);
31523       pFile->hShared = NULL;
31524     }
31525   }
31526
31527   /* If shared memory could not be created, then close the mutex and fail */
31528   if (pFile->hShared == NULL){
31529     winceMutexRelease(pFile->hMutex);
31530     osCloseHandle(pFile->hMutex);
31531     pFile->hMutex = NULL;
31532     return FALSE;
31533   }
31534   
31535   /* Initialize the shared memory if we're supposed to */
31536   if (bInit) {
31537     memset(pFile->shared, 0, sizeof(winceLock));
31538   }
31539
31540   winceMutexRelease(pFile->hMutex);
31541   return TRUE;
31542 }
31543
31544 /*
31545 ** Destroy the part of winFile that deals with wince locks
31546 */
31547 static void winceDestroyLock(winFile *pFile){
31548   if (pFile->hMutex){
31549     /* Acquire the mutex */
31550     winceMutexAcquire(pFile->hMutex);
31551
31552     /* The following blocks should probably assert in debug mode, but they
31553        are to cleanup in case any locks remained open */
31554     if (pFile->local.nReaders){
31555       pFile->shared->nReaders --;
31556     }
31557     if (pFile->local.bReserved){
31558       pFile->shared->bReserved = FALSE;
31559     }
31560     if (pFile->local.bPending){
31561       pFile->shared->bPending = FALSE;
31562     }
31563     if (pFile->local.bExclusive){
31564       pFile->shared->bExclusive = FALSE;
31565     }
31566
31567     /* De-reference and close our copy of the shared memory handle */
31568     osUnmapViewOfFile(pFile->shared);
31569     osCloseHandle(pFile->hShared);
31570
31571     /* Done with the mutex */
31572     winceMutexRelease(pFile->hMutex);    
31573     osCloseHandle(pFile->hMutex);
31574     pFile->hMutex = NULL;
31575   }
31576 }
31577
31578 /* 
31579 ** An implementation of the LockFile() API of Windows for CE
31580 */
31581 static BOOL winceLockFile(
31582   LPHANDLE phFile,
31583   DWORD dwFileOffsetLow,
31584   DWORD dwFileOffsetHigh,
31585   DWORD nNumberOfBytesToLockLow,
31586   DWORD nNumberOfBytesToLockHigh
31587 ){
31588   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31589   BOOL bReturn = FALSE;
31590
31591   UNUSED_PARAMETER(dwFileOffsetHigh);
31592   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31593
31594   if (!pFile->hMutex) return TRUE;
31595   winceMutexAcquire(pFile->hMutex);
31596
31597   /* Wanting an exclusive lock? */
31598   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31599        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31600     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31601        pFile->shared->bExclusive = TRUE;
31602        pFile->local.bExclusive = TRUE;
31603        bReturn = TRUE;
31604     }
31605   }
31606
31607   /* Want a read-only lock? */
31608   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31609            nNumberOfBytesToLockLow == 1){
31610     if (pFile->shared->bExclusive == 0){
31611       pFile->local.nReaders ++;
31612       if (pFile->local.nReaders == 1){
31613         pFile->shared->nReaders ++;
31614       }
31615       bReturn = TRUE;
31616     }
31617   }
31618
31619   /* Want a pending lock? */
31620   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31621     /* If no pending lock has been acquired, then acquire it */
31622     if (pFile->shared->bPending == 0) {
31623       pFile->shared->bPending = TRUE;
31624       pFile->local.bPending = TRUE;
31625       bReturn = TRUE;
31626     }
31627   }
31628
31629   /* Want a reserved lock? */
31630   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31631     if (pFile->shared->bReserved == 0) {
31632       pFile->shared->bReserved = TRUE;
31633       pFile->local.bReserved = TRUE;
31634       bReturn = TRUE;
31635     }
31636   }
31637
31638   winceMutexRelease(pFile->hMutex);
31639   return bReturn;
31640 }
31641
31642 /*
31643 ** An implementation of the UnlockFile API of Windows for CE
31644 */
31645 static BOOL winceUnlockFile(
31646   LPHANDLE phFile,
31647   DWORD dwFileOffsetLow,
31648   DWORD dwFileOffsetHigh,
31649   DWORD nNumberOfBytesToUnlockLow,
31650   DWORD nNumberOfBytesToUnlockHigh
31651 ){
31652   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31653   BOOL bReturn = FALSE;
31654
31655   UNUSED_PARAMETER(dwFileOffsetHigh);
31656   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31657
31658   if (!pFile->hMutex) return TRUE;
31659   winceMutexAcquire(pFile->hMutex);
31660
31661   /* Releasing a reader lock or an exclusive lock */
31662   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31663     /* Did we have an exclusive lock? */
31664     if (pFile->local.bExclusive){
31665       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31666       pFile->local.bExclusive = FALSE;
31667       pFile->shared->bExclusive = FALSE;
31668       bReturn = TRUE;
31669     }
31670
31671     /* Did we just have a reader lock? */
31672     else if (pFile->local.nReaders){
31673       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31674       pFile->local.nReaders --;
31675       if (pFile->local.nReaders == 0)
31676       {
31677         pFile->shared->nReaders --;
31678       }
31679       bReturn = TRUE;
31680     }
31681   }
31682
31683   /* Releasing a pending lock */
31684   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31685     if (pFile->local.bPending){
31686       pFile->local.bPending = FALSE;
31687       pFile->shared->bPending = FALSE;
31688       bReturn = TRUE;
31689     }
31690   }
31691   /* Releasing a reserved lock */
31692   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31693     if (pFile->local.bReserved) {
31694       pFile->local.bReserved = FALSE;
31695       pFile->shared->bReserved = FALSE;
31696       bReturn = TRUE;
31697     }
31698   }
31699
31700   winceMutexRelease(pFile->hMutex);
31701   return bReturn;
31702 }
31703 /*
31704 ** End of the special code for wince
31705 *****************************************************************************/
31706 #endif /* SQLITE_OS_WINCE */
31707
31708 /*
31709 ** Lock a file region.
31710 */
31711 static BOOL winLockFile(
31712   LPHANDLE phFile,
31713   DWORD flags,
31714   DWORD offsetLow,
31715   DWORD offsetHigh,
31716   DWORD numBytesLow,
31717   DWORD numBytesHigh
31718 ){
31719 #if SQLITE_OS_WINCE
31720   /*
31721   ** NOTE: Windows CE is handled differently here due its lack of the Win32
31722   **       API LockFile.
31723   */
31724   return winceLockFile(phFile, offsetLow, offsetHigh,
31725                        numBytesLow, numBytesHigh);
31726 #else
31727   if( isNT() ){
31728     OVERLAPPED ovlp;
31729     memset(&ovlp, 0, sizeof(OVERLAPPED));
31730     ovlp.Offset = offsetLow;
31731     ovlp.OffsetHigh = offsetHigh;
31732     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
31733   }else{
31734     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
31735                       numBytesHigh);
31736   }
31737 #endif
31738 }
31739
31740 /*
31741 ** Unlock a file region.
31742  */
31743 static BOOL winUnlockFile(
31744   LPHANDLE phFile,
31745   DWORD offsetLow,
31746   DWORD offsetHigh,
31747   DWORD numBytesLow,
31748   DWORD numBytesHigh
31749 ){
31750 #if SQLITE_OS_WINCE
31751   /*
31752   ** NOTE: Windows CE is handled differently here due its lack of the Win32
31753   **       API UnlockFile.
31754   */
31755   return winceUnlockFile(phFile, offsetLow, offsetHigh,
31756                          numBytesLow, numBytesHigh);
31757 #else
31758   if( isNT() ){
31759     OVERLAPPED ovlp;
31760     memset(&ovlp, 0, sizeof(OVERLAPPED));
31761     ovlp.Offset = offsetLow;
31762     ovlp.OffsetHigh = offsetHigh;
31763     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
31764   }else{
31765     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
31766                         numBytesHigh);
31767   }
31768 #endif
31769 }
31770
31771 /*****************************************************************************
31772 ** The next group of routines implement the I/O methods specified
31773 ** by the sqlite3_io_methods object.
31774 ******************************************************************************/
31775
31776 /*
31777 ** Some Microsoft compilers lack this definition.
31778 */
31779 #ifndef INVALID_SET_FILE_POINTER
31780 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
31781 #endif
31782
31783 /*
31784 ** Move the current position of the file handle passed as the first 
31785 ** argument to offset iOffset within the file. If successful, return 0. 
31786 ** Otherwise, set pFile->lastErrno and return non-zero.
31787 */
31788 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31789 #if !SQLITE_OS_WINRT
31790   LONG upperBits;                 /* Most sig. 32 bits of new offset */
31791   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
31792   DWORD dwRet;                    /* Value returned by SetFilePointer() */
31793   DWORD lastErrno;                /* Value returned by GetLastError() */
31794
31795   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31796   lowerBits = (LONG)(iOffset & 0xffffffff);
31797
31798   /* API oddity: If successful, SetFilePointer() returns a dword 
31799   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31800   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
31801   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
31802   ** whether an error has actually occured, it is also necessary to call 
31803   ** GetLastError().
31804   */
31805   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31806
31807   if( (dwRet==INVALID_SET_FILE_POINTER
31808       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
31809     pFile->lastErrno = lastErrno;
31810     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
31811              "seekWinFile", pFile->zPath);
31812     return 1;
31813   }
31814
31815   return 0;
31816 #else
31817   /*
31818   ** Same as above, except that this implementation works for WinRT.
31819   */
31820
31821   LARGE_INTEGER x;                /* The new offset */
31822   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
31823
31824   x.QuadPart = iOffset;
31825   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
31826
31827   if(!bRet){
31828     pFile->lastErrno = osGetLastError();
31829     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
31830              "seekWinFile", pFile->zPath);
31831     return 1;
31832   }
31833
31834   return 0;
31835 #endif
31836 }
31837
31838 /*
31839 ** Close a file.
31840 **
31841 ** It is reported that an attempt to close a handle might sometimes
31842 ** fail.  This is a very unreasonable result, but Windows is notorious
31843 ** for being unreasonable so I do not doubt that it might happen.  If
31844 ** the close fails, we pause for 100 milliseconds and try again.  As
31845 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31846 ** giving up and returning an error.
31847 */
31848 #define MX_CLOSE_ATTEMPT 3
31849 static int winClose(sqlite3_file *id){
31850   int rc, cnt = 0;
31851   winFile *pFile = (winFile*)id;
31852
31853   assert( id!=0 );
31854 #ifndef SQLITE_OMIT_WAL
31855   assert( pFile->pShm==0 );
31856 #endif
31857   OSTRACE(("CLOSE %d\n", pFile->h));
31858   do{
31859     rc = osCloseHandle(pFile->h);
31860     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31861   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
31862 #if SQLITE_OS_WINCE
31863 #define WINCE_DELETION_ATTEMPTS 3
31864   winceDestroyLock(pFile);
31865   if( pFile->zDeleteOnClose ){
31866     int cnt = 0;
31867     while(
31868            osDeleteFileW(pFile->zDeleteOnClose)==0
31869         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
31870         && cnt++ < WINCE_DELETION_ATTEMPTS
31871     ){
31872        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
31873     }
31874     sqlite3_free(pFile->zDeleteOnClose);
31875   }
31876 #endif
31877   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31878   if( rc ){
31879     pFile->h = NULL;
31880   }
31881   OpenCounter(-1);
31882   return rc ? SQLITE_OK
31883             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
31884                           "winClose", pFile->zPath);
31885 }
31886
31887 /*
31888 ** Read data from a file into a buffer.  Return SQLITE_OK if all
31889 ** bytes were read successfully and SQLITE_IOERR if anything goes
31890 ** wrong.
31891 */
31892 static int winRead(
31893   sqlite3_file *id,          /* File to read from */
31894   void *pBuf,                /* Write content into this buffer */
31895   int amt,                   /* Number of bytes to read */
31896   sqlite3_int64 offset       /* Begin reading at this offset */
31897 ){
31898 #if !SQLITE_OS_WINCE
31899   OVERLAPPED overlapped;          /* The offset for ReadFile. */
31900 #endif
31901   winFile *pFile = (winFile*)id;  /* file handle */
31902   DWORD nRead;                    /* Number of bytes actually read from file */
31903   int nRetry = 0;                 /* Number of retrys */
31904
31905   assert( id!=0 );
31906   SimulateIOError(return SQLITE_IOERR_READ);
31907   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31908
31909 #if SQLITE_OS_WINCE
31910   if( seekWinFile(pFile, offset) ){
31911     return SQLITE_FULL;
31912   }
31913   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31914 #else
31915   memset(&overlapped, 0, sizeof(OVERLAPPED));
31916   overlapped.Offset = (LONG)(offset & 0xffffffff);
31917   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
31918   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
31919          osGetLastError()!=ERROR_HANDLE_EOF ){
31920 #endif
31921     DWORD lastErrno;
31922     if( retryIoerr(&nRetry, &lastErrno) ) continue;
31923     pFile->lastErrno = lastErrno;
31924     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
31925              "winRead", pFile->zPath);
31926   }
31927   logIoerr(nRetry);
31928   if( nRead<(DWORD)amt ){
31929     /* Unread parts of the buffer must be zero-filled */
31930     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31931     return SQLITE_IOERR_SHORT_READ;
31932   }
31933
31934   return SQLITE_OK;
31935 }
31936
31937 /*
31938 ** Write data from a buffer into a file.  Return SQLITE_OK on success
31939 ** or some other error code on failure.
31940 */
31941 static int winWrite(
31942   sqlite3_file *id,               /* File to write into */
31943   const void *pBuf,               /* The bytes to be written */
31944   int amt,                        /* Number of bytes to write */
31945   sqlite3_int64 offset            /* Offset into the file to begin writing at */
31946 ){
31947   int rc = 0;                     /* True if error has occured, else false */
31948   winFile *pFile = (winFile*)id;  /* File handle */
31949   int nRetry = 0;                 /* Number of retries */
31950
31951   assert( amt>0 );
31952   assert( pFile );
31953   SimulateIOError(return SQLITE_IOERR_WRITE);
31954   SimulateDiskfullError(return SQLITE_FULL);
31955
31956   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31957
31958 #if SQLITE_OS_WINCE
31959   rc = seekWinFile(pFile, offset);
31960   if( rc==0 ){
31961 #else
31962   {
31963 #endif
31964 #if !SQLITE_OS_WINCE
31965     OVERLAPPED overlapped;        /* The offset for WriteFile. */
31966 #endif
31967     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
31968     int nRem = amt;               /* Number of bytes yet to be written */
31969     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
31970     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
31971
31972 #if !SQLITE_OS_WINCE
31973     memset(&overlapped, 0, sizeof(OVERLAPPED));
31974     overlapped.Offset = (LONG)(offset & 0xffffffff);
31975     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
31976 #endif
31977
31978     while( nRem>0 ){
31979 #if SQLITE_OS_WINCE
31980       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
31981 #else
31982       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
31983 #endif
31984         if( retryIoerr(&nRetry, &lastErrno) ) continue;
31985         break;
31986       }
31987       if( nWrite<=0 ){
31988         lastErrno = osGetLastError();
31989         break;
31990       }
31991 #if !SQLITE_OS_WINCE
31992       offset += nWrite;
31993       overlapped.Offset = (LONG)(offset & 0xffffffff);
31994       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
31995 #endif
31996       aRem += nWrite;
31997       nRem -= nWrite;
31998     }
31999     if( nRem>0 ){
32000       pFile->lastErrno = lastErrno;
32001       rc = 1;
32002     }
32003   }
32004
32005   if( rc ){
32006     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32007        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32008       return SQLITE_FULL;
32009     }
32010     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
32011              "winWrite", pFile->zPath);
32012   }else{
32013     logIoerr(nRetry);
32014   }
32015   return SQLITE_OK;
32016 }
32017
32018 /*
32019 ** Truncate an open file to a specified size
32020 */
32021 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32022   winFile *pFile = (winFile*)id;  /* File handle object */
32023   int rc = SQLITE_OK;             /* Return code for this function */
32024
32025   assert( pFile );
32026
32027   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32028   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32029
32030   /* If the user has configured a chunk-size for this file, truncate the
32031   ** file so that it consists of an integer number of chunks (i.e. the
32032   ** actual file size after the operation may be larger than the requested
32033   ** size).
32034   */
32035   if( pFile->szChunk>0 ){
32036     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32037   }
32038
32039   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32040   if( seekWinFile(pFile, nByte) ){
32041     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32042              "winTruncate1", pFile->zPath);
32043   }else if( 0==osSetEndOfFile(pFile->h) ){
32044     pFile->lastErrno = osGetLastError();
32045     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32046              "winTruncate2", pFile->zPath);
32047   }
32048
32049   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32050   return rc;
32051 }
32052
32053 #ifdef SQLITE_TEST
32054 /*
32055 ** Count the number of fullsyncs and normal syncs.  This is used to test
32056 ** that syncs and fullsyncs are occuring at the right times.
32057 */
32058 SQLITE_API int sqlite3_sync_count = 0;
32059 SQLITE_API int sqlite3_fullsync_count = 0;
32060 #endif
32061
32062 /*
32063 ** Make sure all writes to a particular file are committed to disk.
32064 */
32065 static int winSync(sqlite3_file *id, int flags){
32066 #ifndef SQLITE_NO_SYNC
32067   /*
32068   ** Used only when SQLITE_NO_SYNC is not defined.
32069    */
32070   BOOL rc;
32071 #endif
32072 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32073     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32074   /*
32075   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32076   ** OSTRACE() macros.
32077    */
32078   winFile *pFile = (winFile*)id;
32079 #else
32080   UNUSED_PARAMETER(id);
32081 #endif
32082
32083   assert( pFile );
32084   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32085   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32086       || (flags&0x0F)==SQLITE_SYNC_FULL
32087   );
32088
32089   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32090
32091   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32092   ** line is to test that doing so does not cause any problems.
32093   */
32094   SimulateDiskfullError( return SQLITE_FULL );
32095
32096 #ifndef SQLITE_TEST
32097   UNUSED_PARAMETER(flags);
32098 #else
32099   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32100     sqlite3_fullsync_count++;
32101   }
32102   sqlite3_sync_count++;
32103 #endif
32104
32105   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32106   ** no-op
32107   */
32108 #ifdef SQLITE_NO_SYNC
32109   return SQLITE_OK;
32110 #else
32111   rc = osFlushFileBuffers(pFile->h);
32112   SimulateIOError( rc=FALSE );
32113   if( rc ){
32114     return SQLITE_OK;
32115   }else{
32116     pFile->lastErrno = osGetLastError();
32117     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
32118              "winSync", pFile->zPath);
32119   }
32120 #endif
32121 }
32122
32123 /*
32124 ** Determine the current size of a file in bytes
32125 */
32126 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32127   winFile *pFile = (winFile*)id;
32128   int rc = SQLITE_OK;
32129
32130   assert( id!=0 );
32131   SimulateIOError(return SQLITE_IOERR_FSTAT);
32132 #if SQLITE_OS_WINRT
32133   {
32134     FILE_STANDARD_INFO info;
32135     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
32136                                      &info, sizeof(info)) ){
32137       *pSize = info.EndOfFile.QuadPart;
32138     }else{
32139       pFile->lastErrno = osGetLastError();
32140       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32141                        "winFileSize", pFile->zPath);
32142     }
32143   }
32144 #else
32145   {
32146     DWORD upperBits;
32147     DWORD lowerBits;
32148     DWORD lastErrno;
32149
32150     lowerBits = osGetFileSize(pFile->h, &upperBits);
32151     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32152     if(   (lowerBits == INVALID_FILE_SIZE)
32153        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
32154       pFile->lastErrno = lastErrno;
32155       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32156              "winFileSize", pFile->zPath);
32157     }
32158   }
32159 #endif
32160   return rc;
32161 }
32162
32163 /*
32164 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32165 */
32166 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32167 # define LOCKFILE_FAIL_IMMEDIATELY 1
32168 #endif
32169
32170 #ifndef LOCKFILE_EXCLUSIVE_LOCK
32171 # define LOCKFILE_EXCLUSIVE_LOCK 2
32172 #endif
32173
32174 /*
32175 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
32176 ** When the LockFile function was used, it was always expected to fail
32177 ** immediately if the lock could not be obtained.  Also, it always expected to
32178 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
32179 ** and reflect those expectations; therefore, they should not be changed.
32180 */
32181 #ifndef SQLITE_LOCKFILE_FLAGS
32182 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
32183                                   LOCKFILE_EXCLUSIVE_LOCK)
32184 #endif
32185
32186 /*
32187 ** Currently, SQLite never calls the LockFileEx function without wanting the
32188 ** call to fail immediately if the lock cannot be obtained.
32189 */
32190 #ifndef SQLITE_LOCKFILEEX_FLAGS
32191 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
32192 #endif
32193
32194 /*
32195 ** Acquire a reader lock.
32196 ** Different API routines are called depending on whether or not this
32197 ** is Win9x or WinNT.
32198 */
32199 static int getReadLock(winFile *pFile){
32200   int res;
32201   if( isNT() ){
32202 #if SQLITE_OS_WINCE
32203     /*
32204     ** NOTE: Windows CE is handled differently here due its lack of the Win32
32205     **       API LockFileEx.
32206     */
32207     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
32208 #else
32209     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
32210                       SHARED_SIZE, 0);
32211 #endif
32212   }
32213 #ifdef SQLITE_WIN32_HAS_ANSI
32214   else{
32215     int lk;
32216     sqlite3_randomness(sizeof(lk), &lk);
32217     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32218     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32219                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32220   }
32221 #endif
32222   if( res == 0 ){
32223     pFile->lastErrno = osGetLastError();
32224     /* No need to log a failure to lock */
32225   }
32226   return res;
32227 }
32228
32229 /*
32230 ** Undo a readlock
32231 */
32232 static int unlockReadLock(winFile *pFile){
32233   int res;
32234   DWORD lastErrno;
32235   if( isNT() ){
32236     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32237   }
32238 #ifdef SQLITE_WIN32_HAS_ANSI
32239   else{
32240     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32241   }
32242 #endif
32243   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
32244     pFile->lastErrno = lastErrno;
32245     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
32246              "unlockReadLock", pFile->zPath);
32247   }
32248   return res;
32249 }
32250
32251 /*
32252 ** Lock the file with the lock specified by parameter locktype - one
32253 ** of the following:
32254 **
32255 **     (1) SHARED_LOCK
32256 **     (2) RESERVED_LOCK
32257 **     (3) PENDING_LOCK
32258 **     (4) EXCLUSIVE_LOCK
32259 **
32260 ** Sometimes when requesting one lock state, additional lock states
32261 ** are inserted in between.  The locking might fail on one of the later
32262 ** transitions leaving the lock state different from what it started but
32263 ** still short of its goal.  The following chart shows the allowed
32264 ** transitions and the inserted intermediate states:
32265 **
32266 **    UNLOCKED -> SHARED
32267 **    SHARED -> RESERVED
32268 **    SHARED -> (PENDING) -> EXCLUSIVE
32269 **    RESERVED -> (PENDING) -> EXCLUSIVE
32270 **    PENDING -> EXCLUSIVE
32271 **
32272 ** This routine will only increase a lock.  The winUnlock() routine
32273 ** erases all locks at once and returns us immediately to locking level 0.
32274 ** It is not possible to lower the locking level one step at a time.  You
32275 ** must go straight to locking level 0.
32276 */
32277 static int winLock(sqlite3_file *id, int locktype){
32278   int rc = SQLITE_OK;    /* Return code from subroutines */
32279   int res = 1;           /* Result of a Windows lock call */
32280   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32281   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32282   winFile *pFile = (winFile*)id;
32283   DWORD lastErrno = NO_ERROR;
32284
32285   assert( id!=0 );
32286   OSTRACE(("LOCK %d %d was %d(%d)\n",
32287            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32288
32289   /* If there is already a lock of this type or more restrictive on the
32290   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32291   ** sqlite3OsEnterMutex() hasn't been called yet.
32292   */
32293   if( pFile->locktype>=locktype ){
32294     return SQLITE_OK;
32295   }
32296
32297   /* Make sure the locking sequence is correct
32298   */
32299   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32300   assert( locktype!=PENDING_LOCK );
32301   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32302
32303   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32304   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32305   ** the PENDING_LOCK byte is temporary.
32306   */
32307   newLocktype = pFile->locktype;
32308   if(   (pFile->locktype==NO_LOCK)
32309      || (   (locktype==EXCLUSIVE_LOCK)
32310          && (pFile->locktype==RESERVED_LOCK))
32311   ){
32312     int cnt = 3;
32313     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32314                                          PENDING_BYTE, 0, 1, 0))==0 ){
32315       /* Try 3 times to get the pending lock.  This is needed to work
32316       ** around problems caused by indexing and/or anti-virus software on
32317       ** Windows systems.
32318       ** If you are using this code as a model for alternative VFSes, do not
32319       ** copy this retry logic.  It is a hack intended for Windows only.
32320       */
32321       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32322       if( cnt ) sqlite3_win32_sleep(1);
32323     }
32324     gotPendingLock = res;
32325     if( !res ){
32326       lastErrno = osGetLastError();
32327     }
32328   }
32329
32330   /* Acquire a shared lock
32331   */
32332   if( locktype==SHARED_LOCK && res ){
32333     assert( pFile->locktype==NO_LOCK );
32334     res = getReadLock(pFile);
32335     if( res ){
32336       newLocktype = SHARED_LOCK;
32337     }else{
32338       lastErrno = osGetLastError();
32339     }
32340   }
32341
32342   /* Acquire a RESERVED lock
32343   */
32344   if( locktype==RESERVED_LOCK && res ){
32345     assert( pFile->locktype==SHARED_LOCK );
32346     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32347     if( res ){
32348       newLocktype = RESERVED_LOCK;
32349     }else{
32350       lastErrno = osGetLastError();
32351     }
32352   }
32353
32354   /* Acquire a PENDING lock
32355   */
32356   if( locktype==EXCLUSIVE_LOCK && res ){
32357     newLocktype = PENDING_LOCK;
32358     gotPendingLock = 0;
32359   }
32360
32361   /* Acquire an EXCLUSIVE lock
32362   */
32363   if( locktype==EXCLUSIVE_LOCK && res ){
32364     assert( pFile->locktype>=SHARED_LOCK );
32365     res = unlockReadLock(pFile);
32366     OSTRACE(("unreadlock = %d\n", res));
32367     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
32368                       SHARED_SIZE, 0);
32369     if( res ){
32370       newLocktype = EXCLUSIVE_LOCK;
32371     }else{
32372       lastErrno = osGetLastError();
32373       OSTRACE(("error-code = %d\n", lastErrno));
32374       getReadLock(pFile);
32375     }
32376   }
32377
32378   /* If we are holding a PENDING lock that ought to be released, then
32379   ** release it now.
32380   */
32381   if( gotPendingLock && locktype==SHARED_LOCK ){
32382     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32383   }
32384
32385   /* Update the state of the lock has held in the file descriptor then
32386   ** return the appropriate result code.
32387   */
32388   if( res ){
32389     rc = SQLITE_OK;
32390   }else{
32391     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32392            locktype, newLocktype));
32393     pFile->lastErrno = lastErrno;
32394     rc = SQLITE_BUSY;
32395   }
32396   pFile->locktype = (u8)newLocktype;
32397   return rc;
32398 }
32399
32400 /*
32401 ** This routine checks if there is a RESERVED lock held on the specified
32402 ** file by this or any other process. If such a lock is held, return
32403 ** non-zero, otherwise zero.
32404 */
32405 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32406   int rc;
32407   winFile *pFile = (winFile*)id;
32408
32409   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32410
32411   assert( id!=0 );
32412   if( pFile->locktype>=RESERVED_LOCK ){
32413     rc = 1;
32414     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32415   }else{
32416     rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32417     if( rc ){
32418       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32419     }
32420     rc = !rc;
32421     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32422   }
32423   *pResOut = rc;
32424   return SQLITE_OK;
32425 }
32426
32427 /*
32428 ** Lower the locking level on file descriptor id to locktype.  locktype
32429 ** must be either NO_LOCK or SHARED_LOCK.
32430 **
32431 ** If the locking level of the file descriptor is already at or below
32432 ** the requested locking level, this routine is a no-op.
32433 **
32434 ** It is not possible for this routine to fail if the second argument
32435 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32436 ** might return SQLITE_IOERR;
32437 */
32438 static int winUnlock(sqlite3_file *id, int locktype){
32439   int type;
32440   winFile *pFile = (winFile*)id;
32441   int rc = SQLITE_OK;
32442   assert( pFile!=0 );
32443   assert( locktype<=SHARED_LOCK );
32444   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32445           pFile->locktype, pFile->sharedLockByte));
32446   type = pFile->locktype;
32447   if( type>=EXCLUSIVE_LOCK ){
32448     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32449     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32450       /* This should never happen.  We should always be able to
32451       ** reacquire the read lock */
32452       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
32453                "winUnlock", pFile->zPath);
32454     }
32455   }
32456   if( type>=RESERVED_LOCK ){
32457     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32458   }
32459   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32460     unlockReadLock(pFile);
32461   }
32462   if( type>=PENDING_LOCK ){
32463     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32464   }
32465   pFile->locktype = (u8)locktype;
32466   return rc;
32467 }
32468
32469 /*
32470 ** If *pArg is inititially negative then this is a query.  Set *pArg to
32471 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
32472 **
32473 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
32474 */
32475 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
32476   if( *pArg<0 ){
32477     *pArg = (pFile->ctrlFlags & mask)!=0;
32478   }else if( (*pArg)==0 ){
32479     pFile->ctrlFlags &= ~mask;
32480   }else{
32481     pFile->ctrlFlags |= mask;
32482   }
32483 }
32484
32485 /*
32486 ** Control and query of the open file handle.
32487 */
32488 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32489   winFile *pFile = (winFile*)id;
32490   switch( op ){
32491     case SQLITE_FCNTL_LOCKSTATE: {
32492       *(int*)pArg = pFile->locktype;
32493       return SQLITE_OK;
32494     }
32495     case SQLITE_LAST_ERRNO: {
32496       *(int*)pArg = (int)pFile->lastErrno;
32497       return SQLITE_OK;
32498     }
32499     case SQLITE_FCNTL_CHUNK_SIZE: {
32500       pFile->szChunk = *(int *)pArg;
32501       return SQLITE_OK;
32502     }
32503     case SQLITE_FCNTL_SIZE_HINT: {
32504       if( pFile->szChunk>0 ){
32505         sqlite3_int64 oldSz;
32506         int rc = winFileSize(id, &oldSz);
32507         if( rc==SQLITE_OK ){
32508           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
32509           if( newSz>oldSz ){
32510             SimulateIOErrorBenign(1);
32511             rc = winTruncate(id, newSz);
32512             SimulateIOErrorBenign(0);
32513           }
32514         }
32515         return rc;
32516       }
32517       return SQLITE_OK;
32518     }
32519     case SQLITE_FCNTL_PERSIST_WAL: {
32520       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
32521       return SQLITE_OK;
32522     }
32523     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
32524       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
32525       return SQLITE_OK;
32526     }
32527     case SQLITE_FCNTL_VFSNAME: {
32528       *(char**)pArg = sqlite3_mprintf("win32");
32529       return SQLITE_OK;
32530     }
32531     case SQLITE_FCNTL_WIN32_AV_RETRY: {
32532       int *a = (int*)pArg;
32533       if( a[0]>0 ){
32534         win32IoerrRetry = a[0];
32535       }else{
32536         a[0] = win32IoerrRetry;
32537       }
32538       if( a[1]>0 ){
32539         win32IoerrRetryDelay = a[1];
32540       }else{
32541         a[1] = win32IoerrRetryDelay;
32542       }
32543       return SQLITE_OK;
32544     }
32545   }
32546   return SQLITE_NOTFOUND;
32547 }
32548
32549 /*
32550 ** Return the sector size in bytes of the underlying block device for
32551 ** the specified file. This is almost always 512 bytes, but may be
32552 ** larger for some devices.
32553 **
32554 ** SQLite code assumes this function cannot fail. It also assumes that
32555 ** if two files are created in the same file-system directory (i.e.
32556 ** a database and its journal file) that the sector size will be the
32557 ** same for both.
32558 */
32559 static int winSectorSize(sqlite3_file *id){
32560   (void)id;
32561   return SQLITE_DEFAULT_SECTOR_SIZE;
32562 }
32563
32564 /*
32565 ** Return a vector of device characteristics.
32566 */
32567 static int winDeviceCharacteristics(sqlite3_file *id){
32568   winFile *p = (winFile*)id;
32569   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
32570          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
32571 }
32572
32573 #ifndef SQLITE_OMIT_WAL
32574
32575 /* 
32576 ** Windows will only let you create file view mappings
32577 ** on allocation size granularity boundaries.
32578 ** During sqlite3_os_init() we do a GetSystemInfo()
32579 ** to get the granularity size.
32580 */
32581 SYSTEM_INFO winSysInfo;
32582
32583 /*
32584 ** Helper functions to obtain and relinquish the global mutex. The
32585 ** global mutex is used to protect the winLockInfo objects used by 
32586 ** this file, all of which may be shared by multiple threads.
32587 **
32588 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32589 ** is held when required. This function is only used as part of assert() 
32590 ** statements. e.g.
32591 **
32592 **   winShmEnterMutex()
32593 **     assert( winShmMutexHeld() );
32594 **   winShmLeaveMutex()
32595 */
32596 static void winShmEnterMutex(void){
32597   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32598 }
32599 static void winShmLeaveMutex(void){
32600   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32601 }
32602 #ifdef SQLITE_DEBUG
32603 static int winShmMutexHeld(void) {
32604   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32605 }
32606 #endif
32607
32608 /*
32609 ** Object used to represent a single file opened and mmapped to provide
32610 ** shared memory.  When multiple threads all reference the same
32611 ** log-summary, each thread has its own winFile object, but they all
32612 ** point to a single instance of this object.  In other words, each
32613 ** log-summary is opened only once per process.
32614 **
32615 ** winShmMutexHeld() must be true when creating or destroying
32616 ** this object or while reading or writing the following fields:
32617 **
32618 **      nRef
32619 **      pNext 
32620 **
32621 ** The following fields are read-only after the object is created:
32622 ** 
32623 **      fid
32624 **      zFilename
32625 **
32626 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32627 ** winShmMutexHeld() is true when reading or writing any other field
32628 ** in this structure.
32629 **
32630 */
32631 struct winShmNode {
32632   sqlite3_mutex *mutex;      /* Mutex to access this object */
32633   char *zFilename;           /* Name of the file */
32634   winFile hFile;             /* File handle from winOpen */
32635
32636   int szRegion;              /* Size of shared-memory regions */
32637   int nRegion;               /* Size of array apRegion */
32638   struct ShmRegion {
32639     HANDLE hMap;             /* File handle from CreateFileMapping */
32640     void *pMap;
32641   } *aRegion;
32642   DWORD lastErrno;           /* The Windows errno from the last I/O error */
32643
32644   int nRef;                  /* Number of winShm objects pointing to this */
32645   winShm *pFirst;            /* All winShm objects pointing to this */
32646   winShmNode *pNext;         /* Next in list of all winShmNode objects */
32647 #ifdef SQLITE_DEBUG
32648   u8 nextShmId;              /* Next available winShm.id value */
32649 #endif
32650 };
32651
32652 /*
32653 ** A global array of all winShmNode objects.
32654 **
32655 ** The winShmMutexHeld() must be true while reading or writing this list.
32656 */
32657 static winShmNode *winShmNodeList = 0;
32658
32659 /*
32660 ** Structure used internally by this VFS to record the state of an
32661 ** open shared memory connection.
32662 **
32663 ** The following fields are initialized when this object is created and
32664 ** are read-only thereafter:
32665 **
32666 **    winShm.pShmNode
32667 **    winShm.id
32668 **
32669 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32670 ** while accessing any read/write fields.
32671 */
32672 struct winShm {
32673   winShmNode *pShmNode;      /* The underlying winShmNode object */
32674   winShm *pNext;             /* Next winShm with the same winShmNode */
32675   u8 hasMutex;               /* True if holding the winShmNode mutex */
32676   u16 sharedMask;            /* Mask of shared locks held */
32677   u16 exclMask;              /* Mask of exclusive locks held */
32678 #ifdef SQLITE_DEBUG
32679   u8 id;                     /* Id of this connection with its winShmNode */
32680 #endif
32681 };
32682
32683 /*
32684 ** Constants used for locking
32685 */
32686 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
32687 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
32688
32689 /*
32690 ** Apply advisory locks for all n bytes beginning at ofst.
32691 */
32692 #define _SHM_UNLCK  1
32693 #define _SHM_RDLCK  2
32694 #define _SHM_WRLCK  3
32695 static int winShmSystemLock(
32696   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
32697   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32698   int ofst,             /* Offset to first byte to be locked/unlocked */
32699   int nByte             /* Number of bytes to lock or unlock */
32700 ){
32701   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
32702
32703   /* Access to the winShmNode object is serialized by the caller */
32704   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32705
32706   /* Release/Acquire the system-level lock */
32707   if( lockType==_SHM_UNLCK ){
32708     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
32709   }else{
32710     /* Initialize the locking parameters */
32711     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32712     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32713     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
32714   }
32715   
32716   if( rc!= 0 ){
32717     rc = SQLITE_OK;
32718   }else{
32719     pFile->lastErrno =  osGetLastError();
32720     rc = SQLITE_BUSY;
32721   }
32722
32723   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
32724            pFile->hFile.h,
32725            rc==SQLITE_OK ? "ok" : "failed",
32726            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32727            pFile->lastErrno));
32728
32729   return rc;
32730 }
32731
32732 /* Forward references to VFS methods */
32733 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32734 static int winDelete(sqlite3_vfs *,const char*,int);
32735
32736 /*
32737 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32738 **
32739 ** This is not a VFS shared-memory method; it is a utility function called
32740 ** by VFS shared-memory methods.
32741 */
32742 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32743   winShmNode **pp;
32744   winShmNode *p;
32745   BOOL bRc;
32746   assert( winShmMutexHeld() );
32747   pp = &winShmNodeList;
32748   while( (p = *pp)!=0 ){
32749     if( p->nRef==0 ){
32750       int i;
32751       if( p->mutex ) sqlite3_mutex_free(p->mutex);
32752       for(i=0; i<p->nRegion; i++){
32753         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
32754         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32755                  (int)osGetCurrentProcessId(), i,
32756                  bRc ? "ok" : "failed"));
32757         bRc = osCloseHandle(p->aRegion[i].hMap);
32758         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32759                  (int)osGetCurrentProcessId(), i,
32760                  bRc ? "ok" : "failed"));
32761       }
32762       if( p->hFile.h != INVALID_HANDLE_VALUE ){
32763         SimulateIOErrorBenign(1);
32764         winClose((sqlite3_file *)&p->hFile);
32765         SimulateIOErrorBenign(0);
32766       }
32767       if( deleteFlag ){
32768         SimulateIOErrorBenign(1);
32769         sqlite3BeginBenignMalloc();
32770         winDelete(pVfs, p->zFilename, 0);
32771         sqlite3EndBenignMalloc();
32772         SimulateIOErrorBenign(0);
32773       }
32774       *pp = p->pNext;
32775       sqlite3_free(p->aRegion);
32776       sqlite3_free(p);
32777     }else{
32778       pp = &p->pNext;
32779     }
32780   }
32781 }
32782
32783 /*
32784 ** Open the shared-memory area associated with database file pDbFd.
32785 **
32786 ** When opening a new shared-memory file, if no other instances of that
32787 ** file are currently open, in this process or in other processes, then
32788 ** the file must be truncated to zero length or have its header cleared.
32789 */
32790 static int winOpenSharedMemory(winFile *pDbFd){
32791   struct winShm *p;                  /* The connection to be opened */
32792   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
32793   int rc;                            /* Result code */
32794   struct winShmNode *pNew;           /* Newly allocated winShmNode */
32795   int nName;                         /* Size of zName in bytes */
32796
32797   assert( pDbFd->pShm==0 );    /* Not previously opened */
32798
32799   /* Allocate space for the new sqlite3_shm object.  Also speculatively
32800   ** allocate space for a new winShmNode and filename.
32801   */
32802   p = sqlite3_malloc( sizeof(*p) );
32803   if( p==0 ) return SQLITE_IOERR_NOMEM;
32804   memset(p, 0, sizeof(*p));
32805   nName = sqlite3Strlen30(pDbFd->zPath);
32806   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
32807   if( pNew==0 ){
32808     sqlite3_free(p);
32809     return SQLITE_IOERR_NOMEM;
32810   }
32811   memset(pNew, 0, sizeof(*pNew) + nName + 17);
32812   pNew->zFilename = (char*)&pNew[1];
32813   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32814   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
32815
32816   /* Look to see if there is an existing winShmNode that can be used.
32817   ** If no matching winShmNode currently exists, create a new one.
32818   */
32819   winShmEnterMutex();
32820   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32821     /* TBD need to come up with better match here.  Perhaps
32822     ** use FILE_ID_BOTH_DIR_INFO Structure.
32823     */
32824     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32825   }
32826   if( pShmNode ){
32827     sqlite3_free(pNew);
32828   }else{
32829     pShmNode = pNew;
32830     pNew = 0;
32831     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32832     pShmNode->pNext = winShmNodeList;
32833     winShmNodeList = pShmNode;
32834
32835     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32836     if( pShmNode->mutex==0 ){
32837       rc = SQLITE_IOERR_NOMEM;
32838       goto shm_open_err;
32839     }
32840
32841     rc = winOpen(pDbFd->pVfs,
32842                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
32843                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
32844                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32845                  0);
32846     if( SQLITE_OK!=rc ){
32847       goto shm_open_err;
32848     }
32849
32850     /* Check to see if another process is holding the dead-man switch.
32851     ** If not, truncate the file to zero length. 
32852     */
32853     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32854       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32855       if( rc!=SQLITE_OK ){
32856         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
32857                  "winOpenShm", pDbFd->zPath);
32858       }
32859     }
32860     if( rc==SQLITE_OK ){
32861       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32862       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32863     }
32864     if( rc ) goto shm_open_err;
32865   }
32866
32867   /* Make the new connection a child of the winShmNode */
32868   p->pShmNode = pShmNode;
32869 #ifdef SQLITE_DEBUG
32870   p->id = pShmNode->nextShmId++;
32871 #endif
32872   pShmNode->nRef++;
32873   pDbFd->pShm = p;
32874   winShmLeaveMutex();
32875
32876   /* The reference count on pShmNode has already been incremented under
32877   ** the cover of the winShmEnterMutex() mutex and the pointer from the
32878   ** new (struct winShm) object to the pShmNode has been set. All that is
32879   ** left to do is to link the new object into the linked list starting
32880   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
32881   ** mutex.
32882   */
32883   sqlite3_mutex_enter(pShmNode->mutex);
32884   p->pNext = pShmNode->pFirst;
32885   pShmNode->pFirst = p;
32886   sqlite3_mutex_leave(pShmNode->mutex);
32887   return SQLITE_OK;
32888
32889   /* Jump here on any error */
32890 shm_open_err:
32891   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32892   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
32893   sqlite3_free(p);
32894   sqlite3_free(pNew);
32895   winShmLeaveMutex();
32896   return rc;
32897 }
32898
32899 /*
32900 ** Close a connection to shared-memory.  Delete the underlying 
32901 ** storage if deleteFlag is true.
32902 */
32903 static int winShmUnmap(
32904   sqlite3_file *fd,          /* Database holding shared memory */
32905   int deleteFlag             /* Delete after closing if true */
32906 ){
32907   winFile *pDbFd;       /* Database holding shared-memory */
32908   winShm *p;            /* The connection to be closed */
32909   winShmNode *pShmNode; /* The underlying shared-memory file */
32910   winShm **pp;          /* For looping over sibling connections */
32911
32912   pDbFd = (winFile*)fd;
32913   p = pDbFd->pShm;
32914   if( p==0 ) return SQLITE_OK;
32915   pShmNode = p->pShmNode;
32916
32917   /* Remove connection p from the set of connections associated
32918   ** with pShmNode */
32919   sqlite3_mutex_enter(pShmNode->mutex);
32920   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32921   *pp = p->pNext;
32922
32923   /* Free the connection p */
32924   sqlite3_free(p);
32925   pDbFd->pShm = 0;
32926   sqlite3_mutex_leave(pShmNode->mutex);
32927
32928   /* If pShmNode->nRef has reached 0, then close the underlying
32929   ** shared-memory file, too */
32930   winShmEnterMutex();
32931   assert( pShmNode->nRef>0 );
32932   pShmNode->nRef--;
32933   if( pShmNode->nRef==0 ){
32934     winShmPurge(pDbFd->pVfs, deleteFlag);
32935   }
32936   winShmLeaveMutex();
32937
32938   return SQLITE_OK;
32939 }
32940
32941 /*
32942 ** Change the lock state for a shared-memory segment.
32943 */
32944 static int winShmLock(
32945   sqlite3_file *fd,          /* Database file holding the shared memory */
32946   int ofst,                  /* First lock to acquire or release */
32947   int n,                     /* Number of locks to acquire or release */
32948   int flags                  /* What to do with the lock */
32949 ){
32950   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
32951   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
32952   winShm *pX;                           /* For looping over all siblings */
32953   winShmNode *pShmNode = p->pShmNode;
32954   int rc = SQLITE_OK;                   /* Result code */
32955   u16 mask;                             /* Mask of locks to take or release */
32956
32957   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32958   assert( n>=1 );
32959   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32960        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32961        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32962        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32963   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32964
32965   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32966   assert( n>1 || mask==(1<<ofst) );
32967   sqlite3_mutex_enter(pShmNode->mutex);
32968   if( flags & SQLITE_SHM_UNLOCK ){
32969     u16 allMask = 0; /* Mask of locks held by siblings */
32970
32971     /* See if any siblings hold this same lock */
32972     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32973       if( pX==p ) continue;
32974       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32975       allMask |= pX->sharedMask;
32976     }
32977
32978     /* Unlock the system-level locks */
32979     if( (mask & allMask)==0 ){
32980       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32981     }else{
32982       rc = SQLITE_OK;
32983     }
32984
32985     /* Undo the local locks */
32986     if( rc==SQLITE_OK ){
32987       p->exclMask &= ~mask;
32988       p->sharedMask &= ~mask;
32989     } 
32990   }else if( flags & SQLITE_SHM_SHARED ){
32991     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
32992
32993     /* Find out which shared locks are already held by sibling connections.
32994     ** If any sibling already holds an exclusive lock, go ahead and return
32995     ** SQLITE_BUSY.
32996     */
32997     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32998       if( (pX->exclMask & mask)!=0 ){
32999         rc = SQLITE_BUSY;
33000         break;
33001       }
33002       allShared |= pX->sharedMask;
33003     }
33004
33005     /* Get shared locks at the system level, if necessary */
33006     if( rc==SQLITE_OK ){
33007       if( (allShared & mask)==0 ){
33008         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33009       }else{
33010         rc = SQLITE_OK;
33011       }
33012     }
33013
33014     /* Get the local shared locks */
33015     if( rc==SQLITE_OK ){
33016       p->sharedMask |= mask;
33017     }
33018   }else{
33019     /* Make sure no sibling connections hold locks that will block this
33020     ** lock.  If any do, return SQLITE_BUSY right away.
33021     */
33022     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33023       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33024         rc = SQLITE_BUSY;
33025         break;
33026       }
33027     }
33028   
33029     /* Get the exclusive locks at the system level.  Then if successful
33030     ** also mark the local connection as being locked.
33031     */
33032     if( rc==SQLITE_OK ){
33033       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33034       if( rc==SQLITE_OK ){
33035         assert( (p->sharedMask & mask)==0 );
33036         p->exclMask |= mask;
33037       }
33038     }
33039   }
33040   sqlite3_mutex_leave(pShmNode->mutex);
33041   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33042            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
33043            rc ? "failed" : "ok"));
33044   return rc;
33045 }
33046
33047 /*
33048 ** Implement a memory barrier or memory fence on shared memory.  
33049 **
33050 ** All loads and stores begun before the barrier must complete before
33051 ** any load or store begun after the barrier.
33052 */
33053 static void winShmBarrier(
33054   sqlite3_file *fd          /* Database holding the shared memory */
33055 ){
33056   UNUSED_PARAMETER(fd);
33057   /* MemoryBarrier(); // does not work -- do not know why not */
33058   winShmEnterMutex();
33059   winShmLeaveMutex();
33060 }
33061
33062 /*
33063 ** This function is called to obtain a pointer to region iRegion of the 
33064 ** shared-memory associated with the database file fd. Shared-memory regions 
33065 ** are numbered starting from zero. Each shared-memory region is szRegion 
33066 ** bytes in size.
33067 **
33068 ** If an error occurs, an error code is returned and *pp is set to NULL.
33069 **
33070 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33071 ** region has not been allocated (by any client, including one running in a
33072 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
33073 ** isWrite is non-zero and the requested shared-memory region has not yet 
33074 ** been allocated, it is allocated by this function.
33075 **
33076 ** If the shared-memory region has already been allocated or is allocated by
33077 ** this call as described above, then it is mapped into this processes 
33078 ** address space (if it is not already), *pp is set to point to the mapped 
33079 ** memory and SQLITE_OK returned.
33080 */
33081 static int winShmMap(
33082   sqlite3_file *fd,               /* Handle open on database file */
33083   int iRegion,                    /* Region to retrieve */
33084   int szRegion,                   /* Size of regions */
33085   int isWrite,                    /* True to extend file if necessary */
33086   void volatile **pp              /* OUT: Mapped memory */
33087 ){
33088   winFile *pDbFd = (winFile*)fd;
33089   winShm *p = pDbFd->pShm;
33090   winShmNode *pShmNode;
33091   int rc = SQLITE_OK;
33092
33093   if( !p ){
33094     rc = winOpenSharedMemory(pDbFd);
33095     if( rc!=SQLITE_OK ) return rc;
33096     p = pDbFd->pShm;
33097   }
33098   pShmNode = p->pShmNode;
33099
33100   sqlite3_mutex_enter(pShmNode->mutex);
33101   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33102
33103   if( pShmNode->nRegion<=iRegion ){
33104     struct ShmRegion *apNew;           /* New aRegion[] array */
33105     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33106     sqlite3_int64 sz;                  /* Current size of wal-index file */
33107
33108     pShmNode->szRegion = szRegion;
33109
33110     /* The requested region is not mapped into this processes address space.
33111     ** Check to see if it has been allocated (i.e. if the wal-index file is
33112     ** large enough to contain the requested region).
33113     */
33114     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33115     if( rc!=SQLITE_OK ){
33116       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33117                "winShmMap1", pDbFd->zPath);
33118       goto shmpage_out;
33119     }
33120
33121     if( sz<nByte ){
33122       /* The requested memory region does not exist. If isWrite is set to
33123       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33124       **
33125       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33126       ** the requested memory region.
33127       */
33128       if( !isWrite ) goto shmpage_out;
33129       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33130       if( rc!=SQLITE_OK ){
33131         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33132                  "winShmMap2", pDbFd->zPath);
33133         goto shmpage_out;
33134       }
33135     }
33136
33137     /* Map the requested memory region into this processes address space. */
33138     apNew = (struct ShmRegion *)sqlite3_realloc(
33139         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33140     );
33141     if( !apNew ){
33142       rc = SQLITE_IOERR_NOMEM;
33143       goto shmpage_out;
33144     }
33145     pShmNode->aRegion = apNew;
33146
33147     while( pShmNode->nRegion<=iRegion ){
33148       HANDLE hMap;                /* file-mapping handle */
33149       void *pMap = 0;             /* Mapped memory region */
33150      
33151 #if SQLITE_OS_WINRT
33152       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
33153           NULL, PAGE_READWRITE, nByte, NULL
33154       );
33155 #else
33156       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
33157           NULL, PAGE_READWRITE, 0, nByte, NULL
33158       );
33159 #endif
33160       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33161                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
33162                hMap ? "ok" : "failed"));
33163       if( hMap ){
33164         int iOffset = pShmNode->nRegion*szRegion;
33165         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33166 #if SQLITE_OS_WINRT
33167         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33168             iOffset - iOffsetShift, szRegion + iOffsetShift
33169         );
33170 #else
33171         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33172             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33173         );
33174 #endif
33175         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33176                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
33177                  szRegion, pMap ? "ok" : "failed"));
33178       }
33179       if( !pMap ){
33180         pShmNode->lastErrno = osGetLastError();
33181         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
33182                  "winShmMap3", pDbFd->zPath);
33183         if( hMap ) osCloseHandle(hMap);
33184         goto shmpage_out;
33185       }
33186
33187       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33188       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33189       pShmNode->nRegion++;
33190     }
33191   }
33192
33193 shmpage_out:
33194   if( pShmNode->nRegion>iRegion ){
33195     int iOffset = iRegion*szRegion;
33196     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33197     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33198     *pp = (void *)&p[iOffsetShift];
33199   }else{
33200     *pp = 0;
33201   }
33202   sqlite3_mutex_leave(pShmNode->mutex);
33203   return rc;
33204 }
33205
33206 #else
33207 # define winShmMap     0
33208 # define winShmLock    0
33209 # define winShmBarrier 0
33210 # define winShmUnmap   0
33211 #endif /* #ifndef SQLITE_OMIT_WAL */
33212
33213 /*
33214 ** Here ends the implementation of all sqlite3_file methods.
33215 **
33216 ********************** End sqlite3_file Methods *******************************
33217 ******************************************************************************/
33218
33219 /*
33220 ** This vector defines all the methods that can operate on an
33221 ** sqlite3_file for win32.
33222 */
33223 static const sqlite3_io_methods winIoMethod = {
33224   2,                              /* iVersion */
33225   winClose,                       /* xClose */
33226   winRead,                        /* xRead */
33227   winWrite,                       /* xWrite */
33228   winTruncate,                    /* xTruncate */
33229   winSync,                        /* xSync */
33230   winFileSize,                    /* xFileSize */
33231   winLock,                        /* xLock */
33232   winUnlock,                      /* xUnlock */
33233   winCheckReservedLock,           /* xCheckReservedLock */
33234   winFileControl,                 /* xFileControl */
33235   winSectorSize,                  /* xSectorSize */
33236   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33237   winShmMap,                      /* xShmMap */
33238   winShmLock,                     /* xShmLock */
33239   winShmBarrier,                  /* xShmBarrier */
33240   winShmUnmap                     /* xShmUnmap */
33241 };
33242
33243 /****************************************************************************
33244 **************************** sqlite3_vfs methods ****************************
33245 **
33246 ** This division contains the implementation of methods on the
33247 ** sqlite3_vfs object.
33248 */
33249
33250 /*
33251 ** Convert a UTF-8 filename into whatever form the underlying
33252 ** operating system wants filenames in.  Space to hold the result
33253 ** is obtained from malloc and must be freed by the calling
33254 ** function.
33255 */
33256 static void *convertUtf8Filename(const char *zFilename){
33257   void *zConverted = 0;
33258   if( isNT() ){
33259     zConverted = utf8ToUnicode(zFilename);
33260   }
33261 #ifdef SQLITE_WIN32_HAS_ANSI
33262   else{
33263     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33264   }
33265 #endif
33266   /* caller will handle out of memory */
33267   return zConverted;
33268 }
33269
33270 /*
33271 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33272 ** hold at pVfs->mxPathname characters.
33273 */
33274 static int getTempname(int nBuf, char *zBuf){
33275   static char zChars[] =
33276     "abcdefghijklmnopqrstuvwxyz"
33277     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33278     "0123456789";
33279   size_t i, j;
33280   int nTempPath;
33281   char zTempPath[MAX_PATH+2];
33282
33283   /* It's odd to simulate an io-error here, but really this is just
33284   ** using the io-error infrastructure to test that SQLite handles this
33285   ** function failing. 
33286   */
33287   SimulateIOError( return SQLITE_IOERR );
33288
33289   memset(zTempPath, 0, MAX_PATH+2);
33290
33291   if( sqlite3_temp_directory ){
33292     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33293   }
33294 #if !SQLITE_OS_WINRT
33295   else if( isNT() ){
33296     char *zMulti;
33297     WCHAR zWidePath[MAX_PATH];
33298     osGetTempPathW(MAX_PATH-30, zWidePath);
33299     zMulti = unicodeToUtf8(zWidePath);
33300     if( zMulti ){
33301       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33302       sqlite3_free(zMulti);
33303     }else{
33304       return SQLITE_IOERR_NOMEM;
33305     }
33306   }
33307 #ifdef SQLITE_WIN32_HAS_ANSI
33308   else{
33309     char *zUtf8;
33310     char zMbcsPath[MAX_PATH];
33311     osGetTempPathA(MAX_PATH-30, zMbcsPath);
33312     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33313     if( zUtf8 ){
33314       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33315       sqlite3_free(zUtf8);
33316     }else{
33317       return SQLITE_IOERR_NOMEM;
33318     }
33319   }
33320 #endif
33321 #endif
33322
33323   /* Check that the output buffer is large enough for the temporary file 
33324   ** name. If it is not, return SQLITE_ERROR.
33325   */
33326   nTempPath = sqlite3Strlen30(zTempPath);
33327
33328   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
33329     return SQLITE_ERROR;
33330   }
33331
33332   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
33333   zTempPath[i] = 0;
33334
33335   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
33336                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
33337                    zTempPath);
33338   j = sqlite3Strlen30(zBuf);
33339   sqlite3_randomness(15, &zBuf[j]);
33340   for(i=0; i<15; i++, j++){
33341     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33342   }
33343   zBuf[j] = 0;
33344   zBuf[j+1] = 0;
33345
33346   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33347   return SQLITE_OK; 
33348 }
33349
33350 /*
33351 ** Return TRUE if the named file is really a directory.  Return false if
33352 ** it is something other than a directory, or if there is any kind of memory
33353 ** allocation failure.
33354 */
33355 static int winIsDir(const void *zConverted){
33356   DWORD attr;
33357   int rc = 0;
33358   DWORD lastErrno;
33359
33360   if( isNT() ){
33361     int cnt = 0;
33362     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33363     memset(&sAttrData, 0, sizeof(sAttrData));
33364     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
33365                              GetFileExInfoStandard,
33366                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
33367     if( !rc ){
33368       return 0; /* Invalid name? */
33369     }
33370     attr = sAttrData.dwFileAttributes;
33371 #if SQLITE_OS_WINCE==0
33372   }else{
33373     attr = osGetFileAttributesA((char*)zConverted);
33374 #endif
33375   }
33376   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
33377 }
33378
33379 /*
33380 ** Open a file.
33381 */
33382 static int winOpen(
33383   sqlite3_vfs *pVfs,        /* Not used */
33384   const char *zName,        /* Name of the file (UTF-8) */
33385   sqlite3_file *id,         /* Write the SQLite file handle here */
33386   int flags,                /* Open mode flags */
33387   int *pOutFlags            /* Status return flags */
33388 ){
33389   HANDLE h;
33390   DWORD lastErrno;
33391   DWORD dwDesiredAccess;
33392   DWORD dwShareMode;
33393   DWORD dwCreationDisposition;
33394   DWORD dwFlagsAndAttributes = 0;
33395 #if SQLITE_OS_WINCE
33396   int isTemp = 0;
33397 #endif
33398   winFile *pFile = (winFile*)id;
33399   void *zConverted;              /* Filename in OS encoding */
33400   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33401   int cnt = 0;
33402
33403   /* If argument zPath is a NULL pointer, this function is required to open
33404   ** a temporary file. Use this buffer to store the file name in.
33405   */
33406   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
33407
33408   int rc = SQLITE_OK;            /* Function Return Code */
33409 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33410   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33411 #endif
33412
33413   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33414   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33415   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33416 #ifndef NDEBUG
33417   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33418 #endif
33419   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33420
33421 #ifndef NDEBUG
33422   int isOpenJournal = (isCreate && (
33423         eType==SQLITE_OPEN_MASTER_JOURNAL 
33424      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33425      || eType==SQLITE_OPEN_WAL
33426   ));
33427 #endif
33428
33429   /* Check the following statements are true: 
33430   **
33431   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33432   **   (b) if CREATE is set, then READWRITE must also be set, and
33433   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33434   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33435   */
33436   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33437   assert(isCreate==0 || isReadWrite);
33438   assert(isExclusive==0 || isCreate);
33439   assert(isDelete==0 || isCreate);
33440
33441   /* The main DB, main journal, WAL file and master journal are never 
33442   ** automatically deleted. Nor are they ever temporary files.  */
33443   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33444   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33445   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33446   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33447
33448   /* Assert that the upper layer has set one of the "file-type" flags. */
33449   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33450        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33451        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33452        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33453   );
33454
33455   assert( id!=0 );
33456   UNUSED_PARAMETER(pVfs);
33457
33458 #if SQLITE_OS_WINRT
33459   if( !sqlite3_temp_directory ){
33460     sqlite3_log(SQLITE_ERROR,
33461         "sqlite3_temp_directory variable should be set for WinRT");
33462   }
33463 #endif
33464
33465   pFile->h = INVALID_HANDLE_VALUE;
33466
33467   /* If the second argument to this function is NULL, generate a 
33468   ** temporary file name to use 
33469   */
33470   if( !zUtf8Name ){
33471     assert(isDelete && !isOpenJournal);
33472     rc = getTempname(MAX_PATH+2, zTmpname);
33473     if( rc!=SQLITE_OK ){
33474       return rc;
33475     }
33476     zUtf8Name = zTmpname;
33477   }
33478
33479   /* Database filenames are double-zero terminated if they are not
33480   ** URIs with parameters.  Hence, they can always be passed into
33481   ** sqlite3_uri_parameter().
33482   */
33483   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
33484         zUtf8Name[strlen(zUtf8Name)+1]==0 );
33485
33486   /* Convert the filename to the system encoding. */
33487   zConverted = convertUtf8Filename(zUtf8Name);
33488   if( zConverted==0 ){
33489     return SQLITE_IOERR_NOMEM;
33490   }
33491
33492   if( winIsDir(zConverted) ){
33493     sqlite3_free(zConverted);
33494     return SQLITE_CANTOPEN_ISDIR;
33495   }
33496
33497   if( isReadWrite ){
33498     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33499   }else{
33500     dwDesiredAccess = GENERIC_READ;
33501   }
33502
33503   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33504   ** created. SQLite doesn't use it to indicate "exclusive access" 
33505   ** as it is usually understood.
33506   */
33507   if( isExclusive ){
33508     /* Creates a new file, only if it does not already exist. */
33509     /* If the file exists, it fails. */
33510     dwCreationDisposition = CREATE_NEW;
33511   }else if( isCreate ){
33512     /* Open existing file, or create if it doesn't exist */
33513     dwCreationDisposition = OPEN_ALWAYS;
33514   }else{
33515     /* Opens a file, only if it exists. */
33516     dwCreationDisposition = OPEN_EXISTING;
33517   }
33518
33519   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33520
33521   if( isDelete ){
33522 #if SQLITE_OS_WINCE
33523     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33524     isTemp = 1;
33525 #else
33526     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33527                                | FILE_ATTRIBUTE_HIDDEN
33528                                | FILE_FLAG_DELETE_ON_CLOSE;
33529 #endif
33530   }else{
33531     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33532   }
33533   /* Reports from the internet are that performance is always
33534   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33535 #if SQLITE_OS_WINCE
33536   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33537 #endif
33538
33539   if( isNT() ){
33540 #if SQLITE_OS_WINRT
33541     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
33542     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
33543     extendedParameters.dwFileAttributes =
33544             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
33545     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
33546     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
33547     extendedParameters.lpSecurityAttributes = NULL;
33548     extendedParameters.hTemplateFile = NULL;
33549     while( (h = osCreateFile2((LPCWSTR)zConverted,
33550                               dwDesiredAccess,
33551                               dwShareMode,
33552                               dwCreationDisposition,
33553                               &extendedParameters))==INVALID_HANDLE_VALUE &&
33554                               retryIoerr(&cnt, &lastErrno) ){
33555                /* Noop */
33556     }
33557 #else
33558     while( (h = osCreateFileW((LPCWSTR)zConverted,
33559                               dwDesiredAccess,
33560                               dwShareMode, NULL,
33561                               dwCreationDisposition,
33562                               dwFlagsAndAttributes,
33563                               NULL))==INVALID_HANDLE_VALUE &&
33564                               retryIoerr(&cnt, &lastErrno) ){
33565                /* Noop */
33566     }
33567 #endif
33568   }
33569 #ifdef SQLITE_WIN32_HAS_ANSI
33570   else{
33571     while( (h = osCreateFileA((LPCSTR)zConverted,
33572                               dwDesiredAccess,
33573                               dwShareMode, NULL,
33574                               dwCreationDisposition,
33575                               dwFlagsAndAttributes,
33576                               NULL))==INVALID_HANDLE_VALUE &&
33577                               retryIoerr(&cnt, &lastErrno) ){
33578                /* Noop */
33579     }
33580   }
33581 #endif
33582   logIoerr(cnt);
33583
33584   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33585            h, zName, dwDesiredAccess, 
33586            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33587
33588   if( h==INVALID_HANDLE_VALUE ){
33589     pFile->lastErrno = lastErrno;
33590     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
33591     sqlite3_free(zConverted);
33592     if( isReadWrite && !isExclusive ){
33593       return winOpen(pVfs, zName, id, 
33594              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33595     }else{
33596       return SQLITE_CANTOPEN_BKPT;
33597     }
33598   }
33599
33600   if( pOutFlags ){
33601     if( isReadWrite ){
33602       *pOutFlags = SQLITE_OPEN_READWRITE;
33603     }else{
33604       *pOutFlags = SQLITE_OPEN_READONLY;
33605     }
33606   }
33607
33608   memset(pFile, 0, sizeof(*pFile));
33609   pFile->pMethod = &winIoMethod;
33610   pFile->h = h;
33611   pFile->lastErrno = NO_ERROR;
33612   pFile->pVfs = pVfs;
33613 #ifndef SQLITE_OMIT_WAL
33614   pFile->pShm = 0;
33615 #endif
33616   pFile->zPath = zName;
33617   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
33618     pFile->ctrlFlags |= WINFILE_PSOW;
33619   }
33620
33621 #if SQLITE_OS_WINCE
33622   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33623        && !winceCreateLock(zName, pFile)
33624   ){
33625     osCloseHandle(h);
33626     sqlite3_free(zConverted);
33627     return SQLITE_CANTOPEN_BKPT;
33628   }
33629   if( isTemp ){
33630     pFile->zDeleteOnClose = zConverted;
33631   }else
33632 #endif
33633   {
33634     sqlite3_free(zConverted);
33635   }
33636
33637   OpenCounter(+1);
33638   return rc;
33639 }
33640
33641 /*
33642 ** Delete the named file.
33643 **
33644 ** Note that Windows does not allow a file to be deleted if some other
33645 ** process has it open.  Sometimes a virus scanner or indexing program
33646 ** will open a journal file shortly after it is created in order to do
33647 ** whatever it does.  While this other process is holding the
33648 ** file open, we will be unable to delete it.  To work around this
33649 ** problem, we delay 100 milliseconds and try to delete again.  Up
33650 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33651 ** up and returning an error.
33652 */
33653 static int winDelete(
33654   sqlite3_vfs *pVfs,          /* Not used on win32 */
33655   const char *zFilename,      /* Name of file to delete */
33656   int syncDir                 /* Not used on win32 */
33657 ){
33658   int cnt = 0;
33659   int rc;
33660   DWORD attr;
33661   DWORD lastErrno;
33662   void *zConverted;
33663   UNUSED_PARAMETER(pVfs);
33664   UNUSED_PARAMETER(syncDir);
33665
33666   SimulateIOError(return SQLITE_IOERR_DELETE);
33667   zConverted = convertUtf8Filename(zFilename);
33668   if( zConverted==0 ){
33669     return SQLITE_IOERR_NOMEM;
33670   }
33671   if( isNT() ){
33672     do {
33673 #if SQLITE_OS_WINRT
33674       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33675       memset(&sAttrData, 0, sizeof(sAttrData));
33676       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
33677                                   &sAttrData) ){
33678         attr = sAttrData.dwFileAttributes;
33679       }else{
33680         rc = SQLITE_OK; /* Already gone? */
33681         break;
33682       }
33683 #else
33684       attr = osGetFileAttributesW(zConverted);
33685 #endif
33686       if ( attr==INVALID_FILE_ATTRIBUTES ){
33687         rc = SQLITE_OK; /* Already gone? */
33688         break;
33689       }
33690       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
33691         rc = SQLITE_ERROR; /* Files only. */
33692         break;
33693       }
33694       if ( osDeleteFileW(zConverted) ){
33695         rc = SQLITE_OK; /* Deleted OK. */
33696         break;
33697       }
33698       if ( !retryIoerr(&cnt, &lastErrno) ){
33699         rc = SQLITE_ERROR; /* No more retries. */
33700         break;
33701       }
33702     } while(1);
33703   }
33704 #ifdef SQLITE_WIN32_HAS_ANSI
33705   else{
33706     do {
33707       attr = osGetFileAttributesA(zConverted);
33708       if ( attr==INVALID_FILE_ATTRIBUTES ){
33709         rc = SQLITE_OK; /* Already gone? */
33710         break;
33711       }
33712       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
33713         rc = SQLITE_ERROR; /* Files only. */
33714         break;
33715       }
33716       if ( osDeleteFileA(zConverted) ){
33717         rc = SQLITE_OK; /* Deleted OK. */
33718         break;
33719       }
33720       if ( !retryIoerr(&cnt, &lastErrno) ){
33721         rc = SQLITE_ERROR; /* No more retries. */
33722         break;
33723       }
33724     } while(1);
33725   }
33726 #endif
33727   if( rc ){
33728     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
33729              "winDelete", zFilename);
33730   }else{
33731     logIoerr(cnt);
33732   }
33733   sqlite3_free(zConverted);
33734   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
33735   return rc;
33736 }
33737
33738 /*
33739 ** Check the existance and status of a file.
33740 */
33741 static int winAccess(
33742   sqlite3_vfs *pVfs,         /* Not used on win32 */
33743   const char *zFilename,     /* Name of file to check */
33744   int flags,                 /* Type of test to make on this file */
33745   int *pResOut               /* OUT: Result */
33746 ){
33747   DWORD attr;
33748   int rc = 0;
33749   DWORD lastErrno;
33750   void *zConverted;
33751   UNUSED_PARAMETER(pVfs);
33752
33753   SimulateIOError( return SQLITE_IOERR_ACCESS; );
33754   zConverted = convertUtf8Filename(zFilename);
33755   if( zConverted==0 ){
33756     return SQLITE_IOERR_NOMEM;
33757   }
33758   if( isNT() ){
33759     int cnt = 0;
33760     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33761     memset(&sAttrData, 0, sizeof(sAttrData));
33762     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
33763                              GetFileExInfoStandard, 
33764                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
33765     if( rc ){
33766       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33767       ** as if it does not exist.
33768       */
33769       if(    flags==SQLITE_ACCESS_EXISTS
33770           && sAttrData.nFileSizeHigh==0 
33771           && sAttrData.nFileSizeLow==0 ){
33772         attr = INVALID_FILE_ATTRIBUTES;
33773       }else{
33774         attr = sAttrData.dwFileAttributes;
33775       }
33776     }else{
33777       logIoerr(cnt);
33778       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
33779         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
33780         sqlite3_free(zConverted);
33781         return SQLITE_IOERR_ACCESS;
33782       }else{
33783         attr = INVALID_FILE_ATTRIBUTES;
33784       }
33785     }
33786   }
33787 #ifdef SQLITE_WIN32_HAS_ANSI
33788   else{
33789     attr = osGetFileAttributesA((char*)zConverted);
33790   }
33791 #endif
33792   sqlite3_free(zConverted);
33793   switch( flags ){
33794     case SQLITE_ACCESS_READ:
33795     case SQLITE_ACCESS_EXISTS:
33796       rc = attr!=INVALID_FILE_ATTRIBUTES;
33797       break;
33798     case SQLITE_ACCESS_READWRITE:
33799       rc = attr!=INVALID_FILE_ATTRIBUTES &&
33800              (attr & FILE_ATTRIBUTE_READONLY)==0;
33801       break;
33802     default:
33803       assert(!"Invalid flags argument");
33804   }
33805   *pResOut = rc;
33806   return SQLITE_OK;
33807 }
33808
33809
33810 /*
33811 ** Returns non-zero if the specified path name should be used verbatim.  If
33812 ** non-zero is returned from this function, the calling function must simply
33813 ** use the provided path name verbatim -OR- resolve it into a full path name
33814 ** using the GetFullPathName Win32 API function (if available).
33815 */
33816 static BOOL winIsVerbatimPathname(
33817   const char *zPathname
33818 ){
33819   /*
33820   ** If the path name starts with a forward slash or a backslash, it is either
33821   ** a legal UNC name, a volume relative path, or an absolute path name in the
33822   ** "Unix" format on Windows.  There is no easy way to differentiate between
33823   ** the final two cases; therefore, we return the safer return value of TRUE
33824   ** so that callers of this function will simply use it verbatim.
33825   */
33826   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
33827     return TRUE;
33828   }
33829
33830   /*
33831   ** If the path name starts with a letter and a colon it is either a volume
33832   ** relative path or an absolute path.  Callers of this function must not
33833   ** attempt to treat it as a relative path name (i.e. they should simply use
33834   ** it verbatim).
33835   */
33836   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
33837     return TRUE;
33838   }
33839
33840   /*
33841   ** If we get to this point, the path name should almost certainly be a purely
33842   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
33843   */
33844   return FALSE;
33845 }
33846
33847 /*
33848 ** Turn a relative pathname into a full pathname.  Write the full
33849 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
33850 ** bytes in size.
33851 */
33852 static int winFullPathname(
33853   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
33854   const char *zRelative,        /* Possibly relative input path */
33855   int nFull,                    /* Size of output buffer in bytes */
33856   char *zFull                   /* Output buffer */
33857 ){
33858   
33859 #if defined(__CYGWIN__)
33860   SimulateIOError( return SQLITE_ERROR );
33861   UNUSED_PARAMETER(nFull);
33862   assert( pVfs->mxPathname>=MAX_PATH );
33863   assert( nFull>=pVfs->mxPathname );
33864   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
33865     /*
33866     ** NOTE: We are dealing with a relative path name and the data
33867     **       directory has been set.  Therefore, use it as the basis
33868     **       for converting the relative path name to an absolute
33869     **       one by prepending the data directory and a slash.
33870     */
33871     char zOut[MAX_PATH+1];
33872     memset(zOut, 0, MAX_PATH+1);
33873     cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */
33874     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
33875                      sqlite3_data_directory, zOut);
33876   }else{
33877     /*
33878     ** NOTE: The Cygwin docs state that the maximum length needed
33879     **       for the buffer passed to cygwin_conv_to_full_win32_path
33880     **       is MAX_PATH.
33881     */
33882     cygwin_conv_to_full_win32_path(zRelative, zFull);
33883   }
33884   return SQLITE_OK;
33885 #endif
33886
33887 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
33888   SimulateIOError( return SQLITE_ERROR );
33889   /* WinCE has no concept of a relative pathname, or so I am told. */
33890   /* WinRT has no way to convert a relative path to an absolute one. */
33891   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
33892     /*
33893     ** NOTE: We are dealing with a relative path name and the data
33894     **       directory has been set.  Therefore, use it as the basis
33895     **       for converting the relative path name to an absolute
33896     **       one by prepending the data directory and a backslash.
33897     */
33898     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
33899                      sqlite3_data_directory, zRelative);
33900   }else{
33901     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
33902   }
33903   return SQLITE_OK;
33904 #endif
33905
33906 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
33907   int nByte;
33908   void *zConverted;
33909   char *zOut;
33910
33911   /* If this path name begins with "/X:", where "X" is any alphabetic
33912   ** character, discard the initial "/" from the pathname.
33913   */
33914   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
33915     zRelative++;
33916   }
33917
33918   /* It's odd to simulate an io-error here, but really this is just
33919   ** using the io-error infrastructure to test that SQLite handles this
33920   ** function failing. This function could fail if, for example, the
33921   ** current working directory has been unlinked.
33922   */
33923   SimulateIOError( return SQLITE_ERROR );
33924   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
33925     /*
33926     ** NOTE: We are dealing with a relative path name and the data
33927     **       directory has been set.  Therefore, use it as the basis
33928     **       for converting the relative path name to an absolute
33929     **       one by prepending the data directory and a backslash.
33930     */
33931     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
33932                      sqlite3_data_directory, zRelative);
33933     return SQLITE_OK;
33934   }
33935   zConverted = convertUtf8Filename(zRelative);
33936   if( zConverted==0 ){
33937     return SQLITE_IOERR_NOMEM;
33938   }
33939   if( isNT() ){
33940     LPWSTR zTemp;
33941     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
33942     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
33943     if( zTemp==0 ){
33944       sqlite3_free(zConverted);
33945       return SQLITE_IOERR_NOMEM;
33946     }
33947     osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
33948     sqlite3_free(zConverted);
33949     zOut = unicodeToUtf8(zTemp);
33950     sqlite3_free(zTemp);
33951   }
33952 #ifdef SQLITE_WIN32_HAS_ANSI
33953   else{
33954     char *zTemp;
33955     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33956     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
33957     if( zTemp==0 ){
33958       sqlite3_free(zConverted);
33959       return SQLITE_IOERR_NOMEM;
33960     }
33961     osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33962     sqlite3_free(zConverted);
33963     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33964     sqlite3_free(zTemp);
33965   }
33966 #endif
33967   if( zOut ){
33968     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
33969     sqlite3_free(zOut);
33970     return SQLITE_OK;
33971   }else{
33972     return SQLITE_IOERR_NOMEM;
33973   }
33974 #endif
33975 }
33976
33977 #ifndef SQLITE_OMIT_LOAD_EXTENSION
33978 /*
33979 ** Interfaces for opening a shared library, finding entry points
33980 ** within the shared library, and closing the shared library.
33981 */
33982 /*
33983 ** Interfaces for opening a shared library, finding entry points
33984 ** within the shared library, and closing the shared library.
33985 */
33986 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33987   HANDLE h;
33988   void *zConverted = convertUtf8Filename(zFilename);
33989   UNUSED_PARAMETER(pVfs);
33990   if( zConverted==0 ){
33991     return 0;
33992   }
33993   if( isNT() ){
33994 #if SQLITE_OS_WINRT
33995     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
33996 #else
33997     h = osLoadLibraryW((LPCWSTR)zConverted);
33998 #endif
33999   }
34000 #ifdef SQLITE_WIN32_HAS_ANSI
34001   else{
34002     h = osLoadLibraryA((char*)zConverted);
34003   }
34004 #endif
34005   sqlite3_free(zConverted);
34006   return (void*)h;
34007 }
34008 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34009   UNUSED_PARAMETER(pVfs);
34010   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
34011 }
34012 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
34013   UNUSED_PARAMETER(pVfs);
34014   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
34015 }
34016 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34017   UNUSED_PARAMETER(pVfs);
34018   osFreeLibrary((HANDLE)pHandle);
34019 }
34020 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34021   #define winDlOpen  0
34022   #define winDlError 0
34023   #define winDlSym   0
34024   #define winDlClose 0
34025 #endif
34026
34027
34028 /*
34029 ** Write up to nBuf bytes of randomness into zBuf.
34030 */
34031 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34032   int n = 0;
34033   UNUSED_PARAMETER(pVfs);
34034 #if defined(SQLITE_TEST)
34035   n = nBuf;
34036   memset(zBuf, 0, nBuf);
34037 #else
34038   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34039     SYSTEMTIME x;
34040     osGetSystemTime(&x);
34041     memcpy(&zBuf[n], &x, sizeof(x));
34042     n += sizeof(x);
34043   }
34044   if( sizeof(DWORD)<=nBuf-n ){
34045     DWORD pid = osGetCurrentProcessId();
34046     memcpy(&zBuf[n], &pid, sizeof(pid));
34047     n += sizeof(pid);
34048   }
34049 #if SQLITE_OS_WINRT
34050   if( sizeof(ULONGLONG)<=nBuf-n ){
34051     ULONGLONG cnt = osGetTickCount64();
34052     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34053     n += sizeof(cnt);
34054   }
34055 #else
34056   if( sizeof(DWORD)<=nBuf-n ){
34057     DWORD cnt = osGetTickCount();
34058     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34059     n += sizeof(cnt);
34060   }
34061 #endif
34062   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34063     LARGE_INTEGER i;
34064     osQueryPerformanceCounter(&i);
34065     memcpy(&zBuf[n], &i, sizeof(i));
34066     n += sizeof(i);
34067   }
34068 #endif
34069   return n;
34070 }
34071
34072
34073 /*
34074 ** Sleep for a little while.  Return the amount of time slept.
34075 */
34076 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34077   sqlite3_win32_sleep((microsec+999)/1000);
34078   UNUSED_PARAMETER(pVfs);
34079   return ((microsec+999)/1000)*1000;
34080 }
34081
34082 /*
34083 ** The following variable, if set to a non-zero value, is interpreted as
34084 ** the number of seconds since 1970 and is used to set the result of
34085 ** sqlite3OsCurrentTime() during testing.
34086 */
34087 #ifdef SQLITE_TEST
34088 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34089 #endif
34090
34091 /*
34092 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34093 ** the current time and date as a Julian Day number times 86_400_000.  In
34094 ** other words, write into *piNow the number of milliseconds since the Julian
34095 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34096 ** proleptic Gregorian calendar.
34097 **
34098 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
34099 ** cannot be found.
34100 */
34101 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34102   /* FILETIME structure is a 64-bit value representing the number of 
34103      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
34104   */
34105   FILETIME ft;
34106   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34107 #ifdef SQLITE_TEST
34108   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34109 #endif
34110   /* 2^32 - to avoid use of LL and warnings in gcc */
34111   static const sqlite3_int64 max32BitValue = 
34112       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
34113
34114 #if SQLITE_OS_WINCE
34115   SYSTEMTIME time;
34116   osGetSystemTime(&time);
34117   /* if SystemTimeToFileTime() fails, it returns zero. */
34118   if (!osSystemTimeToFileTime(&time,&ft)){
34119     return SQLITE_ERROR;
34120   }
34121 #else
34122   osGetSystemTimeAsFileTime( &ft );
34123 #endif
34124
34125   *piNow = winFiletimeEpoch +
34126             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
34127                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34128
34129 #ifdef SQLITE_TEST
34130   if( sqlite3_current_time ){
34131     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34132   }
34133 #endif
34134   UNUSED_PARAMETER(pVfs);
34135   return SQLITE_OK;
34136 }
34137
34138 /*
34139 ** Find the current time (in Universal Coordinated Time).  Write the
34140 ** current time and date as a Julian Day number into *prNow and
34141 ** return 0.  Return 1 if the time and date cannot be found.
34142 */
34143 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34144   int rc;
34145   sqlite3_int64 i;
34146   rc = winCurrentTimeInt64(pVfs, &i);
34147   if( !rc ){
34148     *prNow = i/86400000.0;
34149   }
34150   return rc;
34151 }
34152
34153 /*
34154 ** The idea is that this function works like a combination of
34155 ** GetLastError() and FormatMessage() on Windows (or errno and
34156 ** strerror_r() on Unix). After an error is returned by an OS
34157 ** function, SQLite calls this function with zBuf pointing to
34158 ** a buffer of nBuf bytes. The OS layer should populate the
34159 ** buffer with a nul-terminated UTF-8 encoded error message
34160 ** describing the last IO error to have occurred within the calling
34161 ** thread.
34162 **
34163 ** If the error message is too large for the supplied buffer,
34164 ** it should be truncated. The return value of xGetLastError
34165 ** is zero if the error message fits in the buffer, or non-zero
34166 ** otherwise (if the message was truncated). If non-zero is returned,
34167 ** then it is not necessary to include the nul-terminator character
34168 ** in the output buffer.
34169 **
34170 ** Not supplying an error message will have no adverse effect
34171 ** on SQLite. It is fine to have an implementation that never
34172 ** returns an error message:
34173 **
34174 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34175 **     assert(zBuf[0]=='\0');
34176 **     return 0;
34177 **   }
34178 **
34179 ** However if an error message is supplied, it will be incorporated
34180 ** by sqlite into the error message available to the user using
34181 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34182 */
34183 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34184   UNUSED_PARAMETER(pVfs);
34185   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
34186 }
34187
34188 /*
34189 ** Initialize and deinitialize the operating system interface.
34190 */
34191 SQLITE_API int sqlite3_os_init(void){
34192   static sqlite3_vfs winVfs = {
34193     3,                   /* iVersion */
34194     sizeof(winFile),     /* szOsFile */
34195     MAX_PATH,            /* mxPathname */
34196     0,                   /* pNext */
34197     "win32",             /* zName */
34198     0,                   /* pAppData */
34199     winOpen,             /* xOpen */
34200     winDelete,           /* xDelete */
34201     winAccess,           /* xAccess */
34202     winFullPathname,     /* xFullPathname */
34203     winDlOpen,           /* xDlOpen */
34204     winDlError,          /* xDlError */
34205     winDlSym,            /* xDlSym */
34206     winDlClose,          /* xDlClose */
34207     winRandomness,       /* xRandomness */
34208     winSleep,            /* xSleep */
34209     winCurrentTime,      /* xCurrentTime */
34210     winGetLastError,     /* xGetLastError */
34211     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34212     winSetSystemCall,    /* xSetSystemCall */
34213     winGetSystemCall,    /* xGetSystemCall */
34214     winNextSystemCall,   /* xNextSystemCall */
34215   };
34216
34217   /* Double-check that the aSyscall[] array has been constructed
34218   ** correctly.  See ticket [bb3a86e890c8e96ab] */
34219   assert( ArraySize(aSyscall)==73 );
34220
34221 #ifndef SQLITE_OMIT_WAL
34222   /* get memory map allocation granularity */
34223   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34224 #if SQLITE_OS_WINRT
34225   osGetNativeSystemInfo(&winSysInfo);
34226 #else
34227   osGetSystemInfo(&winSysInfo);
34228 #endif
34229   assert(winSysInfo.dwAllocationGranularity > 0);
34230 #endif
34231
34232   sqlite3_vfs_register(&winVfs, 1);
34233   return SQLITE_OK; 
34234 }
34235
34236 SQLITE_API int sqlite3_os_end(void){ 
34237 #if SQLITE_OS_WINRT
34238   if( sleepObj != NULL ){
34239     osCloseHandle(sleepObj);
34240     sleepObj = NULL;
34241   }
34242 #endif
34243   return SQLITE_OK;
34244 }
34245
34246 #endif /* SQLITE_OS_WIN */
34247
34248 /************** End of os_win.c **********************************************/
34249 /************** Begin file bitvec.c ******************************************/
34250 /*
34251 ** 2008 February 16
34252 **
34253 ** The author disclaims copyright to this source code.  In place of
34254 ** a legal notice, here is a blessing:
34255 **
34256 **    May you do good and not evil.
34257 **    May you find forgiveness for yourself and forgive others.
34258 **    May you share freely, never taking more than you give.
34259 **
34260 *************************************************************************
34261 ** This file implements an object that represents a fixed-length
34262 ** bitmap.  Bits are numbered starting with 1.
34263 **
34264 ** A bitmap is used to record which pages of a database file have been
34265 ** journalled during a transaction, or which pages have the "dont-write"
34266 ** property.  Usually only a few pages are meet either condition.
34267 ** So the bitmap is usually sparse and has low cardinality.
34268 ** But sometimes (for example when during a DROP of a large table) most
34269 ** or all of the pages in a database can get journalled.  In those cases, 
34270 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
34271 ** to handle both cases well.
34272 **
34273 ** The size of the bitmap is fixed when the object is created.
34274 **
34275 ** All bits are clear when the bitmap is created.  Individual bits
34276 ** may be set or cleared one at a time.
34277 **
34278 ** Test operations are about 100 times more common that set operations.
34279 ** Clear operations are exceedingly rare.  There are usually between
34280 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34281 ** sometimes grow into tens of thousands or larger.  The size of the
34282 ** Bitvec object is the number of pages in the database file at the
34283 ** start of a transaction, and is thus usually less than a few thousand,
34284 ** but can be as large as 2 billion for a really big database.
34285 */
34286
34287 /* Size of the Bitvec structure in bytes. */
34288 #define BITVEC_SZ        512
34289
34290 /* Round the union size down to the nearest pointer boundary, since that's how 
34291 ** it will be aligned within the Bitvec struct. */
34292 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34293
34294 /* Type of the array "element" for the bitmap representation. 
34295 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
34296 ** Setting this to the "natural word" size of your CPU may improve
34297 ** performance. */
34298 #define BITVEC_TELEM     u8
34299 /* Size, in bits, of the bitmap element. */
34300 #define BITVEC_SZELEM    8
34301 /* Number of elements in a bitmap array. */
34302 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34303 /* Number of bits in the bitmap array. */
34304 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34305
34306 /* Number of u32 values in hash table. */
34307 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34308 /* Maximum number of entries in hash table before 
34309 ** sub-dividing and re-hashing. */
34310 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34311 /* Hashing function for the aHash representation.
34312 ** Empirical testing showed that the *37 multiplier 
34313 ** (an arbitrary prime)in the hash function provided 
34314 ** no fewer collisions than the no-op *1. */
34315 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34316
34317 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34318
34319
34320 /*
34321 ** A bitmap is an instance of the following structure.
34322 **
34323 ** This bitmap records the existance of zero or more bits
34324 ** with values between 1 and iSize, inclusive.
34325 **
34326 ** There are three possible representations of the bitmap.
34327 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34328 ** bitmap.  The least significant bit is bit 1.
34329 **
34330 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34331 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34332 **
34333 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34334 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34335 ** handles up to iDivisor separate values of i.  apSub[0] holds
34336 ** values between 1 and iDivisor.  apSub[1] holds values between
34337 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34338 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34339 ** to hold deal with values between 1 and iDivisor.
34340 */
34341 struct Bitvec {
34342   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34343   u32 nSet;       /* Number of bits that are set - only valid for aHash
34344                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34345                   ** this would be 125. */
34346   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34347                   /* Should >=0 for apSub element. */
34348                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34349                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34350   union {
34351     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34352     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34353     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34354   } u;
34355 };
34356
34357 /*
34358 ** Create a new bitmap object able to handle bits between 0 and iSize,
34359 ** inclusive.  Return a pointer to the new object.  Return NULL if 
34360 ** malloc fails.
34361 */
34362 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34363   Bitvec *p;
34364   assert( sizeof(*p)==BITVEC_SZ );
34365   p = sqlite3MallocZero( sizeof(*p) );
34366   if( p ){
34367     p->iSize = iSize;
34368   }
34369   return p;
34370 }
34371
34372 /*
34373 ** Check to see if the i-th bit is set.  Return true or false.
34374 ** If p is NULL (if the bitmap has not been created) or if
34375 ** i is out of range, then return false.
34376 */
34377 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34378   if( p==0 ) return 0;
34379   if( i>p->iSize || i==0 ) return 0;
34380   i--;
34381   while( p->iDivisor ){
34382     u32 bin = i/p->iDivisor;
34383     i = i%p->iDivisor;
34384     p = p->u.apSub[bin];
34385     if (!p) {
34386       return 0;
34387     }
34388   }
34389   if( p->iSize<=BITVEC_NBIT ){
34390     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34391   } else{
34392     u32 h = BITVEC_HASH(i++);
34393     while( p->u.aHash[h] ){
34394       if( p->u.aHash[h]==i ) return 1;
34395       h = (h+1) % BITVEC_NINT;
34396     }
34397     return 0;
34398   }
34399 }
34400
34401 /*
34402 ** Set the i-th bit.  Return 0 on success and an error code if
34403 ** anything goes wrong.
34404 **
34405 ** This routine might cause sub-bitmaps to be allocated.  Failing
34406 ** to get the memory needed to hold the sub-bitmap is the only
34407 ** that can go wrong with an insert, assuming p and i are valid.
34408 **
34409 ** The calling function must ensure that p is a valid Bitvec object
34410 ** and that the value for "i" is within range of the Bitvec object.
34411 ** Otherwise the behavior is undefined.
34412 */
34413 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34414   u32 h;
34415   if( p==0 ) return SQLITE_OK;
34416   assert( i>0 );
34417   assert( i<=p->iSize );
34418   i--;
34419   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34420     u32 bin = i/p->iDivisor;
34421     i = i%p->iDivisor;
34422     if( p->u.apSub[bin]==0 ){
34423       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34424       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34425     }
34426     p = p->u.apSub[bin];
34427   }
34428   if( p->iSize<=BITVEC_NBIT ){
34429     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34430     return SQLITE_OK;
34431   }
34432   h = BITVEC_HASH(i++);
34433   /* if there wasn't a hash collision, and this doesn't */
34434   /* completely fill the hash, then just add it without */
34435   /* worring about sub-dividing and re-hashing. */
34436   if( !p->u.aHash[h] ){
34437     if (p->nSet<(BITVEC_NINT-1)) {
34438       goto bitvec_set_end;
34439     } else {
34440       goto bitvec_set_rehash;
34441     }
34442   }
34443   /* there was a collision, check to see if it's already */
34444   /* in hash, if not, try to find a spot for it */
34445   do {
34446     if( p->u.aHash[h]==i ) return SQLITE_OK;
34447     h++;
34448     if( h>=BITVEC_NINT ) h = 0;
34449   } while( p->u.aHash[h] );
34450   /* we didn't find it in the hash.  h points to the first */
34451   /* available free spot. check to see if this is going to */
34452   /* make our hash too "full".  */
34453 bitvec_set_rehash:
34454   if( p->nSet>=BITVEC_MXHASH ){
34455     unsigned int j;
34456     int rc;
34457     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34458     if( aiValues==0 ){
34459       return SQLITE_NOMEM;
34460     }else{
34461       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34462       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34463       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34464       rc = sqlite3BitvecSet(p, i);
34465       for(j=0; j<BITVEC_NINT; j++){
34466         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34467       }
34468       sqlite3StackFree(0, aiValues);
34469       return rc;
34470     }
34471   }
34472 bitvec_set_end:
34473   p->nSet++;
34474   p->u.aHash[h] = i;
34475   return SQLITE_OK;
34476 }
34477
34478 /*
34479 ** Clear the i-th bit.
34480 **
34481 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34482 ** that BitvecClear can use to rebuilt its hash table.
34483 */
34484 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34485   if( p==0 ) return;
34486   assert( i>0 );
34487   i--;
34488   while( p->iDivisor ){
34489     u32 bin = i/p->iDivisor;
34490     i = i%p->iDivisor;
34491     p = p->u.apSub[bin];
34492     if (!p) {
34493       return;
34494     }
34495   }
34496   if( p->iSize<=BITVEC_NBIT ){
34497     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34498   }else{
34499     unsigned int j;
34500     u32 *aiValues = pBuf;
34501     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34502     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34503     p->nSet = 0;
34504     for(j=0; j<BITVEC_NINT; j++){
34505       if( aiValues[j] && aiValues[j]!=(i+1) ){
34506         u32 h = BITVEC_HASH(aiValues[j]-1);
34507         p->nSet++;
34508         while( p->u.aHash[h] ){
34509           h++;
34510           if( h>=BITVEC_NINT ) h = 0;
34511         }
34512         p->u.aHash[h] = aiValues[j];
34513       }
34514     }
34515   }
34516 }
34517
34518 /*
34519 ** Destroy a bitmap object.  Reclaim all memory used.
34520 */
34521 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34522   if( p==0 ) return;
34523   if( p->iDivisor ){
34524     unsigned int i;
34525     for(i=0; i<BITVEC_NPTR; i++){
34526       sqlite3BitvecDestroy(p->u.apSub[i]);
34527     }
34528   }
34529   sqlite3_free(p);
34530 }
34531
34532 /*
34533 ** Return the value of the iSize parameter specified when Bitvec *p
34534 ** was created.
34535 */
34536 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34537   return p->iSize;
34538 }
34539
34540 #ifndef SQLITE_OMIT_BUILTIN_TEST
34541 /*
34542 ** Let V[] be an array of unsigned characters sufficient to hold
34543 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34544 ** Then the following macros can be used to set, clear, or test
34545 ** individual bits within V.
34546 */
34547 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34548 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34549 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34550
34551 /*
34552 ** This routine runs an extensive test of the Bitvec code.
34553 **
34554 ** The input is an array of integers that acts as a program
34555 ** to test the Bitvec.  The integers are opcodes followed
34556 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34557 ** opcode follows immediately after the last operand.
34558 **
34559 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34560 ** "halt" opcode and causes the test to end.
34561 **
34562 **    0          Halt and return the number of errors
34563 **    1 N S X    Set N bits beginning with S and incrementing by X
34564 **    2 N S X    Clear N bits beginning with S and incrementing by X
34565 **    3 N        Set N randomly chosen bits
34566 **    4 N        Clear N randomly chosen bits
34567 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
34568 **
34569 ** The opcodes 1 through 4 perform set and clear operations are performed
34570 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34571 ** Opcode 5 works on the linear array only, not on the Bitvec.
34572 ** Opcode 5 is used to deliberately induce a fault in order to
34573 ** confirm that error detection works.
34574 **
34575 ** At the conclusion of the test the linear array is compared
34576 ** against the Bitvec object.  If there are any differences,
34577 ** an error is returned.  If they are the same, zero is returned.
34578 **
34579 ** If a memory allocation error occurs, return -1.
34580 */
34581 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34582   Bitvec *pBitvec = 0;
34583   unsigned char *pV = 0;
34584   int rc = -1;
34585   int i, nx, pc, op;
34586   void *pTmpSpace;
34587
34588   /* Allocate the Bitvec to be tested and a linear array of
34589   ** bits to act as the reference */
34590   pBitvec = sqlite3BitvecCreate( sz );
34591   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
34592   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34593   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34594
34595   /* NULL pBitvec tests */
34596   sqlite3BitvecSet(0, 1);
34597   sqlite3BitvecClear(0, 1, pTmpSpace);
34598
34599   /* Run the program */
34600   pc = 0;
34601   while( (op = aOp[pc])!=0 ){
34602     switch( op ){
34603       case 1:
34604       case 2:
34605       case 5: {
34606         nx = 4;
34607         i = aOp[pc+2] - 1;
34608         aOp[pc+2] += aOp[pc+3];
34609         break;
34610       }
34611       case 3:
34612       case 4: 
34613       default: {
34614         nx = 2;
34615         sqlite3_randomness(sizeof(i), &i);
34616         break;
34617       }
34618     }
34619     if( (--aOp[pc+1]) > 0 ) nx = 0;
34620     pc += nx;
34621     i = (i & 0x7fffffff)%sz;
34622     if( (op & 1)!=0 ){
34623       SETBIT(pV, (i+1));
34624       if( op!=5 ){
34625         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34626       }
34627     }else{
34628       CLEARBIT(pV, (i+1));
34629       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34630     }
34631   }
34632
34633   /* Test to make sure the linear array exactly matches the
34634   ** Bitvec object.  Start with the assumption that they do
34635   ** match (rc==0).  Change rc to non-zero if a discrepancy
34636   ** is found.
34637   */
34638   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34639           + sqlite3BitvecTest(pBitvec, 0)
34640           + (sqlite3BitvecSize(pBitvec) - sz);
34641   for(i=1; i<=sz; i++){
34642     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34643       rc = i;
34644       break;
34645     }
34646   }
34647
34648   /* Free allocated structure */
34649 bitvec_end:
34650   sqlite3_free(pTmpSpace);
34651   sqlite3_free(pV);
34652   sqlite3BitvecDestroy(pBitvec);
34653   return rc;
34654 }
34655 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34656
34657 /************** End of bitvec.c **********************************************/
34658 /************** Begin file pcache.c ******************************************/
34659 /*
34660 ** 2008 August 05
34661 **
34662 ** The author disclaims copyright to this source code.  In place of
34663 ** a legal notice, here is a blessing:
34664 **
34665 **    May you do good and not evil.
34666 **    May you find forgiveness for yourself and forgive others.
34667 **    May you share freely, never taking more than you give.
34668 **
34669 *************************************************************************
34670 ** This file implements that page cache.
34671 */
34672
34673 /*
34674 ** A complete page cache is an instance of this structure.
34675 */
34676 struct PCache {
34677   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
34678   PgHdr *pSynced;                     /* Last synced page in dirty page list */
34679   int nRef;                           /* Number of referenced pages */
34680   int szCache;                        /* Configured cache size */
34681   int szPage;                         /* Size of every page in this cache */
34682   int szExtra;                        /* Size of extra space for each page */
34683   int bPurgeable;                     /* True if pages are on backing store */
34684   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
34685   void *pStress;                      /* Argument to xStress */
34686   sqlite3_pcache *pCache;             /* Pluggable cache module */
34687   PgHdr *pPage1;                      /* Reference to page 1 */
34688 };
34689
34690 /*
34691 ** Some of the assert() macros in this code are too expensive to run
34692 ** even during normal debugging.  Use them only rarely on long-running
34693 ** tests.  Enable the expensive asserts using the
34694 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34695 */
34696 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34697 # define expensive_assert(X)  assert(X)
34698 #else
34699 # define expensive_assert(X)
34700 #endif
34701
34702 /********************************** Linked List Management ********************/
34703
34704 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34705 /*
34706 ** Check that the pCache->pSynced variable is set correctly. If it
34707 ** is not, either fail an assert or return zero. Otherwise, return
34708 ** non-zero. This is only used in debugging builds, as follows:
34709 **
34710 **   expensive_assert( pcacheCheckSynced(pCache) );
34711 */
34712 static int pcacheCheckSynced(PCache *pCache){
34713   PgHdr *p;
34714   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34715     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34716   }
34717   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34718 }
34719 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34720
34721 /*
34722 ** Remove page pPage from the list of dirty pages.
34723 */
34724 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34725   PCache *p = pPage->pCache;
34726
34727   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34728   assert( pPage->pDirtyPrev || pPage==p->pDirty );
34729
34730   /* Update the PCache1.pSynced variable if necessary. */
34731   if( p->pSynced==pPage ){
34732     PgHdr *pSynced = pPage->pDirtyPrev;
34733     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34734       pSynced = pSynced->pDirtyPrev;
34735     }
34736     p->pSynced = pSynced;
34737   }
34738
34739   if( pPage->pDirtyNext ){
34740     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34741   }else{
34742     assert( pPage==p->pDirtyTail );
34743     p->pDirtyTail = pPage->pDirtyPrev;
34744   }
34745   if( pPage->pDirtyPrev ){
34746     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34747   }else{
34748     assert( pPage==p->pDirty );
34749     p->pDirty = pPage->pDirtyNext;
34750   }
34751   pPage->pDirtyNext = 0;
34752   pPage->pDirtyPrev = 0;
34753
34754   expensive_assert( pcacheCheckSynced(p) );
34755 }
34756
34757 /*
34758 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34759 ** pPage).
34760 */
34761 static void pcacheAddToDirtyList(PgHdr *pPage){
34762   PCache *p = pPage->pCache;
34763
34764   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34765
34766   pPage->pDirtyNext = p->pDirty;
34767   if( pPage->pDirtyNext ){
34768     assert( pPage->pDirtyNext->pDirtyPrev==0 );
34769     pPage->pDirtyNext->pDirtyPrev = pPage;
34770   }
34771   p->pDirty = pPage;
34772   if( !p->pDirtyTail ){
34773     p->pDirtyTail = pPage;
34774   }
34775   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34776     p->pSynced = pPage;
34777   }
34778   expensive_assert( pcacheCheckSynced(p) );
34779 }
34780
34781 /*
34782 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34783 ** being used for an in-memory database, this function is a no-op.
34784 */
34785 static void pcacheUnpin(PgHdr *p){
34786   PCache *pCache = p->pCache;
34787   if( pCache->bPurgeable ){
34788     if( p->pgno==1 ){
34789       pCache->pPage1 = 0;
34790     }
34791     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
34792   }
34793 }
34794
34795 /*************************************************** General Interfaces ******
34796 **
34797 ** Initialize and shutdown the page cache subsystem. Neither of these 
34798 ** functions are threadsafe.
34799 */
34800 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34801   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
34802     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34803     ** built-in default page cache is used instead of the application defined
34804     ** page cache. */
34805     sqlite3PCacheSetDefault();
34806   }
34807   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
34808 }
34809 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34810   if( sqlite3GlobalConfig.pcache2.xShutdown ){
34811     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34812     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
34813   }
34814 }
34815
34816 /*
34817 ** Return the size in bytes of a PCache object.
34818 */
34819 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34820
34821 /*
34822 ** Create a new PCache object. Storage space to hold the object
34823 ** has already been allocated and is passed in as the p pointer. 
34824 ** The caller discovers how much space needs to be allocated by 
34825 ** calling sqlite3PcacheSize().
34826 */
34827 SQLITE_PRIVATE void sqlite3PcacheOpen(
34828   int szPage,                  /* Size of every page */
34829   int szExtra,                 /* Extra space associated with each page */
34830   int bPurgeable,              /* True if pages are on backing store */
34831   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34832   void *pStress,               /* Argument to xStress */
34833   PCache *p                    /* Preallocated space for the PCache */
34834 ){
34835   memset(p, 0, sizeof(PCache));
34836   p->szPage = szPage;
34837   p->szExtra = szExtra;
34838   p->bPurgeable = bPurgeable;
34839   p->xStress = xStress;
34840   p->pStress = pStress;
34841   p->szCache = 100;
34842 }
34843
34844 /*
34845 ** Change the page size for PCache object. The caller must ensure that there
34846 ** are no outstanding page references when this function is called.
34847 */
34848 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34849   assert( pCache->nRef==0 && pCache->pDirty==0 );
34850   if( pCache->pCache ){
34851     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
34852     pCache->pCache = 0;
34853     pCache->pPage1 = 0;
34854   }
34855   pCache->szPage = szPage;
34856 }
34857
34858 /*
34859 ** Compute the number of pages of cache requested.
34860 */
34861 static int numberOfCachePages(PCache *p){
34862   if( p->szCache>=0 ){
34863     return p->szCache;
34864   }else{
34865     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
34866   }
34867 }
34868
34869 /*
34870 ** Try to obtain a page from the cache.
34871 */
34872 SQLITE_PRIVATE int sqlite3PcacheFetch(
34873   PCache *pCache,       /* Obtain the page from this cache */
34874   Pgno pgno,            /* Page number to obtain */
34875   int createFlag,       /* If true, create page if it does not exist already */
34876   PgHdr **ppPage        /* Write the page here */
34877 ){
34878   sqlite3_pcache_page *pPage = 0;
34879   PgHdr *pPgHdr = 0;
34880   int eCreate;
34881
34882   assert( pCache!=0 );
34883   assert( createFlag==1 || createFlag==0 );
34884   assert( pgno>0 );
34885
34886   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34887   ** allocate it now.
34888   */
34889   if( !pCache->pCache && createFlag ){
34890     sqlite3_pcache *p;
34891     p = sqlite3GlobalConfig.pcache2.xCreate(
34892         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
34893     );
34894     if( !p ){
34895       return SQLITE_NOMEM;
34896     }
34897     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
34898     pCache->pCache = p;
34899   }
34900
34901   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34902   if( pCache->pCache ){
34903     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
34904   }
34905
34906   if( !pPage && eCreate==1 ){
34907     PgHdr *pPg;
34908
34909     /* Find a dirty page to write-out and recycle. First try to find a 
34910     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34911     ** cleared), but if that is not possible settle for any other 
34912     ** unreferenced dirty page.
34913     */
34914     expensive_assert( pcacheCheckSynced(pCache) );
34915     for(pPg=pCache->pSynced; 
34916         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
34917         pPg=pPg->pDirtyPrev
34918     );
34919     pCache->pSynced = pPg;
34920     if( !pPg ){
34921       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34922     }
34923     if( pPg ){
34924       int rc;
34925 #ifdef SQLITE_LOG_CACHE_SPILL
34926       sqlite3_log(SQLITE_FULL, 
34927                   "spill page %d making room for %d - cache used: %d/%d",
34928                   pPg->pgno, pgno,
34929                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
34930                   numberOfCachePages(pCache));
34931 #endif
34932       rc = pCache->xStress(pCache->pStress, pPg);
34933       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34934         return rc;
34935       }
34936     }
34937
34938     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
34939   }
34940
34941   if( pPage ){
34942     pPgHdr = (PgHdr *)pPage->pExtra;
34943
34944     if( !pPgHdr->pPage ){
34945       memset(pPgHdr, 0, sizeof(PgHdr));
34946       pPgHdr->pPage = pPage;
34947       pPgHdr->pData = pPage->pBuf;
34948       pPgHdr->pExtra = (void *)&pPgHdr[1];
34949       memset(pPgHdr->pExtra, 0, pCache->szExtra);
34950       pPgHdr->pCache = pCache;
34951       pPgHdr->pgno = pgno;
34952     }
34953     assert( pPgHdr->pCache==pCache );
34954     assert( pPgHdr->pgno==pgno );
34955     assert( pPgHdr->pData==pPage->pBuf );
34956     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
34957
34958     if( 0==pPgHdr->nRef ){
34959       pCache->nRef++;
34960     }
34961     pPgHdr->nRef++;
34962     if( pgno==1 ){
34963       pCache->pPage1 = pPgHdr;
34964     }
34965   }
34966   *ppPage = pPgHdr;
34967   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34968 }
34969
34970 /*
34971 ** Decrement the reference count on a page. If the page is clean and the
34972 ** reference count drops to 0, then it is made elible for recycling.
34973 */
34974 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34975   assert( p->nRef>0 );
34976   p->nRef--;
34977   if( p->nRef==0 ){
34978     PCache *pCache = p->pCache;
34979     pCache->nRef--;
34980     if( (p->flags&PGHDR_DIRTY)==0 ){
34981       pcacheUnpin(p);
34982     }else{
34983       /* Move the page to the head of the dirty list. */
34984       pcacheRemoveFromDirtyList(p);
34985       pcacheAddToDirtyList(p);
34986     }
34987   }
34988 }
34989
34990 /*
34991 ** Increase the reference count of a supplied page by 1.
34992 */
34993 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34994   assert(p->nRef>0);
34995   p->nRef++;
34996 }
34997
34998 /*
34999 ** Drop a page from the cache. There must be exactly one reference to the
35000 ** page. This function deletes that reference, so after it returns the
35001 ** page pointed to by p is invalid.
35002 */
35003 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35004   PCache *pCache;
35005   assert( p->nRef==1 );
35006   if( p->flags&PGHDR_DIRTY ){
35007     pcacheRemoveFromDirtyList(p);
35008   }
35009   pCache = p->pCache;
35010   pCache->nRef--;
35011   if( p->pgno==1 ){
35012     pCache->pPage1 = 0;
35013   }
35014   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
35015 }
35016
35017 /*
35018 ** Make sure the page is marked as dirty. If it isn't dirty already,
35019 ** make it so.
35020 */
35021 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35022   p->flags &= ~PGHDR_DONT_WRITE;
35023   assert( p->nRef>0 );
35024   if( 0==(p->flags & PGHDR_DIRTY) ){
35025     p->flags |= PGHDR_DIRTY;
35026     pcacheAddToDirtyList( p);
35027   }
35028 }
35029
35030 /*
35031 ** Make sure the page is marked as clean. If it isn't clean already,
35032 ** make it so.
35033 */
35034 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35035   if( (p->flags & PGHDR_DIRTY) ){
35036     pcacheRemoveFromDirtyList(p);
35037     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35038     if( p->nRef==0 ){
35039       pcacheUnpin(p);
35040     }
35041   }
35042 }
35043
35044 /*
35045 ** Make every page in the cache clean.
35046 */
35047 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35048   PgHdr *p;
35049   while( (p = pCache->pDirty)!=0 ){
35050     sqlite3PcacheMakeClean(p);
35051   }
35052 }
35053
35054 /*
35055 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35056 */
35057 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35058   PgHdr *p;
35059   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35060     p->flags &= ~PGHDR_NEED_SYNC;
35061   }
35062   pCache->pSynced = pCache->pDirtyTail;
35063 }
35064
35065 /*
35066 ** Change the page number of page p to newPgno. 
35067 */
35068 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35069   PCache *pCache = p->pCache;
35070   assert( p->nRef>0 );
35071   assert( newPgno>0 );
35072   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
35073   p->pgno = newPgno;
35074   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35075     pcacheRemoveFromDirtyList(p);
35076     pcacheAddToDirtyList(p);
35077   }
35078 }
35079
35080 /*
35081 ** Drop every cache entry whose page number is greater than "pgno". The
35082 ** caller must ensure that there are no outstanding references to any pages
35083 ** other than page 1 with a page number greater than pgno.
35084 **
35085 ** If there is a reference to page 1 and the pgno parameter passed to this
35086 ** function is 0, then the data area associated with page 1 is zeroed, but
35087 ** the page object is not dropped.
35088 */
35089 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35090   if( pCache->pCache ){
35091     PgHdr *p;
35092     PgHdr *pNext;
35093     for(p=pCache->pDirty; p; p=pNext){
35094       pNext = p->pDirtyNext;
35095       /* This routine never gets call with a positive pgno except right
35096       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35097       ** it must be that pgno==0.
35098       */
35099       assert( p->pgno>0 );
35100       if( ALWAYS(p->pgno>pgno) ){
35101         assert( p->flags&PGHDR_DIRTY );
35102         sqlite3PcacheMakeClean(p);
35103       }
35104     }
35105     if( pgno==0 && pCache->pPage1 ){
35106       memset(pCache->pPage1->pData, 0, pCache->szPage);
35107       pgno = 1;
35108     }
35109     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
35110   }
35111 }
35112
35113 /*
35114 ** Close a cache.
35115 */
35116 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35117   if( pCache->pCache ){
35118     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35119   }
35120 }
35121
35122 /* 
35123 ** Discard the contents of the cache.
35124 */
35125 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35126   sqlite3PcacheTruncate(pCache, 0);
35127 }
35128
35129 /*
35130 ** Merge two lists of pages connected by pDirty and in pgno order.
35131 ** Do not both fixing the pDirtyPrev pointers.
35132 */
35133 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35134   PgHdr result, *pTail;
35135   pTail = &result;
35136   while( pA && pB ){
35137     if( pA->pgno<pB->pgno ){
35138       pTail->pDirty = pA;
35139       pTail = pA;
35140       pA = pA->pDirty;
35141     }else{
35142       pTail->pDirty = pB;
35143       pTail = pB;
35144       pB = pB->pDirty;
35145     }
35146   }
35147   if( pA ){
35148     pTail->pDirty = pA;
35149   }else if( pB ){
35150     pTail->pDirty = pB;
35151   }else{
35152     pTail->pDirty = 0;
35153   }
35154   return result.pDirty;
35155 }
35156
35157 /*
35158 ** Sort the list of pages in accending order by pgno.  Pages are
35159 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35160 ** corrupted by this sort.
35161 **
35162 ** Since there cannot be more than 2^31 distinct pages in a database,
35163 ** there cannot be more than 31 buckets required by the merge sorter.
35164 ** One extra bucket is added to catch overflow in case something
35165 ** ever changes to make the previous sentence incorrect.
35166 */
35167 #define N_SORT_BUCKET  32
35168 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35169   PgHdr *a[N_SORT_BUCKET], *p;
35170   int i;
35171   memset(a, 0, sizeof(a));
35172   while( pIn ){
35173     p = pIn;
35174     pIn = p->pDirty;
35175     p->pDirty = 0;
35176     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35177       if( a[i]==0 ){
35178         a[i] = p;
35179         break;
35180       }else{
35181         p = pcacheMergeDirtyList(a[i], p);
35182         a[i] = 0;
35183       }
35184     }
35185     if( NEVER(i==N_SORT_BUCKET-1) ){
35186       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35187       ** the input list.  But that is impossible.
35188       */
35189       a[i] = pcacheMergeDirtyList(a[i], p);
35190     }
35191   }
35192   p = a[0];
35193   for(i=1; i<N_SORT_BUCKET; i++){
35194     p = pcacheMergeDirtyList(p, a[i]);
35195   }
35196   return p;
35197 }
35198
35199 /*
35200 ** Return a list of all dirty pages in the cache, sorted by page number.
35201 */
35202 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35203   PgHdr *p;
35204   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35205     p->pDirty = p->pDirtyNext;
35206   }
35207   return pcacheSortDirtyList(pCache->pDirty);
35208 }
35209
35210 /* 
35211 ** Return the total number of referenced pages held by the cache.
35212 */
35213 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35214   return pCache->nRef;
35215 }
35216
35217 /*
35218 ** Return the number of references to the page supplied as an argument.
35219 */
35220 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35221   return p->nRef;
35222 }
35223
35224 /* 
35225 ** Return the total number of pages in the cache.
35226 */
35227 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35228   int nPage = 0;
35229   if( pCache->pCache ){
35230     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
35231   }
35232   return nPage;
35233 }
35234
35235 #ifdef SQLITE_TEST
35236 /*
35237 ** Get the suggested cache-size value.
35238 */
35239 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35240   return numberOfCachePages(pCache);
35241 }
35242 #endif
35243
35244 /*
35245 ** Set the suggested cache-size value.
35246 */
35247 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35248   pCache->szCache = mxPage;
35249   if( pCache->pCache ){
35250     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
35251                                            numberOfCachePages(pCache));
35252   }
35253 }
35254
35255 /*
35256 ** Free up as much memory as possible from the page cache.
35257 */
35258 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
35259   if( pCache->pCache ){
35260     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
35261   }
35262 }
35263
35264 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35265 /*
35266 ** For all dirty pages currently in the cache, invoke the specified
35267 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35268 ** defined.
35269 */
35270 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35271   PgHdr *pDirty;
35272   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35273     xIter(pDirty);
35274   }
35275 }
35276 #endif
35277
35278 /************** End of pcache.c **********************************************/
35279 /************** Begin file pcache1.c *****************************************/
35280 /*
35281 ** 2008 November 05
35282 **
35283 ** The author disclaims copyright to this source code.  In place of
35284 ** a legal notice, here is a blessing:
35285 **
35286 **    May you do good and not evil.
35287 **    May you find forgiveness for yourself and forgive others.
35288 **    May you share freely, never taking more than you give.
35289 **
35290 *************************************************************************
35291 **
35292 ** This file implements the default page cache implementation (the
35293 ** sqlite3_pcache interface). It also contains part of the implementation
35294 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35295 ** If the default page cache implementation is overriden, then neither of
35296 ** these two features are available.
35297 */
35298
35299
35300 typedef struct PCache1 PCache1;
35301 typedef struct PgHdr1 PgHdr1;
35302 typedef struct PgFreeslot PgFreeslot;
35303 typedef struct PGroup PGroup;
35304
35305 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
35306 ** of one or more PCaches that are able to recycle each others unpinned
35307 ** pages when they are under memory pressure.  A PGroup is an instance of
35308 ** the following object.
35309 **
35310 ** This page cache implementation works in one of two modes:
35311 **
35312 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35313 **        one PGroup per PCache.
35314 **
35315 **   (2)  There is a single global PGroup that all PCaches are a member
35316 **        of.
35317 **
35318 ** Mode 1 uses more memory (since PCache instances are not able to rob
35319 ** unused pages from other PCaches) but it also operates without a mutex,
35320 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35321 ** threadsafe, but recycles pages more efficiently.
35322 **
35323 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35324 ** PGroup which is the pcache1.grp global variable and its mutex is
35325 ** SQLITE_MUTEX_STATIC_LRU.
35326 */
35327 struct PGroup {
35328   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35329   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
35330   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
35331   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
35332   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
35333   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35334 };
35335
35336 /* Each page cache is an instance of the following object.  Every
35337 ** open database file (including each in-memory database and each
35338 ** temporary or transient database) has a single page cache which
35339 ** is an instance of this object.
35340 **
35341 ** Pointers to structures of this type are cast and returned as 
35342 ** opaque sqlite3_pcache* handles.
35343 */
35344 struct PCache1 {
35345   /* Cache configuration parameters. Page size (szPage) and the purgeable
35346   ** flag (bPurgeable) are set when the cache is created. nMax may be 
35347   ** modified at any time by a call to the pcache1Cachesize() method.
35348   ** The PGroup mutex must be held when accessing nMax.
35349   */
35350   PGroup *pGroup;                     /* PGroup this cache belongs to */
35351   int szPage;                         /* Size of allocated pages in bytes */
35352   int szExtra;                        /* Size of extra space in bytes */
35353   int bPurgeable;                     /* True if cache is purgeable */
35354   unsigned int nMin;                  /* Minimum number of pages reserved */
35355   unsigned int nMax;                  /* Configured "cache_size" value */
35356   unsigned int n90pct;                /* nMax*9/10 */
35357   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35358
35359   /* Hash table of all pages. The following variables may only be accessed
35360   ** when the accessor is holding the PGroup mutex.
35361   */
35362   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35363   unsigned int nPage;                 /* Total number of pages in apHash */
35364   unsigned int nHash;                 /* Number of slots in apHash[] */
35365   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35366 };
35367
35368 /*
35369 ** Each cache entry is represented by an instance of the following 
35370 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
35371 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
35372 ** in memory.
35373 */
35374 struct PgHdr1 {
35375   sqlite3_pcache_page page;
35376   unsigned int iKey;             /* Key value (page number) */
35377   PgHdr1 *pNext;                 /* Next in hash table chain */
35378   PCache1 *pCache;               /* Cache that currently owns this page */
35379   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35380   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35381 };
35382
35383 /*
35384 ** Free slots in the allocator used to divide up the buffer provided using
35385 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35386 */
35387 struct PgFreeslot {
35388   PgFreeslot *pNext;  /* Next free slot */
35389 };
35390
35391 /*
35392 ** Global data used by this cache.
35393 */
35394 static SQLITE_WSD struct PCacheGlobal {
35395   PGroup grp;                    /* The global PGroup for mode (2) */
35396
35397   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35398   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35399   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35400   ** The nFreeSlot and pFree values do require mutex protection.
35401   */
35402   int isInit;                    /* True if initialized */
35403   int szSlot;                    /* Size of each free slot */
35404   int nSlot;                     /* The number of pcache slots */
35405   int nReserve;                  /* Try to keep nFreeSlot above this */
35406   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35407   /* Above requires no mutex.  Use mutex below for variable that follow. */
35408   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35409   PgFreeslot *pFree;             /* Free page blocks */
35410   int nFreeSlot;                 /* Number of unused pcache slots */
35411   /* The following value requires a mutex to change.  We skip the mutex on
35412   ** reading because (1) most platforms read a 32-bit integer atomically and
35413   ** (2) even if an incorrect value is read, no great harm is done since this
35414   ** is really just an optimization. */
35415   int bUnderPressure;            /* True if low on PAGECACHE memory */
35416 } pcache1_g;
35417
35418 /*
35419 ** All code in this file should access the global structure above via the
35420 ** alias "pcache1". This ensures that the WSD emulation is used when
35421 ** compiling for systems that do not support real WSD.
35422 */
35423 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35424
35425 /*
35426 ** Macros to enter and leave the PCache LRU mutex.
35427 */
35428 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35429 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35430
35431 /******************************************************************************/
35432 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35433
35434 /*
35435 ** This function is called during initialization if a static buffer is 
35436 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35437 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35438 ** enough to contain 'n' buffers of 'sz' bytes each.
35439 **
35440 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35441 ** to be serialized already.  There is no need for further mutexing.
35442 */
35443 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35444   if( pcache1.isInit ){
35445     PgFreeslot *p;
35446     sz = ROUNDDOWN8(sz);
35447     pcache1.szSlot = sz;
35448     pcache1.nSlot = pcache1.nFreeSlot = n;
35449     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35450     pcache1.pStart = pBuf;
35451     pcache1.pFree = 0;
35452     pcache1.bUnderPressure = 0;
35453     while( n-- ){
35454       p = (PgFreeslot*)pBuf;
35455       p->pNext = pcache1.pFree;
35456       pcache1.pFree = p;
35457       pBuf = (void*)&((char*)pBuf)[sz];
35458     }
35459     pcache1.pEnd = pBuf;
35460   }
35461 }
35462
35463 /*
35464 ** Malloc function used within this file to allocate space from the buffer
35465 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35466 ** such buffer exists or there is no space left in it, this function falls 
35467 ** back to sqlite3Malloc().
35468 **
35469 ** Multiple threads can run this routine at the same time.  Global variables
35470 ** in pcache1 need to be protected via mutex.
35471 */
35472 static void *pcache1Alloc(int nByte){
35473   void *p = 0;
35474   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35475   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35476   if( nByte<=pcache1.szSlot ){
35477     sqlite3_mutex_enter(pcache1.mutex);
35478     p = (PgHdr1 *)pcache1.pFree;
35479     if( p ){
35480       pcache1.pFree = pcache1.pFree->pNext;
35481       pcache1.nFreeSlot--;
35482       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35483       assert( pcache1.nFreeSlot>=0 );
35484       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35485     }
35486     sqlite3_mutex_leave(pcache1.mutex);
35487   }
35488   if( p==0 ){
35489     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35490     ** it from sqlite3Malloc instead.
35491     */
35492     p = sqlite3Malloc(nByte);
35493 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35494     if( p ){
35495       int sz = sqlite3MallocSize(p);
35496       sqlite3_mutex_enter(pcache1.mutex);
35497       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35498       sqlite3_mutex_leave(pcache1.mutex);
35499     }
35500 #endif
35501     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35502   }
35503   return p;
35504 }
35505
35506 /*
35507 ** Free an allocated buffer obtained from pcache1Alloc().
35508 */
35509 static int pcache1Free(void *p){
35510   int nFreed = 0;
35511   if( p==0 ) return 0;
35512   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35513     PgFreeslot *pSlot;
35514     sqlite3_mutex_enter(pcache1.mutex);
35515     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35516     pSlot = (PgFreeslot*)p;
35517     pSlot->pNext = pcache1.pFree;
35518     pcache1.pFree = pSlot;
35519     pcache1.nFreeSlot++;
35520     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35521     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35522     sqlite3_mutex_leave(pcache1.mutex);
35523   }else{
35524     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35525     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35526     nFreed = sqlite3MallocSize(p);
35527 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35528     sqlite3_mutex_enter(pcache1.mutex);
35529     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
35530     sqlite3_mutex_leave(pcache1.mutex);
35531 #endif
35532     sqlite3_free(p);
35533   }
35534   return nFreed;
35535 }
35536
35537 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35538 /*
35539 ** Return the size of a pcache allocation
35540 */
35541 static int pcache1MemSize(void *p){
35542   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35543     return pcache1.szSlot;
35544   }else{
35545     int iSize;
35546     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35547     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35548     iSize = sqlite3MallocSize(p);
35549     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35550     return iSize;
35551   }
35552 }
35553 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35554
35555 /*
35556 ** Allocate a new page object initially associated with cache pCache.
35557 */
35558 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35559   PgHdr1 *p = 0;
35560   void *pPg;
35561
35562   /* The group mutex must be released before pcache1Alloc() is called. This
35563   ** is because it may call sqlite3_release_memory(), which assumes that 
35564   ** this mutex is not held. */
35565   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35566   pcache1LeaveMutex(pCache->pGroup);
35567 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
35568   pPg = pcache1Alloc(pCache->szPage);
35569   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
35570   if( !pPg || !p ){
35571     pcache1Free(pPg);
35572     sqlite3_free(p);
35573     pPg = 0;
35574   }
35575 #else
35576   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
35577   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
35578 #endif
35579   pcache1EnterMutex(pCache->pGroup);
35580
35581   if( pPg ){
35582     p->page.pBuf = pPg;
35583     p->page.pExtra = &p[1];
35584     if( pCache->bPurgeable ){
35585       pCache->pGroup->nCurrentPage++;
35586     }
35587     return p;
35588   }
35589   return 0;
35590 }
35591
35592 /*
35593 ** Free a page object allocated by pcache1AllocPage().
35594 **
35595 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
35596 ** that the current implementation happens to never call this routine
35597 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35598 */
35599 static void pcache1FreePage(PgHdr1 *p){
35600   if( ALWAYS(p) ){
35601     PCache1 *pCache = p->pCache;
35602     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
35603     pcache1Free(p->page.pBuf);
35604 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
35605     sqlite3_free(p);
35606 #endif
35607     if( pCache->bPurgeable ){
35608       pCache->pGroup->nCurrentPage--;
35609     }
35610   }
35611 }
35612
35613 /*
35614 ** Malloc function used by SQLite to obtain space from the buffer configured
35615 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35616 ** exists, this function falls back to sqlite3Malloc().
35617 */
35618 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35619   return pcache1Alloc(sz);
35620 }
35621
35622 /*
35623 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35624 */
35625 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35626   pcache1Free(p);
35627 }
35628
35629
35630 /*
35631 ** Return true if it desirable to avoid allocating a new page cache
35632 ** entry.
35633 **
35634 ** If memory was allocated specifically to the page cache using
35635 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35636 ** it is desirable to avoid allocating a new page cache entry because
35637 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35638 ** for all page cache needs and we should not need to spill the
35639 ** allocation onto the heap.
35640 **
35641 ** Or, the heap is used for all page cache memory but the heap is
35642 ** under memory pressure, then again it is desirable to avoid
35643 ** allocating a new page cache entry in order to avoid stressing
35644 ** the heap even further.
35645 */
35646 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35647   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
35648     return pcache1.bUnderPressure;
35649   }else{
35650     return sqlite3HeapNearlyFull();
35651   }
35652 }
35653
35654 /******************************************************************************/
35655 /******** General Implementation Functions ************************************/
35656
35657 /*
35658 ** This function is used to resize the hash table used by the cache passed
35659 ** as the first argument.
35660 **
35661 ** The PCache mutex must be held when this function is called.
35662 */
35663 static int pcache1ResizeHash(PCache1 *p){
35664   PgHdr1 **apNew;
35665   unsigned int nNew;
35666   unsigned int i;
35667
35668   assert( sqlite3_mutex_held(p->pGroup->mutex) );
35669
35670   nNew = p->nHash*2;
35671   if( nNew<256 ){
35672     nNew = 256;
35673   }
35674
35675   pcache1LeaveMutex(p->pGroup);
35676   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35677   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
35678   if( p->nHash ){ sqlite3EndBenignMalloc(); }
35679   pcache1EnterMutex(p->pGroup);
35680   if( apNew ){
35681     for(i=0; i<p->nHash; i++){
35682       PgHdr1 *pPage;
35683       PgHdr1 *pNext = p->apHash[i];
35684       while( (pPage = pNext)!=0 ){
35685         unsigned int h = pPage->iKey % nNew;
35686         pNext = pPage->pNext;
35687         pPage->pNext = apNew[h];
35688         apNew[h] = pPage;
35689       }
35690     }
35691     sqlite3_free(p->apHash);
35692     p->apHash = apNew;
35693     p->nHash = nNew;
35694   }
35695
35696   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35697 }
35698
35699 /*
35700 ** This function is used internally to remove the page pPage from the 
35701 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35702 ** LRU list, then this function is a no-op.
35703 **
35704 ** The PGroup mutex must be held when this function is called.
35705 **
35706 ** If pPage is NULL then this routine is a no-op.
35707 */
35708 static void pcache1PinPage(PgHdr1 *pPage){
35709   PCache1 *pCache;
35710   PGroup *pGroup;
35711
35712   if( pPage==0 ) return;
35713   pCache = pPage->pCache;
35714   pGroup = pCache->pGroup;
35715   assert( sqlite3_mutex_held(pGroup->mutex) );
35716   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35717     if( pPage->pLruPrev ){
35718       pPage->pLruPrev->pLruNext = pPage->pLruNext;
35719     }
35720     if( pPage->pLruNext ){
35721       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35722     }
35723     if( pGroup->pLruHead==pPage ){
35724       pGroup->pLruHead = pPage->pLruNext;
35725     }
35726     if( pGroup->pLruTail==pPage ){
35727       pGroup->pLruTail = pPage->pLruPrev;
35728     }
35729     pPage->pLruNext = 0;
35730     pPage->pLruPrev = 0;
35731     pPage->pCache->nRecyclable--;
35732   }
35733 }
35734
35735
35736 /*
35737 ** Remove the page supplied as an argument from the hash table 
35738 ** (PCache1.apHash structure) that it is currently stored in.
35739 **
35740 ** The PGroup mutex must be held when this function is called.
35741 */
35742 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35743   unsigned int h;
35744   PCache1 *pCache = pPage->pCache;
35745   PgHdr1 **pp;
35746
35747   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35748   h = pPage->iKey % pCache->nHash;
35749   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35750   *pp = (*pp)->pNext;
35751
35752   pCache->nPage--;
35753 }
35754
35755 /*
35756 ** If there are currently more than nMaxPage pages allocated, try
35757 ** to recycle pages to reduce the number allocated to nMaxPage.
35758 */
35759 static void pcache1EnforceMaxPage(PGroup *pGroup){
35760   assert( sqlite3_mutex_held(pGroup->mutex) );
35761   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35762     PgHdr1 *p = pGroup->pLruTail;
35763     assert( p->pCache->pGroup==pGroup );
35764     pcache1PinPage(p);
35765     pcache1RemoveFromHash(p);
35766     pcache1FreePage(p);
35767   }
35768 }
35769
35770 /*
35771 ** Discard all pages from cache pCache with a page number (key value) 
35772 ** greater than or equal to iLimit. Any pinned pages that meet this 
35773 ** criteria are unpinned before they are discarded.
35774 **
35775 ** The PCache mutex must be held when this function is called.
35776 */
35777 static void pcache1TruncateUnsafe(
35778   PCache1 *pCache,             /* The cache to truncate */
35779   unsigned int iLimit          /* Drop pages with this pgno or larger */
35780 ){
35781   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
35782   unsigned int h;
35783   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35784   for(h=0; h<pCache->nHash; h++){
35785     PgHdr1 **pp = &pCache->apHash[h]; 
35786     PgHdr1 *pPage;
35787     while( (pPage = *pp)!=0 ){
35788       if( pPage->iKey>=iLimit ){
35789         pCache->nPage--;
35790         *pp = pPage->pNext;
35791         pcache1PinPage(pPage);
35792         pcache1FreePage(pPage);
35793       }else{
35794         pp = &pPage->pNext;
35795         TESTONLY( nPage++; )
35796       }
35797     }
35798   }
35799   assert( pCache->nPage==nPage );
35800 }
35801
35802 /******************************************************************************/
35803 /******** sqlite3_pcache Methods **********************************************/
35804
35805 /*
35806 ** Implementation of the sqlite3_pcache.xInit method.
35807 */
35808 static int pcache1Init(void *NotUsed){
35809   UNUSED_PARAMETER(NotUsed);
35810   assert( pcache1.isInit==0 );
35811   memset(&pcache1, 0, sizeof(pcache1));
35812   if( sqlite3GlobalConfig.bCoreMutex ){
35813     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35814     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35815   }
35816   pcache1.grp.mxPinned = 10;
35817   pcache1.isInit = 1;
35818   return SQLITE_OK;
35819 }
35820
35821 /*
35822 ** Implementation of the sqlite3_pcache.xShutdown method.
35823 ** Note that the static mutex allocated in xInit does 
35824 ** not need to be freed.
35825 */
35826 static void pcache1Shutdown(void *NotUsed){
35827   UNUSED_PARAMETER(NotUsed);
35828   assert( pcache1.isInit!=0 );
35829   memset(&pcache1, 0, sizeof(pcache1));
35830 }
35831
35832 /*
35833 ** Implementation of the sqlite3_pcache.xCreate method.
35834 **
35835 ** Allocate a new cache.
35836 */
35837 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
35838   PCache1 *pCache;      /* The newly created page cache */
35839   PGroup *pGroup;       /* The group the new page cache will belong to */
35840   int sz;               /* Bytes of memory required to allocate the new cache */
35841
35842   /*
35843   ** The seperateCache variable is true if each PCache has its own private
35844   ** PGroup.  In other words, separateCache is true for mode (1) where no
35845   ** mutexing is required.
35846   **
35847   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35848   **
35849   **   *  Always use a unified cache in single-threaded applications
35850   **
35851   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35852   **      use separate caches (mode-1)
35853   */
35854 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35855   const int separateCache = 0;
35856 #else
35857   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35858 #endif
35859
35860   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
35861   assert( szExtra < 300 );
35862
35863   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35864   pCache = (PCache1 *)sqlite3MallocZero(sz);
35865   if( pCache ){
35866     if( separateCache ){
35867       pGroup = (PGroup*)&pCache[1];
35868       pGroup->mxPinned = 10;
35869     }else{
35870       pGroup = &pcache1.grp;
35871     }
35872     pCache->pGroup = pGroup;
35873     pCache->szPage = szPage;
35874     pCache->szExtra = szExtra;
35875     pCache->bPurgeable = (bPurgeable ? 1 : 0);
35876     if( bPurgeable ){
35877       pCache->nMin = 10;
35878       pcache1EnterMutex(pGroup);
35879       pGroup->nMinPage += pCache->nMin;
35880       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35881       pcache1LeaveMutex(pGroup);
35882     }
35883   }
35884   return (sqlite3_pcache *)pCache;
35885 }
35886
35887 /*
35888 ** Implementation of the sqlite3_pcache.xCachesize method. 
35889 **
35890 ** Configure the cache_size limit for a cache.
35891 */
35892 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35893   PCache1 *pCache = (PCache1 *)p;
35894   if( pCache->bPurgeable ){
35895     PGroup *pGroup = pCache->pGroup;
35896     pcache1EnterMutex(pGroup);
35897     pGroup->nMaxPage += (nMax - pCache->nMax);
35898     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35899     pCache->nMax = nMax;
35900     pCache->n90pct = pCache->nMax*9/10;
35901     pcache1EnforceMaxPage(pGroup);
35902     pcache1LeaveMutex(pGroup);
35903   }
35904 }
35905
35906 /*
35907 ** Implementation of the sqlite3_pcache.xShrink method. 
35908 **
35909 ** Free up as much memory as possible.
35910 */
35911 static void pcache1Shrink(sqlite3_pcache *p){
35912   PCache1 *pCache = (PCache1*)p;
35913   if( pCache->bPurgeable ){
35914     PGroup *pGroup = pCache->pGroup;
35915     int savedMaxPage;
35916     pcache1EnterMutex(pGroup);
35917     savedMaxPage = pGroup->nMaxPage;
35918     pGroup->nMaxPage = 0;
35919     pcache1EnforceMaxPage(pGroup);
35920     pGroup->nMaxPage = savedMaxPage;
35921     pcache1LeaveMutex(pGroup);
35922   }
35923 }
35924
35925 /*
35926 ** Implementation of the sqlite3_pcache.xPagecount method. 
35927 */
35928 static int pcache1Pagecount(sqlite3_pcache *p){
35929   int n;
35930   PCache1 *pCache = (PCache1*)p;
35931   pcache1EnterMutex(pCache->pGroup);
35932   n = pCache->nPage;
35933   pcache1LeaveMutex(pCache->pGroup);
35934   return n;
35935 }
35936
35937 /*
35938 ** Implementation of the sqlite3_pcache.xFetch method. 
35939 **
35940 ** Fetch a page by key value.
35941 **
35942 ** Whether or not a new page may be allocated by this function depends on
35943 ** the value of the createFlag argument.  0 means do not allocate a new
35944 ** page.  1 means allocate a new page if space is easily available.  2 
35945 ** means to try really hard to allocate a new page.
35946 **
35947 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35948 ** database) there is really no difference between createFlag 1 and 2.  So
35949 ** the calling function (pcache.c) will never have a createFlag of 1 on
35950 ** a non-purgeable cache.
35951 **
35952 ** There are three different approaches to obtaining space for a page,
35953 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35954 **
35955 **   1. Regardless of the value of createFlag, the cache is searched for a 
35956 **      copy of the requested page. If one is found, it is returned.
35957 **
35958 **   2. If createFlag==0 and the page is not already in the cache, NULL is
35959 **      returned.
35960 **
35961 **   3. If createFlag is 1, and the page is not already in the cache, then
35962 **      return NULL (do not allocate a new page) if any of the following
35963 **      conditions are true:
35964 **
35965 **       (a) the number of pages pinned by the cache is greater than
35966 **           PCache1.nMax, or
35967 **
35968 **       (b) the number of pages pinned by the cache is greater than
35969 **           the sum of nMax for all purgeable caches, less the sum of 
35970 **           nMin for all other purgeable caches, or
35971 **
35972 **   4. If none of the first three conditions apply and the cache is marked
35973 **      as purgeable, and if one of the following is true:
35974 **
35975 **       (a) The number of pages allocated for the cache is already 
35976 **           PCache1.nMax, or
35977 **
35978 **       (b) The number of pages allocated for all purgeable caches is
35979 **           already equal to or greater than the sum of nMax for all
35980 **           purgeable caches,
35981 **
35982 **       (c) The system is under memory pressure and wants to avoid
35983 **           unnecessary pages cache entry allocations
35984 **
35985 **      then attempt to recycle a page from the LRU list. If it is the right
35986 **      size, return the recycled buffer. Otherwise, free the buffer and
35987 **      proceed to step 5. 
35988 **
35989 **   5. Otherwise, allocate and return a new page buffer.
35990 */
35991 static sqlite3_pcache_page *pcache1Fetch(
35992   sqlite3_pcache *p, 
35993   unsigned int iKey, 
35994   int createFlag
35995 ){
35996   unsigned int nPinned;
35997   PCache1 *pCache = (PCache1 *)p;
35998   PGroup *pGroup;
35999   PgHdr1 *pPage = 0;
36000
36001   assert( pCache->bPurgeable || createFlag!=1 );
36002   assert( pCache->bPurgeable || pCache->nMin==0 );
36003   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36004   assert( pCache->nMin==0 || pCache->bPurgeable );
36005   pcache1EnterMutex(pGroup = pCache->pGroup);
36006
36007   /* Step 1: Search the hash table for an existing entry. */
36008   if( pCache->nHash>0 ){
36009     unsigned int h = iKey % pCache->nHash;
36010     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36011   }
36012
36013   /* Step 2: Abort if no existing page is found and createFlag is 0 */
36014   if( pPage || createFlag==0 ){
36015     pcache1PinPage(pPage);
36016     goto fetch_out;
36017   }
36018
36019   /* The pGroup local variable will normally be initialized by the
36020   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
36021   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36022   ** local variable here.  Delaying the initialization of pGroup is an
36023   ** optimization:  The common case is to exit the module before reaching
36024   ** this point.
36025   */
36026 #ifdef SQLITE_MUTEX_OMIT
36027   pGroup = pCache->pGroup;
36028 #endif
36029
36030   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36031   assert( pCache->nPage >= pCache->nRecyclable );
36032   nPinned = pCache->nPage - pCache->nRecyclable;
36033   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36034   assert( pCache->n90pct == pCache->nMax*9/10 );
36035   if( createFlag==1 && (
36036         nPinned>=pGroup->mxPinned
36037      || nPinned>=pCache->n90pct
36038      || pcache1UnderMemoryPressure(pCache)
36039   )){
36040     goto fetch_out;
36041   }
36042
36043   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36044     goto fetch_out;
36045   }
36046
36047   /* Step 4. Try to recycle a page. */
36048   if( pCache->bPurgeable && pGroup->pLruTail && (
36049          (pCache->nPage+1>=pCache->nMax)
36050       || pGroup->nCurrentPage>=pGroup->nMaxPage
36051       || pcache1UnderMemoryPressure(pCache)
36052   )){
36053     PCache1 *pOther;
36054     pPage = pGroup->pLruTail;
36055     pcache1RemoveFromHash(pPage);
36056     pcache1PinPage(pPage);
36057     pOther = pPage->pCache;
36058
36059     /* We want to verify that szPage and szExtra are the same for pOther
36060     ** and pCache.  Assert that we can verify this by comparing sums. */
36061     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
36062     assert( pCache->szExtra<512 );
36063     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
36064     assert( pOther->szExtra<512 );
36065
36066     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
36067       pcache1FreePage(pPage);
36068       pPage = 0;
36069     }else{
36070       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
36071     }
36072   }
36073
36074   /* Step 5. If a usable page buffer has still not been found, 
36075   ** attempt to allocate a new one. 
36076   */
36077   if( !pPage ){
36078     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36079     pPage = pcache1AllocPage(pCache);
36080     if( createFlag==1 ) sqlite3EndBenignMalloc();
36081   }
36082
36083   if( pPage ){
36084     unsigned int h = iKey % pCache->nHash;
36085     pCache->nPage++;
36086     pPage->iKey = iKey;
36087     pPage->pNext = pCache->apHash[h];
36088     pPage->pCache = pCache;
36089     pPage->pLruPrev = 0;
36090     pPage->pLruNext = 0;
36091     *(void **)pPage->page.pExtra = 0;
36092     pCache->apHash[h] = pPage;
36093   }
36094
36095 fetch_out:
36096   if( pPage && iKey>pCache->iMaxKey ){
36097     pCache->iMaxKey = iKey;
36098   }
36099   pcache1LeaveMutex(pGroup);
36100   return &pPage->page;
36101 }
36102
36103
36104 /*
36105 ** Implementation of the sqlite3_pcache.xUnpin method.
36106 **
36107 ** Mark a page as unpinned (eligible for asynchronous recycling).
36108 */
36109 static void pcache1Unpin(
36110   sqlite3_pcache *p, 
36111   sqlite3_pcache_page *pPg, 
36112   int reuseUnlikely
36113 ){
36114   PCache1 *pCache = (PCache1 *)p;
36115   PgHdr1 *pPage = (PgHdr1 *)pPg;
36116   PGroup *pGroup = pCache->pGroup;
36117  
36118   assert( pPage->pCache==pCache );
36119   pcache1EnterMutex(pGroup);
36120
36121   /* It is an error to call this function if the page is already 
36122   ** part of the PGroup LRU list.
36123   */
36124   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36125   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36126
36127   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36128     pcache1RemoveFromHash(pPage);
36129     pcache1FreePage(pPage);
36130   }else{
36131     /* Add the page to the PGroup LRU list. */
36132     if( pGroup->pLruHead ){
36133       pGroup->pLruHead->pLruPrev = pPage;
36134       pPage->pLruNext = pGroup->pLruHead;
36135       pGroup->pLruHead = pPage;
36136     }else{
36137       pGroup->pLruTail = pPage;
36138       pGroup->pLruHead = pPage;
36139     }
36140     pCache->nRecyclable++;
36141   }
36142
36143   pcache1LeaveMutex(pCache->pGroup);
36144 }
36145
36146 /*
36147 ** Implementation of the sqlite3_pcache.xRekey method. 
36148 */
36149 static void pcache1Rekey(
36150   sqlite3_pcache *p,
36151   sqlite3_pcache_page *pPg,
36152   unsigned int iOld,
36153   unsigned int iNew
36154 ){
36155   PCache1 *pCache = (PCache1 *)p;
36156   PgHdr1 *pPage = (PgHdr1 *)pPg;
36157   PgHdr1 **pp;
36158   unsigned int h; 
36159   assert( pPage->iKey==iOld );
36160   assert( pPage->pCache==pCache );
36161
36162   pcache1EnterMutex(pCache->pGroup);
36163
36164   h = iOld%pCache->nHash;
36165   pp = &pCache->apHash[h];
36166   while( (*pp)!=pPage ){
36167     pp = &(*pp)->pNext;
36168   }
36169   *pp = pPage->pNext;
36170
36171   h = iNew%pCache->nHash;
36172   pPage->iKey = iNew;
36173   pPage->pNext = pCache->apHash[h];
36174   pCache->apHash[h] = pPage;
36175   if( iNew>pCache->iMaxKey ){
36176     pCache->iMaxKey = iNew;
36177   }
36178
36179   pcache1LeaveMutex(pCache->pGroup);
36180 }
36181
36182 /*
36183 ** Implementation of the sqlite3_pcache.xTruncate method. 
36184 **
36185 ** Discard all unpinned pages in the cache with a page number equal to
36186 ** or greater than parameter iLimit. Any pinned pages with a page number
36187 ** equal to or greater than iLimit are implicitly unpinned.
36188 */
36189 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36190   PCache1 *pCache = (PCache1 *)p;
36191   pcache1EnterMutex(pCache->pGroup);
36192   if( iLimit<=pCache->iMaxKey ){
36193     pcache1TruncateUnsafe(pCache, iLimit);
36194     pCache->iMaxKey = iLimit-1;
36195   }
36196   pcache1LeaveMutex(pCache->pGroup);
36197 }
36198
36199 /*
36200 ** Implementation of the sqlite3_pcache.xDestroy method. 
36201 **
36202 ** Destroy a cache allocated using pcache1Create().
36203 */
36204 static void pcache1Destroy(sqlite3_pcache *p){
36205   PCache1 *pCache = (PCache1 *)p;
36206   PGroup *pGroup = pCache->pGroup;
36207   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36208   pcache1EnterMutex(pGroup);
36209   pcache1TruncateUnsafe(pCache, 0);
36210   assert( pGroup->nMaxPage >= pCache->nMax );
36211   pGroup->nMaxPage -= pCache->nMax;
36212   assert( pGroup->nMinPage >= pCache->nMin );
36213   pGroup->nMinPage -= pCache->nMin;
36214   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36215   pcache1EnforceMaxPage(pGroup);
36216   pcache1LeaveMutex(pGroup);
36217   sqlite3_free(pCache->apHash);
36218   sqlite3_free(pCache);
36219 }
36220
36221 /*
36222 ** This function is called during initialization (sqlite3_initialize()) to
36223 ** install the default pluggable cache module, assuming the user has not
36224 ** already provided an alternative.
36225 */
36226 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36227   static const sqlite3_pcache_methods2 defaultMethods = {
36228     1,                       /* iVersion */
36229     0,                       /* pArg */
36230     pcache1Init,             /* xInit */
36231     pcache1Shutdown,         /* xShutdown */
36232     pcache1Create,           /* xCreate */
36233     pcache1Cachesize,        /* xCachesize */
36234     pcache1Pagecount,        /* xPagecount */
36235     pcache1Fetch,            /* xFetch */
36236     pcache1Unpin,            /* xUnpin */
36237     pcache1Rekey,            /* xRekey */
36238     pcache1Truncate,         /* xTruncate */
36239     pcache1Destroy,          /* xDestroy */
36240     pcache1Shrink            /* xShrink */
36241   };
36242   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
36243 }
36244
36245 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36246 /*
36247 ** This function is called to free superfluous dynamically allocated memory
36248 ** held by the pager system. Memory in use by any SQLite pager allocated
36249 ** by the current thread may be sqlite3_free()ed.
36250 **
36251 ** nReq is the number of bytes of memory required. Once this much has
36252 ** been released, the function returns. The return value is the total number 
36253 ** of bytes of memory released.
36254 */
36255 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36256   int nFree = 0;
36257   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36258   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36259   if( pcache1.pStart==0 ){
36260     PgHdr1 *p;
36261     pcache1EnterMutex(&pcache1.grp);
36262     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36263       nFree += pcache1MemSize(p->page.pBuf);
36264 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36265       nFree += sqlite3MemSize(p);
36266 #endif
36267       pcache1PinPage(p);
36268       pcache1RemoveFromHash(p);
36269       pcache1FreePage(p);
36270     }
36271     pcache1LeaveMutex(&pcache1.grp);
36272   }
36273   return nFree;
36274 }
36275 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36276
36277 #ifdef SQLITE_TEST
36278 /*
36279 ** This function is used by test procedures to inspect the internal state
36280 ** of the global cache.
36281 */
36282 SQLITE_PRIVATE void sqlite3PcacheStats(
36283   int *pnCurrent,      /* OUT: Total number of pages cached */
36284   int *pnMax,          /* OUT: Global maximum cache size */
36285   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36286   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36287 ){
36288   PgHdr1 *p;
36289   int nRecyclable = 0;
36290   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36291     nRecyclable++;
36292   }
36293   *pnCurrent = pcache1.grp.nCurrentPage;
36294   *pnMax = (int)pcache1.grp.nMaxPage;
36295   *pnMin = (int)pcache1.grp.nMinPage;
36296   *pnRecyclable = nRecyclable;
36297 }
36298 #endif
36299
36300 /************** End of pcache1.c *********************************************/
36301 /************** Begin file rowset.c ******************************************/
36302 /*
36303 ** 2008 December 3
36304 **
36305 ** The author disclaims copyright to this source code.  In place of
36306 ** a legal notice, here is a blessing:
36307 **
36308 **    May you do good and not evil.
36309 **    May you find forgiveness for yourself and forgive others.
36310 **    May you share freely, never taking more than you give.
36311 **
36312 *************************************************************************
36313 **
36314 ** This module implements an object we call a "RowSet".
36315 **
36316 ** The RowSet object is a collection of rowids.  Rowids
36317 ** are inserted into the RowSet in an arbitrary order.  Inserts
36318 ** can be intermixed with tests to see if a given rowid has been
36319 ** previously inserted into the RowSet.
36320 **
36321 ** After all inserts are finished, it is possible to extract the
36322 ** elements of the RowSet in sorted order.  Once this extraction
36323 ** process has started, no new elements may be inserted.
36324 **
36325 ** Hence, the primitive operations for a RowSet are:
36326 **
36327 **    CREATE
36328 **    INSERT
36329 **    TEST
36330 **    SMALLEST
36331 **    DESTROY
36332 **
36333 ** The CREATE and DESTROY primitives are the constructor and destructor,
36334 ** obviously.  The INSERT primitive adds a new element to the RowSet.
36335 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
36336 ** extracts the least value from the RowSet.
36337 **
36338 ** The INSERT primitive might allocate additional memory.  Memory is
36339 ** allocated in chunks so most INSERTs do no allocation.  There is an 
36340 ** upper bound on the size of allocated memory.  No memory is freed
36341 ** until DESTROY.
36342 **
36343 ** The TEST primitive includes a "batch" number.  The TEST primitive
36344 ** will only see elements that were inserted before the last change
36345 ** in the batch number.  In other words, if an INSERT occurs between
36346 ** two TESTs where the TESTs have the same batch nubmer, then the
36347 ** value added by the INSERT will not be visible to the second TEST.
36348 ** The initial batch number is zero, so if the very first TEST contains
36349 ** a non-zero batch number, it will see all prior INSERTs.
36350 **
36351 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
36352 ** that is attempted.
36353 **
36354 ** The cost of an INSERT is roughly constant.  (Sometime new memory
36355 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
36356 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36357 ** The cost of a TEST using the same batch number is O(logN).  The cost
36358 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
36359 ** primitives are constant time.  The cost of DESTROY is O(N).
36360 **
36361 ** There is an added cost of O(N) when switching between TEST and
36362 ** SMALLEST primitives.
36363 */
36364
36365
36366 /*
36367 ** Target size for allocation chunks.
36368 */
36369 #define ROWSET_ALLOCATION_SIZE 1024
36370
36371 /*
36372 ** The number of rowset entries per allocation chunk.
36373 */
36374 #define ROWSET_ENTRY_PER_CHUNK  \
36375                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36376
36377 /*
36378 ** Each entry in a RowSet is an instance of the following object.
36379 **
36380 ** This same object is reused to store a linked list of trees of RowSetEntry
36381 ** objects.  In that alternative use, pRight points to the next entry
36382 ** in the list, pLeft points to the tree, and v is unused.  The
36383 ** RowSet.pForest value points to the head of this forest list.
36384 */
36385 struct RowSetEntry {            
36386   i64 v;                        /* ROWID value for this entry */
36387   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
36388   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
36389 };
36390
36391 /*
36392 ** RowSetEntry objects are allocated in large chunks (instances of the
36393 ** following structure) to reduce memory allocation overhead.  The
36394 ** chunks are kept on a linked list so that they can be deallocated
36395 ** when the RowSet is destroyed.
36396 */
36397 struct RowSetChunk {
36398   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
36399   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36400 };
36401
36402 /*
36403 ** A RowSet in an instance of the following structure.
36404 **
36405 ** A typedef of this structure if found in sqliteInt.h.
36406 */
36407 struct RowSet {
36408   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
36409   sqlite3 *db;                   /* The database connection */
36410   struct RowSetEntry *pEntry;    /* List of entries using pRight */
36411   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
36412   struct RowSetEntry *pFresh;    /* Source of new entry objects */
36413   struct RowSetEntry *pForest;   /* List of binary trees of entries */
36414   u16 nFresh;                    /* Number of objects on pFresh */
36415   u8 rsFlags;                    /* Various flags */
36416   u8 iBatch;                     /* Current insert batch */
36417 };
36418
36419 /*
36420 ** Allowed values for RowSet.rsFlags
36421 */
36422 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
36423 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
36424
36425 /*
36426 ** Turn bulk memory into a RowSet object.  N bytes of memory
36427 ** are available at pSpace.  The db pointer is used as a memory context
36428 ** for any subsequent allocations that need to occur.
36429 ** Return a pointer to the new RowSet object.
36430 **
36431 ** It must be the case that N is sufficient to make a Rowset.  If not
36432 ** an assertion fault occurs.
36433 ** 
36434 ** If N is larger than the minimum, use the surplus as an initial
36435 ** allocation of entries available to be filled.
36436 */
36437 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36438   RowSet *p;
36439   assert( N >= ROUND8(sizeof(*p)) );
36440   p = pSpace;
36441   p->pChunk = 0;
36442   p->db = db;
36443   p->pEntry = 0;
36444   p->pLast = 0;
36445   p->pForest = 0;
36446   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36447   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36448   p->rsFlags = ROWSET_SORTED;
36449   p->iBatch = 0;
36450   return p;
36451 }
36452
36453 /*
36454 ** Deallocate all chunks from a RowSet.  This frees all memory that
36455 ** the RowSet has allocated over its lifetime.  This routine is
36456 ** the destructor for the RowSet.
36457 */
36458 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36459   struct RowSetChunk *pChunk, *pNextChunk;
36460   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36461     pNextChunk = pChunk->pNextChunk;
36462     sqlite3DbFree(p->db, pChunk);
36463   }
36464   p->pChunk = 0;
36465   p->nFresh = 0;
36466   p->pEntry = 0;
36467   p->pLast = 0;
36468   p->pForest = 0;
36469   p->rsFlags = ROWSET_SORTED;
36470 }
36471
36472 /*
36473 ** Allocate a new RowSetEntry object that is associated with the
36474 ** given RowSet.  Return a pointer to the new and completely uninitialized
36475 ** objected.
36476 **
36477 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
36478 ** routine returns NULL.
36479 */
36480 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
36481   assert( p!=0 );
36482   if( p->nFresh==0 ){
36483     struct RowSetChunk *pNew;
36484     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36485     if( pNew==0 ){
36486       return 0;
36487     }
36488     pNew->pNextChunk = p->pChunk;
36489     p->pChunk = pNew;
36490     p->pFresh = pNew->aEntry;
36491     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36492   }
36493   p->nFresh--;
36494   return p->pFresh++;
36495 }
36496
36497 /*
36498 ** Insert a new value into a RowSet.
36499 **
36500 ** The mallocFailed flag of the database connection is set if a
36501 ** memory allocation fails.
36502 */
36503 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36504   struct RowSetEntry *pEntry;  /* The new entry */
36505   struct RowSetEntry *pLast;   /* The last prior entry */
36506
36507   /* This routine is never called after sqlite3RowSetNext() */
36508   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
36509
36510   pEntry = rowSetEntryAlloc(p);
36511   if( pEntry==0 ) return;
36512   pEntry->v = rowid;
36513   pEntry->pRight = 0;
36514   pLast = p->pLast;
36515   if( pLast ){
36516     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
36517       p->rsFlags &= ~ROWSET_SORTED;
36518     }
36519     pLast->pRight = pEntry;
36520   }else{
36521     p->pEntry = pEntry;
36522   }
36523   p->pLast = pEntry;
36524 }
36525
36526 /*
36527 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
36528 **
36529 ** The input lists are connected via pRight pointers and are 
36530 ** assumed to each already be in sorted order.
36531 */
36532 static struct RowSetEntry *rowSetEntryMerge(
36533   struct RowSetEntry *pA,    /* First sorted list to be merged */
36534   struct RowSetEntry *pB     /* Second sorted list to be merged */
36535 ){
36536   struct RowSetEntry head;
36537   struct RowSetEntry *pTail;
36538
36539   pTail = &head;
36540   while( pA && pB ){
36541     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36542     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36543     if( pA->v<pB->v ){
36544       pTail->pRight = pA;
36545       pA = pA->pRight;
36546       pTail = pTail->pRight;
36547     }else if( pB->v<pA->v ){
36548       pTail->pRight = pB;
36549       pB = pB->pRight;
36550       pTail = pTail->pRight;
36551     }else{
36552       pA = pA->pRight;
36553     }
36554   }
36555   if( pA ){
36556     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36557     pTail->pRight = pA;
36558   }else{
36559     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36560     pTail->pRight = pB;
36561   }
36562   return head.pRight;
36563 }
36564
36565 /*
36566 ** Sort all elements on the list of RowSetEntry objects into order of
36567 ** increasing v.
36568 */ 
36569 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
36570   unsigned int i;
36571   struct RowSetEntry *pNext, *aBucket[40];
36572
36573   memset(aBucket, 0, sizeof(aBucket));
36574   while( pIn ){
36575     pNext = pIn->pRight;
36576     pIn->pRight = 0;
36577     for(i=0; aBucket[i]; i++){
36578       pIn = rowSetEntryMerge(aBucket[i], pIn);
36579       aBucket[i] = 0;
36580     }
36581     aBucket[i] = pIn;
36582     pIn = pNext;
36583   }
36584   pIn = 0;
36585   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36586     pIn = rowSetEntryMerge(pIn, aBucket[i]);
36587   }
36588   return pIn;
36589 }
36590
36591
36592 /*
36593 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36594 ** Convert this tree into a linked list connected by the pRight pointers
36595 ** and return pointers to the first and last elements of the new list.
36596 */
36597 static void rowSetTreeToList(
36598   struct RowSetEntry *pIn,         /* Root of the input tree */
36599   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36600   struct RowSetEntry **ppLast      /* Write tail of the output list here */
36601 ){
36602   assert( pIn!=0 );
36603   if( pIn->pLeft ){
36604     struct RowSetEntry *p;
36605     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36606     p->pRight = pIn;
36607   }else{
36608     *ppFirst = pIn;
36609   }
36610   if( pIn->pRight ){
36611     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36612   }else{
36613     *ppLast = pIn;
36614   }
36615   assert( (*ppLast)->pRight==0 );
36616 }
36617
36618
36619 /*
36620 ** Convert a sorted list of elements (connected by pRight) into a binary
36621 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36622 ** node taken from the head of *ppList.  A depth of 2 means a tree with
36623 ** three nodes.  And so forth.
36624 **
36625 ** Use as many entries from the input list as required and update the
36626 ** *ppList to point to the unused elements of the list.  If the input
36627 ** list contains too few elements, then construct an incomplete tree
36628 ** and leave *ppList set to NULL.
36629 **
36630 ** Return a pointer to the root of the constructed binary tree.
36631 */
36632 static struct RowSetEntry *rowSetNDeepTree(
36633   struct RowSetEntry **ppList,
36634   int iDepth
36635 ){
36636   struct RowSetEntry *p;         /* Root of the new tree */
36637   struct RowSetEntry *pLeft;     /* Left subtree */
36638   if( *ppList==0 ){
36639     return 0;
36640   }
36641   if( iDepth==1 ){
36642     p = *ppList;
36643     *ppList = p->pRight;
36644     p->pLeft = p->pRight = 0;
36645     return p;
36646   }
36647   pLeft = rowSetNDeepTree(ppList, iDepth-1);
36648   p = *ppList;
36649   if( p==0 ){
36650     return pLeft;
36651   }
36652   p->pLeft = pLeft;
36653   *ppList = p->pRight;
36654   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36655   return p;
36656 }
36657
36658 /*
36659 ** Convert a sorted list of elements into a binary tree. Make the tree
36660 ** as deep as it needs to be in order to contain the entire list.
36661 */
36662 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36663   int iDepth;           /* Depth of the tree so far */
36664   struct RowSetEntry *p;       /* Current tree root */
36665   struct RowSetEntry *pLeft;   /* Left subtree */
36666
36667   assert( pList!=0 );
36668   p = pList;
36669   pList = p->pRight;
36670   p->pLeft = p->pRight = 0;
36671   for(iDepth=1; pList; iDepth++){
36672     pLeft = p;
36673     p = pList;
36674     pList = p->pRight;
36675     p->pLeft = pLeft;
36676     p->pRight = rowSetNDeepTree(&pList, iDepth);
36677   }
36678   return p;
36679 }
36680
36681 /*
36682 ** Take all the entries on p->pEntry and on the trees in p->pForest and
36683 ** sort them all together into one big ordered list on p->pEntry.
36684 **
36685 ** This routine should only be called once in the life of a RowSet.
36686 */
36687 static void rowSetToList(RowSet *p){
36688
36689   /* This routine is called only once */
36690   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
36691
36692   if( (p->rsFlags & ROWSET_SORTED)==0 ){
36693     p->pEntry = rowSetEntrySort(p->pEntry);
36694   }
36695
36696   /* While this module could theoretically support it, sqlite3RowSetNext()
36697   ** is never called after sqlite3RowSetText() for the same RowSet.  So
36698   ** there is never a forest to deal with.  Should this change, simply
36699   ** remove the assert() and the #if 0. */
36700   assert( p->pForest==0 );
36701 #if 0
36702   while( p->pForest ){
36703     struct RowSetEntry *pTree = p->pForest->pLeft;
36704     if( pTree ){
36705       struct RowSetEntry *pHead, *pTail;
36706       rowSetTreeToList(pTree, &pHead, &pTail);
36707       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
36708     }
36709     p->pForest = p->pForest->pRight;
36710   }
36711 #endif
36712   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
36713 }
36714
36715 /*
36716 ** Extract the smallest element from the RowSet.
36717 ** Write the element into *pRowid.  Return 1 on success.  Return
36718 ** 0 if the RowSet is already empty.
36719 **
36720 ** After this routine has been called, the sqlite3RowSetInsert()
36721 ** routine may not be called again.  
36722 */
36723 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36724   assert( p!=0 );
36725
36726   /* Merge the forest into a single sorted list on first call */
36727   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
36728
36729   /* Return the next entry on the list */
36730   if( p->pEntry ){
36731     *pRowid = p->pEntry->v;
36732     p->pEntry = p->pEntry->pRight;
36733     if( p->pEntry==0 ){
36734       sqlite3RowSetClear(p);
36735     }
36736     return 1;
36737   }else{
36738     return 0;
36739   }
36740 }
36741
36742 /*
36743 ** Check to see if element iRowid was inserted into the rowset as
36744 ** part of any insert batch prior to iBatch.  Return 1 or 0.
36745 **
36746 ** If this is the first test of a new batch and if there exist entires
36747 ** on pRowSet->pEntry, then sort those entires into the forest at
36748 ** pRowSet->pForest so that they can be tested.
36749 */
36750 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36751   struct RowSetEntry *p, *pTree;
36752
36753   /* This routine is never called after sqlite3RowSetNext() */
36754   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
36755
36756   /* Sort entries into the forest on the first test of a new batch 
36757   */
36758   if( iBatch!=pRowSet->iBatch ){
36759     p = pRowSet->pEntry;
36760     if( p ){
36761       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
36762       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
36763         p = rowSetEntrySort(p);
36764       }
36765       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
36766         ppPrevTree = &pTree->pRight;
36767         if( pTree->pLeft==0 ){
36768           pTree->pLeft = rowSetListToTree(p);
36769           break;
36770         }else{
36771           struct RowSetEntry *pAux, *pTail;
36772           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
36773           pTree->pLeft = 0;
36774           p = rowSetEntryMerge(pAux, p);
36775         }
36776       }
36777       if( pTree==0 ){
36778         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
36779         if( pTree ){
36780           pTree->v = 0;
36781           pTree->pRight = 0;
36782           pTree->pLeft = rowSetListToTree(p);
36783         }
36784       }
36785       pRowSet->pEntry = 0;
36786       pRowSet->pLast = 0;
36787       pRowSet->rsFlags |= ROWSET_SORTED;
36788     }
36789     pRowSet->iBatch = iBatch;
36790   }
36791
36792   /* Test to see if the iRowid value appears anywhere in the forest.
36793   ** Return 1 if it does and 0 if not.
36794   */
36795   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
36796     p = pTree->pLeft;
36797     while( p ){
36798       if( p->v<iRowid ){
36799         p = p->pRight;
36800       }else if( p->v>iRowid ){
36801         p = p->pLeft;
36802       }else{
36803         return 1;
36804       }
36805     }
36806   }
36807   return 0;
36808 }
36809
36810 /************** End of rowset.c **********************************************/
36811 /************** Begin file pager.c *******************************************/
36812 /*
36813 ** 2001 September 15
36814 **
36815 ** The author disclaims copyright to this source code.  In place of
36816 ** a legal notice, here is a blessing:
36817 **
36818 **    May you do good and not evil.
36819 **    May you find forgiveness for yourself and forgive others.
36820 **    May you share freely, never taking more than you give.
36821 **
36822 *************************************************************************
36823 ** This is the implementation of the page cache subsystem or "pager".
36824 ** 
36825 ** The pager is used to access a database disk file.  It implements
36826 ** atomic commit and rollback through the use of a journal file that
36827 ** is separate from the database file.  The pager also implements file
36828 ** locking to prevent two processes from writing the same database
36829 ** file simultaneously, or one process from reading the database while
36830 ** another is writing.
36831 */
36832 #ifndef SQLITE_OMIT_DISKIO
36833 /************** Include wal.h in the middle of pager.c ***********************/
36834 /************** Begin file wal.h *********************************************/
36835 /*
36836 ** 2010 February 1
36837 **
36838 ** The author disclaims copyright to this source code.  In place of
36839 ** a legal notice, here is a blessing:
36840 **
36841 **    May you do good and not evil.
36842 **    May you find forgiveness for yourself and forgive others.
36843 **    May you share freely, never taking more than you give.
36844 **
36845 *************************************************************************
36846 ** This header file defines the interface to the write-ahead logging 
36847 ** system. Refer to the comments below and the header comment attached to 
36848 ** the implementation of each function in log.c for further details.
36849 */
36850
36851 #ifndef _WAL_H_
36852 #define _WAL_H_
36853
36854
36855 /* Additional values that can be added to the sync_flags argument of
36856 ** sqlite3WalFrames():
36857 */
36858 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
36859 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
36860
36861 #ifdef SQLITE_OMIT_WAL
36862 # define sqlite3WalOpen(x,y,z)                   0
36863 # define sqlite3WalLimit(x,y)
36864 # define sqlite3WalClose(w,x,y,z)                0
36865 # define sqlite3WalBeginReadTransaction(y,z)     0
36866 # define sqlite3WalEndReadTransaction(z)
36867 # define sqlite3WalRead(v,w,x,y,z)               0
36868 # define sqlite3WalDbsize(y)                     0
36869 # define sqlite3WalBeginWriteTransaction(y)      0
36870 # define sqlite3WalEndWriteTransaction(x)        0
36871 # define sqlite3WalUndo(x,y,z)                   0
36872 # define sqlite3WalSavepoint(y,z)
36873 # define sqlite3WalSavepointUndo(y,z)            0
36874 # define sqlite3WalFrames(u,v,w,x,y,z)           0
36875 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36876 # define sqlite3WalCallback(z)                   0
36877 # define sqlite3WalExclusiveMode(y,z)            0
36878 # define sqlite3WalHeapMemory(z)                 0
36879 # define sqlite3WalFramesize(z)                  0
36880 #else
36881
36882 #define WAL_SAVEPOINT_NDATA 4
36883
36884 /* Connection to a write-ahead log (WAL) file. 
36885 ** There is one object of this type for each pager. 
36886 */
36887 typedef struct Wal Wal;
36888
36889 /* Open and close a connection to a write-ahead log. */
36890 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
36891 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36892
36893 /* Set the limiting size of a WAL file. */
36894 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
36895
36896 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
36897 ** snapshot is like a read-transaction.  It is the state of the database
36898 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
36899 ** preserves the current state even if the other threads or processes
36900 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
36901 ** transaction and releases the lock.
36902 */
36903 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36904 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36905
36906 /* Read a page from the write-ahead log, if it is present. */
36907 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36908
36909 /* If the WAL is not empty, return the size of the database. */
36910 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36911
36912 /* Obtain or release the WRITER lock. */
36913 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36914 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36915
36916 /* Undo any frames written (but not committed) to the log */
36917 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36918
36919 /* Return an integer that records the current (uncommitted) write
36920 ** position in the WAL */
36921 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36922
36923 /* Move the write position of the WAL back to iFrame.  Called in
36924 ** response to a ROLLBACK TO command. */
36925 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36926
36927 /* Write a frame or frames to the log. */
36928 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36929
36930 /* Copy pages from the log to the database file */ 
36931 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36932   Wal *pWal,                      /* Write-ahead log connection */
36933   int eMode,                      /* One of PASSIVE, FULL and RESTART */
36934   int (*xBusy)(void*),            /* Function to call when busy */
36935   void *pBusyArg,                 /* Context argument for xBusyHandler */
36936   int sync_flags,                 /* Flags to sync db file with (or 0) */
36937   int nBuf,                       /* Size of buffer nBuf */
36938   u8 *zBuf,                       /* Temporary buffer to use */
36939   int *pnLog,                     /* OUT: Number of frames in WAL */
36940   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
36941 );
36942
36943 /* Return the value to pass to a sqlite3_wal_hook callback, the
36944 ** number of frames in the WAL at the point of the last commit since
36945 ** sqlite3WalCallback() was called.  If no commits have occurred since
36946 ** the last call, then return 0.
36947 */
36948 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36949
36950 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36951 ** by the pager layer on the database file.
36952 */
36953 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36954
36955 /* Return true if the argument is non-NULL and the WAL module is using
36956 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36957 ** WAL module is using shared-memory, return false. 
36958 */
36959 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36960
36961 #ifdef SQLITE_ENABLE_ZIPVFS
36962 /* If the WAL file is not empty, return the number of bytes of content
36963 ** stored in each frame (i.e. the db page-size when the WAL was created).
36964 */
36965 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
36966 #endif
36967
36968 #endif /* ifndef SQLITE_OMIT_WAL */
36969 #endif /* _WAL_H_ */
36970
36971 /************** End of wal.h *************************************************/
36972 /************** Continuing where we left off in pager.c **********************/
36973
36974
36975 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36976 **
36977 ** This comment block describes invariants that hold when using a rollback
36978 ** journal.  These invariants do not apply for journal_mode=WAL,
36979 ** journal_mode=MEMORY, or journal_mode=OFF.
36980 **
36981 ** Within this comment block, a page is deemed to have been synced
36982 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36983 ** Otherwise, the page is not synced until the xSync method of the VFS
36984 ** is called successfully on the file containing the page.
36985 **
36986 ** Definition:  A page of the database file is said to be "overwriteable" if
36987 ** one or more of the following are true about the page:
36988 ** 
36989 **     (a)  The original content of the page as it was at the beginning of
36990 **          the transaction has been written into the rollback journal and
36991 **          synced.
36992 ** 
36993 **     (b)  The page was a freelist leaf page at the start of the transaction.
36994 ** 
36995 **     (c)  The page number is greater than the largest page that existed in
36996 **          the database file at the start of the transaction.
36997 ** 
36998 ** (1) A page of the database file is never overwritten unless one of the
36999 **     following are true:
37000 ** 
37001 **     (a) The page and all other pages on the same sector are overwriteable.
37002 ** 
37003 **     (b) The atomic page write optimization is enabled, and the entire
37004 **         transaction other than the update of the transaction sequence
37005 **         number consists of a single page change.
37006 ** 
37007 ** (2) The content of a page written into the rollback journal exactly matches
37008 **     both the content in the database when the rollback journal was written
37009 **     and the content in the database at the beginning of the current
37010 **     transaction.
37011 ** 
37012 ** (3) Writes to the database file are an integer multiple of the page size
37013 **     in length and are aligned on a page boundary.
37014 ** 
37015 ** (4) Reads from the database file are either aligned on a page boundary and
37016 **     an integer multiple of the page size in length or are taken from the
37017 **     first 100 bytes of the database file.
37018 ** 
37019 ** (5) All writes to the database file are synced prior to the rollback journal
37020 **     being deleted, truncated, or zeroed.
37021 ** 
37022 ** (6) If a master journal file is used, then all writes to the database file
37023 **     are synced prior to the master journal being deleted.
37024 ** 
37025 ** Definition: Two databases (or the same database at two points it time)
37026 ** are said to be "logically equivalent" if they give the same answer to
37027 ** all queries.  Note in particular the content of freelist leaf
37028 ** pages can be changed arbitarily without effecting the logical equivalence
37029 ** of the database.
37030 ** 
37031 ** (7) At any time, if any subset, including the empty set and the total set,
37032 **     of the unsynced changes to a rollback journal are removed and the 
37033 **     journal is rolled back, the resulting database file will be logical
37034 **     equivalent to the database file at the beginning of the transaction.
37035 ** 
37036 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37037 **     is called to restore the database file to the same size it was at
37038 **     the beginning of the transaction.  (In some VFSes, the xTruncate
37039 **     method is a no-op, but that does not change the fact the SQLite will
37040 **     invoke it.)
37041 ** 
37042 ** (9) Whenever the database file is modified, at least one bit in the range
37043 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
37044 **     the EXCLUSIVE lock, thus signaling other connections on the same
37045 **     database to flush their caches.
37046 **
37047 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37048 **      than one billion transactions.
37049 **
37050 ** (11) A database file is well-formed at the beginning and at the conclusion
37051 **      of every transaction.
37052 **
37053 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37054 **      the database file.
37055 **
37056 ** (13) A SHARED lock is held on the database file while reading any
37057 **      content out of the database file.
37058 **
37059 ******************************************************************************/
37060
37061 /*
37062 ** Macros for troubleshooting.  Normally turned off
37063 */
37064 #if 0
37065 int sqlite3PagerTrace=1;  /* True to enable tracing */
37066 #define sqlite3DebugPrintf printf
37067 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37068 #else
37069 #define PAGERTRACE(X)
37070 #endif
37071
37072 /*
37073 ** The following two macros are used within the PAGERTRACE() macros above
37074 ** to print out file-descriptors. 
37075 **
37076 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37077 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37078 ** struct as its argument.
37079 */
37080 #define PAGERID(p) ((int)(p->fd))
37081 #define FILEHANDLEID(fd) ((int)fd)
37082
37083 /*
37084 ** The Pager.eState variable stores the current 'state' of a pager. A
37085 ** pager may be in any one of the seven states shown in the following
37086 ** state diagram.
37087 **
37088 **                            OPEN <------+------+
37089 **                              |         |      |
37090 **                              V         |      |
37091 **               +---------> READER-------+      |
37092 **               |              |                |
37093 **               |              V                |
37094 **               |<-------WRITER_LOCKED------> ERROR
37095 **               |              |                ^  
37096 **               |              V                |
37097 **               |<------WRITER_CACHEMOD-------->|
37098 **               |              |                |
37099 **               |              V                |
37100 **               |<-------WRITER_DBMOD---------->|
37101 **               |              |                |
37102 **               |              V                |
37103 **               +<------WRITER_FINISHED-------->+
37104 **
37105 **
37106 ** List of state transitions and the C [function] that performs each:
37107 ** 
37108 **   OPEN              -> READER              [sqlite3PagerSharedLock]
37109 **   READER            -> OPEN                [pager_unlock]
37110 **
37111 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
37112 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
37113 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
37114 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
37115 **   WRITER_***        -> READER              [pager_end_transaction]
37116 **
37117 **   WRITER_***        -> ERROR               [pager_error]
37118 **   ERROR             -> OPEN                [pager_unlock]
37119 ** 
37120 **
37121 **  OPEN:
37122 **
37123 **    The pager starts up in this state. Nothing is guaranteed in this
37124 **    state - the file may or may not be locked and the database size is
37125 **    unknown. The database may not be read or written.
37126 **
37127 **    * No read or write transaction is active.
37128 **    * Any lock, or no lock at all, may be held on the database file.
37129 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37130 **
37131 **  READER:
37132 **
37133 **    In this state all the requirements for reading the database in 
37134 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
37135 **    was) in exclusive-locking mode, a user-level read transaction is 
37136 **    open. The database size is known in this state.
37137 **
37138 **    A connection running with locking_mode=normal enters this state when
37139 **    it opens a read-transaction on the database and returns to state
37140 **    OPEN after the read-transaction is completed. However a connection
37141 **    running in locking_mode=exclusive (including temp databases) remains in
37142 **    this state even after the read-transaction is closed. The only way
37143 **    a locking_mode=exclusive connection can transition from READER to OPEN
37144 **    is via the ERROR state (see below).
37145 ** 
37146 **    * A read transaction may be active (but a write-transaction cannot).
37147 **    * A SHARED or greater lock is held on the database file.
37148 **    * The dbSize variable may be trusted (even if a user-level read 
37149 **      transaction is not active). The dbOrigSize and dbFileSize variables
37150 **      may not be trusted at this point.
37151 **    * If the database is a WAL database, then the WAL connection is open.
37152 **    * Even if a read-transaction is not open, it is guaranteed that 
37153 **      there is no hot-journal in the file-system.
37154 **
37155 **  WRITER_LOCKED:
37156 **
37157 **    The pager moves to this state from READER when a write-transaction
37158 **    is first opened on the database. In WRITER_LOCKED state, all locks 
37159 **    required to start a write-transaction are held, but no actual 
37160 **    modifications to the cache or database have taken place.
37161 **
37162 **    In rollback mode, a RESERVED or (if the transaction was opened with 
37163 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37164 **    moving to this state, but the journal file is not written to or opened 
37165 **    to in this state. If the transaction is committed or rolled back while 
37166 **    in WRITER_LOCKED state, all that is required is to unlock the database 
37167 **    file.
37168 **
37169 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37170 **    If the connection is running with locking_mode=exclusive, an attempt
37171 **    is made to obtain an EXCLUSIVE lock on the database file.
37172 **
37173 **    * A write transaction is active.
37174 **    * If the connection is open in rollback-mode, a RESERVED or greater 
37175 **      lock is held on the database file.
37176 **    * If the connection is open in WAL-mode, a WAL write transaction
37177 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37178 **      called).
37179 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37180 **    * The contents of the pager cache have not been modified.
37181 **    * The journal file may or may not be open.
37182 **    * Nothing (not even the first header) has been written to the journal.
37183 **
37184 **  WRITER_CACHEMOD:
37185 **
37186 **    A pager moves from WRITER_LOCKED state to this state when a page is
37187 **    first modified by the upper layer. In rollback mode the journal file
37188 **    is opened (if it is not already open) and a header written to the
37189 **    start of it. The database file on disk has not been modified.
37190 **
37191 **    * A write transaction is active.
37192 **    * A RESERVED or greater lock is held on the database file.
37193 **    * The journal file is open and the first header has been written 
37194 **      to it, but the header has not been synced to disk.
37195 **    * The contents of the page cache have been modified.
37196 **
37197 **  WRITER_DBMOD:
37198 **
37199 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37200 **    when it modifies the contents of the database file. WAL connections
37201 **    never enter this state (since they do not modify the database file,
37202 **    just the log file).
37203 **
37204 **    * A write transaction is active.
37205 **    * An EXCLUSIVE or greater lock is held on the database file.
37206 **    * The journal file is open and the first header has been written 
37207 **      and synced to disk.
37208 **    * The contents of the page cache have been modified (and possibly
37209 **      written to disk).
37210 **
37211 **  WRITER_FINISHED:
37212 **
37213 **    It is not possible for a WAL connection to enter this state.
37214 **
37215 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37216 **    state after the entire transaction has been successfully written into the
37217 **    database file. In this state the transaction may be committed simply
37218 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
37219 **    not possible to modify the database further. At this point, the upper 
37220 **    layer must either commit or rollback the transaction.
37221 **
37222 **    * A write transaction is active.
37223 **    * An EXCLUSIVE or greater lock is held on the database file.
37224 **    * All writing and syncing of journal and database data has finished.
37225 **      If no error occured, all that remains is to finalize the journal to
37226 **      commit the transaction. If an error did occur, the caller will need
37227 **      to rollback the transaction. 
37228 **
37229 **  ERROR:
37230 **
37231 **    The ERROR state is entered when an IO or disk-full error (including
37232 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
37233 **    difficult to be sure that the in-memory pager state (cache contents, 
37234 **    db size etc.) are consistent with the contents of the file-system.
37235 **
37236 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37237 **    cannot.
37238 **
37239 **    For example, if an IO error occurs while performing a rollback, 
37240 **    the contents of the page-cache may be left in an inconsistent state.
37241 **    At this point it would be dangerous to change back to READER state
37242 **    (as usually happens after a rollback). Any subsequent readers might
37243 **    report database corruption (due to the inconsistent cache), and if
37244 **    they upgrade to writers, they may inadvertently corrupt the database
37245 **    file. To avoid this hazard, the pager switches into the ERROR state
37246 **    instead of READER following such an error.
37247 **
37248 **    Once it has entered the ERROR state, any attempt to use the pager
37249 **    to read or write data returns an error. Eventually, once all 
37250 **    outstanding transactions have been abandoned, the pager is able to
37251 **    transition back to OPEN state, discarding the contents of the 
37252 **    page-cache and any other in-memory state at the same time. Everything
37253 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37254 **    when a read-transaction is next opened on the pager (transitioning
37255 **    the pager into READER state). At that point the system has recovered 
37256 **    from the error.
37257 **
37258 **    Specifically, the pager jumps into the ERROR state if:
37259 **
37260 **      1. An error occurs while attempting a rollback. This happens in
37261 **         function sqlite3PagerRollback().
37262 **
37263 **      2. An error occurs while attempting to finalize a journal file
37264 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37265 **
37266 **      3. An error occurs while attempting to write to the journal or
37267 **         database file in function pagerStress() in order to free up
37268 **         memory.
37269 **
37270 **    In other cases, the error is returned to the b-tree layer. The b-tree
37271 **    layer then attempts a rollback operation. If the error condition 
37272 **    persists, the pager enters the ERROR state via condition (1) above.
37273 **
37274 **    Condition (3) is necessary because it can be triggered by a read-only
37275 **    statement executed within a transaction. In this case, if the error
37276 **    code were simply returned to the user, the b-tree layer would not
37277 **    automatically attempt a rollback, as it assumes that an error in a
37278 **    read-only statement cannot leave the pager in an internally inconsistent 
37279 **    state.
37280 **
37281 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37282 **    * There are one or more outstanding references to pages (after the
37283 **      last reference is dropped the pager should move back to OPEN state).
37284 **    * The pager is not an in-memory pager.
37285 **    
37286 **
37287 ** Notes:
37288 **
37289 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37290 **     connection is open in WAL mode. A WAL connection is always in one
37291 **     of the first four states.
37292 **
37293 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37294 **     state. There are two exceptions: immediately after exclusive-mode has
37295 **     been turned on (and before any read or write transactions are 
37296 **     executed), and when the pager is leaving the "error state".
37297 **
37298 **   * See also: assert_pager_state().
37299 */
37300 #define PAGER_OPEN                  0
37301 #define PAGER_READER                1
37302 #define PAGER_WRITER_LOCKED         2
37303 #define PAGER_WRITER_CACHEMOD       3
37304 #define PAGER_WRITER_DBMOD          4
37305 #define PAGER_WRITER_FINISHED       5
37306 #define PAGER_ERROR                 6
37307
37308 /*
37309 ** The Pager.eLock variable is almost always set to one of the 
37310 ** following locking-states, according to the lock currently held on
37311 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37312 ** This variable is kept up to date as locks are taken and released by
37313 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37314 **
37315 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37316 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37317 ** the operation was successful. In these circumstances pagerLockDb() and
37318 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37319 ** when unlocking the file, and only updated when locking the file if the
37320 ** VFS call is successful. This way, the Pager.eLock variable may be set
37321 ** to a less exclusive (lower) value than the lock that is actually held
37322 ** at the system level, but it is never set to a more exclusive value.
37323 **
37324 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
37325 ** be a few redundant xLock() calls or a lock may be held for longer than
37326 ** required, but nothing really goes wrong.
37327 **
37328 ** The exception is when the database file is unlocked as the pager moves
37329 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
37330 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37331 ** transition, by the same pager or any other). If the call to xUnlock()
37332 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37333 ** can confuse the call to xCheckReservedLock() call made later as part
37334 ** of hot-journal detection.
37335 **
37336 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
37337 ** lock held by this process or any others". So xCheckReservedLock may 
37338 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37339 ** doesn't know it because of a previous error in xUnlock). If this happens
37340 ** a hot-journal may be mistaken for a journal being created by an active
37341 ** transaction in another process, causing SQLite to read from the database
37342 ** without rolling it back.
37343 **
37344 ** To work around this, if a call to xUnlock() fails when unlocking the
37345 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37346 ** is only changed back to a real locking state after a successful call
37347 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37348 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
37349 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37350 ** lock on the database file before attempting to roll it back. See function
37351 ** PagerSharedLock() for more detail.
37352 **
37353 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
37354 ** PAGER_OPEN state.
37355 */
37356 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37357
37358 /*
37359 ** A macro used for invoking the codec if there is one
37360 */
37361 #ifdef SQLITE_HAS_CODEC
37362 # define CODEC1(P,D,N,X,E) \
37363     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37364 # define CODEC2(P,D,N,X,E,O) \
37365     if( P->xCodec==0 ){ O=(char*)D; }else \
37366     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37367 #else
37368 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37369 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37370 #endif
37371
37372 /*
37373 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
37374 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37375 ** This could conceivably cause corruption following a power failure on
37376 ** such a system. This is currently an undocumented limit.
37377 */
37378 #define MAX_SECTOR_SIZE 0x10000
37379
37380 /*
37381 ** An instance of the following structure is allocated for each active
37382 ** savepoint and statement transaction in the system. All such structures
37383 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37384 ** resized using sqlite3Realloc().
37385 **
37386 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37387 ** set to 0. If a journal-header is written into the main journal while
37388 ** the savepoint is active, then iHdrOffset is set to the byte offset 
37389 ** immediately following the last journal record written into the main
37390 ** journal before the journal-header. This is required during savepoint
37391 ** rollback (see pagerPlaybackSavepoint()).
37392 */
37393 typedef struct PagerSavepoint PagerSavepoint;
37394 struct PagerSavepoint {
37395   i64 iOffset;                 /* Starting offset in main journal */
37396   i64 iHdrOffset;              /* See above */
37397   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37398   Pgno nOrig;                  /* Original number of pages in file */
37399   Pgno iSubRec;                /* Index of first record in sub-journal */
37400 #ifndef SQLITE_OMIT_WAL
37401   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37402 #endif
37403 };
37404
37405 /*
37406 ** A open page cache is an instance of struct Pager. A description of
37407 ** some of the more important member variables follows:
37408 **
37409 ** eState
37410 **
37411 **   The current 'state' of the pager object. See the comment and state
37412 **   diagram above for a description of the pager state.
37413 **
37414 ** eLock
37415 **
37416 **   For a real on-disk database, the current lock held on the database file -
37417 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37418 **
37419 **   For a temporary or in-memory database (neither of which require any
37420 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37421 **   databases always have Pager.exclusiveMode==1, this tricks the pager
37422 **   logic into thinking that it already has all the locks it will ever
37423 **   need (and no reason to release them).
37424 **
37425 **   In some (obscure) circumstances, this variable may also be set to
37426 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37427 **   details.
37428 **
37429 ** changeCountDone
37430 **
37431 **   This boolean variable is used to make sure that the change-counter 
37432 **   (the 4-byte header field at byte offset 24 of the database file) is 
37433 **   not updated more often than necessary. 
37434 **
37435 **   It is set to true when the change-counter field is updated, which 
37436 **   can only happen if an exclusive lock is held on the database file.
37437 **   It is cleared (set to false) whenever an exclusive lock is 
37438 **   relinquished on the database file. Each time a transaction is committed,
37439 **   The changeCountDone flag is inspected. If it is true, the work of
37440 **   updating the change-counter is omitted for the current transaction.
37441 **
37442 **   This mechanism means that when running in exclusive mode, a connection 
37443 **   need only update the change-counter once, for the first transaction
37444 **   committed.
37445 **
37446 ** setMaster
37447 **
37448 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
37449 **   (or may not) specify a master-journal name to be written into the 
37450 **   journal file before it is synced to disk.
37451 **
37452 **   Whether or not a journal file contains a master-journal pointer affects 
37453 **   the way in which the journal file is finalized after the transaction is 
37454 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
37455 **   If a journal file does not contain a master-journal pointer, it is
37456 **   finalized by overwriting the first journal header with zeroes. If
37457 **   it does contain a master-journal pointer the journal file is finalized 
37458 **   by truncating it to zero bytes, just as if the connection were 
37459 **   running in "journal_mode=truncate" mode.
37460 **
37461 **   Journal files that contain master journal pointers cannot be finalized
37462 **   simply by overwriting the first journal-header with zeroes, as the
37463 **   master journal pointer could interfere with hot-journal rollback of any
37464 **   subsequently interrupted transaction that reuses the journal file.
37465 **
37466 **   The flag is cleared as soon as the journal file is finalized (either
37467 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37468 **   journal file from being successfully finalized, the setMaster flag
37469 **   is cleared anyway (and the pager will move to ERROR state).
37470 **
37471 ** doNotSpill, doNotSyncSpill
37472 **
37473 **   These two boolean variables control the behaviour of cache-spills
37474 **   (calls made by the pcache module to the pagerStress() routine to
37475 **   write cached data to the file-system in order to free up memory).
37476 **
37477 **   When doNotSpill is non-zero, writing to the database from pagerStress()
37478 **   is disabled altogether. This is done in a very obscure case that
37479 **   comes up during savepoint rollback that requires the pcache module
37480 **   to allocate a new page to prevent the journal file from being written
37481 **   while it is being traversed by code in pager_playback().
37482 ** 
37483 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37484 **   is permitted, but syncing the journal file is not. This flag is set
37485 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
37486 **   the database page-size in order to prevent a journal sync from happening 
37487 **   in between the journalling of two pages on the same sector. 
37488 **
37489 ** subjInMemory
37490 **
37491 **   This is a boolean variable. If true, then any required sub-journal
37492 **   is opened as an in-memory journal file. If false, then in-memory
37493 **   sub-journals are only used for in-memory pager files.
37494 **
37495 **   This variable is updated by the upper layer each time a new 
37496 **   write-transaction is opened.
37497 **
37498 ** dbSize, dbOrigSize, dbFileSize
37499 **
37500 **   Variable dbSize is set to the number of pages in the database file.
37501 **   It is valid in PAGER_READER and higher states (all states except for
37502 **   OPEN and ERROR). 
37503 **
37504 **   dbSize is set based on the size of the database file, which may be 
37505 **   larger than the size of the database (the value stored at offset
37506 **   28 of the database header by the btree). If the size of the file
37507 **   is not an integer multiple of the page-size, the value stored in
37508 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37509 **   Except, any file that is greater than 0 bytes in size is considered
37510 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
37511 **   to dbSize==1).
37512 **
37513 **   During a write-transaction, if pages with page-numbers greater than
37514 **   dbSize are modified in the cache, dbSize is updated accordingly.
37515 **   Similarly, if the database is truncated using PagerTruncateImage(), 
37516 **   dbSize is updated.
37517 **
37518 **   Variables dbOrigSize and dbFileSize are valid in states 
37519 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37520 **   variable at the start of the transaction. It is used during rollback,
37521 **   and to determine whether or not pages need to be journalled before
37522 **   being modified.
37523 **
37524 **   Throughout a write-transaction, dbFileSize contains the size of
37525 **   the file on disk in pages. It is set to a copy of dbSize when the
37526 **   write-transaction is first opened, and updated when VFS calls are made
37527 **   to write or truncate the database file on disk. 
37528 **
37529 **   The only reason the dbFileSize variable is required is to suppress 
37530 **   unnecessary calls to xTruncate() after committing a transaction. If, 
37531 **   when a transaction is committed, the dbFileSize variable indicates 
37532 **   that the database file is larger than the database image (Pager.dbSize), 
37533 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37534 **   to measure the database file on disk, and then truncates it if required.
37535 **   dbFileSize is not used when rolling back a transaction. In this case
37536 **   pager_truncate() is called unconditionally (which means there may be
37537 **   a call to xFilesize() that is not strictly required). In either case,
37538 **   pager_truncate() may cause the file to become smaller or larger.
37539 **
37540 ** dbHintSize
37541 **
37542 **   The dbHintSize variable is used to limit the number of calls made to
37543 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
37544 **
37545 **   dbHintSize is set to a copy of the dbSize variable when a
37546 **   write-transaction is opened (at the same time as dbFileSize and
37547 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37548 **   dbHintSize is increased to the number of pages that correspond to the
37549 **   size-hint passed to the method call. See pager_write_pagelist() for 
37550 **   details.
37551 **
37552 ** errCode
37553 **
37554 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37555 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
37556 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
37557 **   sub-codes.
37558 */
37559 struct Pager {
37560   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37561   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37562   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
37563   u8 useJournal;              /* Use a rollback journal on this file */
37564   u8 noSync;                  /* Do not sync the journal if true */
37565   u8 fullSync;                /* Do extra syncs of the journal for robustness */
37566   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37567   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
37568   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
37569   u8 tempFile;                /* zFilename is a temporary file */
37570   u8 readOnly;                /* True for a read-only database */
37571   u8 memDb;                   /* True to inhibit all file I/O */
37572
37573   /**************************************************************************
37574   ** The following block contains those class members that change during
37575   ** routine opertion.  Class members not in this block are either fixed
37576   ** when the pager is first created or else only change when there is a
37577   ** significant mode change (such as changing the page_size, locking_mode,
37578   ** or the journal_mode).  From another view, these class members describe
37579   ** the "state" of the pager, while other class members describe the
37580   ** "configuration" of the pager.
37581   */
37582   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37583   u8 eLock;                   /* Current lock held on database file */
37584   u8 changeCountDone;         /* Set after incrementing the change-counter */
37585   u8 setMaster;               /* True if a m-j name has been written to jrnl */
37586   u8 doNotSpill;              /* Do not spill the cache when non-zero */
37587   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
37588   u8 subjInMemory;            /* True to use in-memory sub-journals */
37589   Pgno dbSize;                /* Number of pages in the database */
37590   Pgno dbOrigSize;            /* dbSize before the current transaction */
37591   Pgno dbFileSize;            /* Number of pages in the database file */
37592   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
37593   int errCode;                /* One of several kinds of errors */
37594   int nRec;                   /* Pages journalled since last j-header written */
37595   u32 cksumInit;              /* Quasi-random value added to every checksum */
37596   u32 nSubRec;                /* Number of records written to sub-journal */
37597   Bitvec *pInJournal;         /* One bit for each page in the database file */
37598   sqlite3_file *fd;           /* File descriptor for database */
37599   sqlite3_file *jfd;          /* File descriptor for main journal */
37600   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
37601   i64 journalOff;             /* Current write offset in the journal file */
37602   i64 journalHdr;             /* Byte offset to previous journal header */
37603   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
37604   PagerSavepoint *aSavepoint; /* Array of active savepoints */
37605   int nSavepoint;             /* Number of elements in aSavepoint[] */
37606   char dbFileVers[16];        /* Changes whenever database file changes */
37607   /*
37608   ** End of the routinely-changing class members
37609   ***************************************************************************/
37610
37611   u16 nExtra;                 /* Add this many bytes to each in-memory page */
37612   i16 nReserve;               /* Number of unused bytes at end of each page */
37613   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37614   u32 sectorSize;             /* Assumed sector size during rollback */
37615   int pageSize;               /* Number of bytes in a page */
37616   Pgno mxPgno;                /* Maximum allowed size of the database */
37617   i64 journalSizeLimit;       /* Size limit for persistent journal files */
37618   char *zFilename;            /* Name of the database file */
37619   char *zJournal;             /* Name of the journal file */
37620   int (*xBusyHandler)(void*); /* Function to call when busy */
37621   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37622   int aStat[3];               /* Total cache hits, misses and writes */
37623 #ifdef SQLITE_TEST
37624   int nRead;                  /* Database pages read */
37625 #endif
37626   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37627 #ifdef SQLITE_HAS_CODEC
37628   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37629   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37630   void (*xCodecFree)(void*);             /* Destructor for the codec */
37631   void *pCodec;               /* First argument to xCodec... methods */
37632 #endif
37633   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
37634   PCache *pPCache;            /* Pointer to page cache object */
37635 #ifndef SQLITE_OMIT_WAL
37636   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
37637   char *zWal;                 /* File name for write-ahead log */
37638 #endif
37639 };
37640
37641 /*
37642 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
37643 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
37644 ** or CACHE_WRITE to sqlite3_db_status().
37645 */
37646 #define PAGER_STAT_HIT   0
37647 #define PAGER_STAT_MISS  1
37648 #define PAGER_STAT_WRITE 2
37649
37650 /*
37651 ** The following global variables hold counters used for
37652 ** testing purposes only.  These variables do not exist in
37653 ** a non-testing build.  These variables are not thread-safe.
37654 */
37655 #ifdef SQLITE_TEST
37656 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
37657 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
37658 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
37659 # define PAGER_INCR(v)  v++
37660 #else
37661 # define PAGER_INCR(v)
37662 #endif
37663
37664
37665
37666 /*
37667 ** Journal files begin with the following magic string.  The data
37668 ** was obtained from /dev/random.  It is used only as a sanity check.
37669 **
37670 ** Since version 2.8.0, the journal format contains additional sanity
37671 ** checking information.  If the power fails while the journal is being
37672 ** written, semi-random garbage data might appear in the journal
37673 ** file after power is restored.  If an attempt is then made
37674 ** to roll the journal back, the database could be corrupted.  The additional
37675 ** sanity checking data is an attempt to discover the garbage in the
37676 ** journal and ignore it.
37677 **
37678 ** The sanity checking information for the new journal format consists
37679 ** of a 32-bit checksum on each page of data.  The checksum covers both
37680 ** the page number and the pPager->pageSize bytes of data for the page.
37681 ** This cksum is initialized to a 32-bit random value that appears in the
37682 ** journal file right after the header.  The random initializer is important,
37683 ** because garbage data that appears at the end of a journal is likely
37684 ** data that was once in other files that have now been deleted.  If the
37685 ** garbage data came from an obsolete journal file, the checksums might
37686 ** be correct.  But by initializing the checksum to random value which
37687 ** is different for every journal, we minimize that risk.
37688 */
37689 static const unsigned char aJournalMagic[] = {
37690   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37691 };
37692
37693 /*
37694 ** The size of the of each page record in the journal is given by
37695 ** the following macro.
37696 */
37697 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
37698
37699 /*
37700 ** The journal header size for this pager. This is usually the same 
37701 ** size as a single disk sector. See also setSectorSize().
37702 */
37703 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37704
37705 /*
37706 ** The macro MEMDB is true if we are dealing with an in-memory database.
37707 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37708 ** the value of MEMDB will be a constant and the compiler will optimize
37709 ** out code that would never execute.
37710 */
37711 #ifdef SQLITE_OMIT_MEMORYDB
37712 # define MEMDB 0
37713 #else
37714 # define MEMDB pPager->memDb
37715 #endif
37716
37717 /*
37718 ** The maximum legal page number is (2^31 - 1).
37719 */
37720 #define PAGER_MAX_PGNO 2147483647
37721
37722 /*
37723 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37724 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37725 **
37726 ** This is so that expressions can be written as:
37727 **
37728 **   if( isOpen(pPager->jfd) ){ ...
37729 **
37730 ** instead of
37731 **
37732 **   if( pPager->jfd->pMethods ){ ...
37733 */
37734 #define isOpen(pFd) ((pFd)->pMethods)
37735
37736 /*
37737 ** Return true if this pager uses a write-ahead log instead of the usual
37738 ** rollback journal. Otherwise false.
37739 */
37740 #ifndef SQLITE_OMIT_WAL
37741 static int pagerUseWal(Pager *pPager){
37742   return (pPager->pWal!=0);
37743 }
37744 #else
37745 # define pagerUseWal(x) 0
37746 # define pagerRollbackWal(x) 0
37747 # define pagerWalFrames(v,w,x,y) 0
37748 # define pagerOpenWalIfPresent(z) SQLITE_OK
37749 # define pagerBeginReadTransaction(z) SQLITE_OK
37750 #endif
37751
37752 #ifndef NDEBUG 
37753 /*
37754 ** Usage:
37755 **
37756 **   assert( assert_pager_state(pPager) );
37757 **
37758 ** This function runs many asserts to try to find inconsistencies in
37759 ** the internal state of the Pager object.
37760 */
37761 static int assert_pager_state(Pager *p){
37762   Pager *pPager = p;
37763
37764   /* State must be valid. */
37765   assert( p->eState==PAGER_OPEN
37766        || p->eState==PAGER_READER
37767        || p->eState==PAGER_WRITER_LOCKED
37768        || p->eState==PAGER_WRITER_CACHEMOD
37769        || p->eState==PAGER_WRITER_DBMOD
37770        || p->eState==PAGER_WRITER_FINISHED
37771        || p->eState==PAGER_ERROR
37772   );
37773
37774   /* Regardless of the current state, a temp-file connection always behaves
37775   ** as if it has an exclusive lock on the database file. It never updates
37776   ** the change-counter field, so the changeCountDone flag is always set.
37777   */
37778   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37779   assert( p->tempFile==0 || pPager->changeCountDone );
37780
37781   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
37782   ** And if the journal-mode is "OFF", the journal file must not be open.
37783   */
37784   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37785   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37786
37787   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
37788   ** this means an in-memory pager performs no IO at all, it cannot encounter 
37789   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
37790   ** a journal file. (although the in-memory journal implementation may 
37791   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
37792   ** is therefore not possible for an in-memory pager to enter the ERROR 
37793   ** state.
37794   */
37795   if( MEMDB ){
37796     assert( p->noSync );
37797     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
37798          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
37799     );
37800     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37801     assert( pagerUseWal(p)==0 );
37802   }
37803
37804   /* If changeCountDone is set, a RESERVED lock or greater must be held
37805   ** on the file.
37806   */
37807   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37808   assert( p->eLock!=PENDING_LOCK );
37809
37810   switch( p->eState ){
37811     case PAGER_OPEN:
37812       assert( !MEMDB );
37813       assert( pPager->errCode==SQLITE_OK );
37814       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37815       break;
37816
37817     case PAGER_READER:
37818       assert( pPager->errCode==SQLITE_OK );
37819       assert( p->eLock!=UNKNOWN_LOCK );
37820       assert( p->eLock>=SHARED_LOCK );
37821       break;
37822
37823     case PAGER_WRITER_LOCKED:
37824       assert( p->eLock!=UNKNOWN_LOCK );
37825       assert( pPager->errCode==SQLITE_OK );
37826       if( !pagerUseWal(pPager) ){
37827         assert( p->eLock>=RESERVED_LOCK );
37828       }
37829       assert( pPager->dbSize==pPager->dbOrigSize );
37830       assert( pPager->dbOrigSize==pPager->dbFileSize );
37831       assert( pPager->dbOrigSize==pPager->dbHintSize );
37832       assert( pPager->setMaster==0 );
37833       break;
37834
37835     case PAGER_WRITER_CACHEMOD:
37836       assert( p->eLock!=UNKNOWN_LOCK );
37837       assert( pPager->errCode==SQLITE_OK );
37838       if( !pagerUseWal(pPager) ){
37839         /* It is possible that if journal_mode=wal here that neither the
37840         ** journal file nor the WAL file are open. This happens during
37841         ** a rollback transaction that switches from journal_mode=off
37842         ** to journal_mode=wal.
37843         */
37844         assert( p->eLock>=RESERVED_LOCK );
37845         assert( isOpen(p->jfd) 
37846              || p->journalMode==PAGER_JOURNALMODE_OFF 
37847              || p->journalMode==PAGER_JOURNALMODE_WAL 
37848         );
37849       }
37850       assert( pPager->dbOrigSize==pPager->dbFileSize );
37851       assert( pPager->dbOrigSize==pPager->dbHintSize );
37852       break;
37853
37854     case PAGER_WRITER_DBMOD:
37855       assert( p->eLock==EXCLUSIVE_LOCK );
37856       assert( pPager->errCode==SQLITE_OK );
37857       assert( !pagerUseWal(pPager) );
37858       assert( p->eLock>=EXCLUSIVE_LOCK );
37859       assert( isOpen(p->jfd) 
37860            || p->journalMode==PAGER_JOURNALMODE_OFF 
37861            || p->journalMode==PAGER_JOURNALMODE_WAL 
37862       );
37863       assert( pPager->dbOrigSize<=pPager->dbHintSize );
37864       break;
37865
37866     case PAGER_WRITER_FINISHED:
37867       assert( p->eLock==EXCLUSIVE_LOCK );
37868       assert( pPager->errCode==SQLITE_OK );
37869       assert( !pagerUseWal(pPager) );
37870       assert( isOpen(p->jfd) 
37871            || p->journalMode==PAGER_JOURNALMODE_OFF 
37872            || p->journalMode==PAGER_JOURNALMODE_WAL 
37873       );
37874       break;
37875
37876     case PAGER_ERROR:
37877       /* There must be at least one outstanding reference to the pager if
37878       ** in ERROR state. Otherwise the pager should have already dropped
37879       ** back to OPEN state.
37880       */
37881       assert( pPager->errCode!=SQLITE_OK );
37882       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37883       break;
37884   }
37885
37886   return 1;
37887 }
37888 #endif /* ifndef NDEBUG */
37889
37890 #ifdef SQLITE_DEBUG 
37891 /*
37892 ** Return a pointer to a human readable string in a static buffer
37893 ** containing the state of the Pager object passed as an argument. This
37894 ** is intended to be used within debuggers. For example, as an alternative
37895 ** to "print *pPager" in gdb:
37896 **
37897 ** (gdb) printf "%s", print_pager_state(pPager)
37898 */
37899 static char *print_pager_state(Pager *p){
37900   static char zRet[1024];
37901
37902   sqlite3_snprintf(1024, zRet,
37903       "Filename:      %s\n"
37904       "State:         %s errCode=%d\n"
37905       "Lock:          %s\n"
37906       "Locking mode:  locking_mode=%s\n"
37907       "Journal mode:  journal_mode=%s\n"
37908       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37909       "Journal:       journalOff=%lld journalHdr=%lld\n"
37910       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37911       , p->zFilename
37912       , p->eState==PAGER_OPEN            ? "OPEN" :
37913         p->eState==PAGER_READER          ? "READER" :
37914         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
37915         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37916         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
37917         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37918         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
37919       , (int)p->errCode
37920       , p->eLock==NO_LOCK         ? "NO_LOCK" :
37921         p->eLock==RESERVED_LOCK   ? "RESERVED" :
37922         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
37923         p->eLock==SHARED_LOCK     ? "SHARED" :
37924         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
37925       , p->exclusiveMode ? "exclusive" : "normal"
37926       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
37927         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
37928         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
37929         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
37930         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37931         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
37932       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37933       , p->journalOff, p->journalHdr
37934       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37935   );
37936
37937   return zRet;
37938 }
37939 #endif
37940
37941 /*
37942 ** Return true if it is necessary to write page *pPg into the sub-journal.
37943 ** A page needs to be written into the sub-journal if there exists one
37944 ** or more open savepoints for which:
37945 **
37946 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
37947 **   * The bit corresponding to the page-number is not set in
37948 **     PagerSavepoint.pInSavepoint.
37949 */
37950 static int subjRequiresPage(PgHdr *pPg){
37951   Pgno pgno = pPg->pgno;
37952   Pager *pPager = pPg->pPager;
37953   int i;
37954   for(i=0; i<pPager->nSavepoint; i++){
37955     PagerSavepoint *p = &pPager->aSavepoint[i];
37956     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37957       return 1;
37958     }
37959   }
37960   return 0;
37961 }
37962
37963 /*
37964 ** Return true if the page is already in the journal file.
37965 */
37966 static int pageInJournal(PgHdr *pPg){
37967   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37968 }
37969
37970 /*
37971 ** Read a 32-bit integer from the given file descriptor.  Store the integer
37972 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
37973 ** error code is something goes wrong.
37974 **
37975 ** All values are stored on disk as big-endian.
37976 */
37977 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37978   unsigned char ac[4];
37979   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37980   if( rc==SQLITE_OK ){
37981     *pRes = sqlite3Get4byte(ac);
37982   }
37983   return rc;
37984 }
37985
37986 /*
37987 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37988 */
37989 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
37990
37991
37992 /*
37993 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
37994 ** on success or an error code is something goes wrong.
37995 */
37996 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37997   char ac[4];
37998   put32bits(ac, val);
37999   return sqlite3OsWrite(fd, ac, 4, offset);
38000 }
38001
38002 /*
38003 ** Unlock the database file to level eLock, which must be either NO_LOCK
38004 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38005 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38006 **
38007 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38008 ** called, do not modify it. See the comment above the #define of 
38009 ** UNKNOWN_LOCK for an explanation of this.
38010 */
38011 static int pagerUnlockDb(Pager *pPager, int eLock){
38012   int rc = SQLITE_OK;
38013
38014   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38015   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38016   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38017   if( isOpen(pPager->fd) ){
38018     assert( pPager->eLock>=eLock );
38019     rc = sqlite3OsUnlock(pPager->fd, eLock);
38020     if( pPager->eLock!=UNKNOWN_LOCK ){
38021       pPager->eLock = (u8)eLock;
38022     }
38023     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38024   }
38025   return rc;
38026 }
38027
38028 /*
38029 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38030 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38031 ** Pager.eLock variable to the new locking state. 
38032 **
38033 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
38034 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
38035 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
38036 ** of this.
38037 */
38038 static int pagerLockDb(Pager *pPager, int eLock){
38039   int rc = SQLITE_OK;
38040
38041   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38042   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38043     rc = sqlite3OsLock(pPager->fd, eLock);
38044     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38045       pPager->eLock = (u8)eLock;
38046       IOTRACE(("LOCK %p %d\n", pPager, eLock))
38047     }
38048   }
38049   return rc;
38050 }
38051
38052 /*
38053 ** This function determines whether or not the atomic-write optimization
38054 ** can be used with this pager. The optimization can be used if:
38055 **
38056 **  (a) the value returned by OsDeviceCharacteristics() indicates that
38057 **      a database page may be written atomically, and
38058 **  (b) the value returned by OsSectorSize() is less than or equal
38059 **      to the page size.
38060 **
38061 ** The optimization is also always enabled for temporary files. It is
38062 ** an error to call this function if pPager is opened on an in-memory
38063 ** database.
38064 **
38065 ** If the optimization cannot be used, 0 is returned. If it can be used,
38066 ** then the value returned is the size of the journal file when it
38067 ** contains rollback data for exactly one page.
38068 */
38069 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38070 static int jrnlBufferSize(Pager *pPager){
38071   assert( !MEMDB );
38072   if( !pPager->tempFile ){
38073     int dc;                           /* Device characteristics */
38074     int nSector;                      /* Sector size */
38075     int szPage;                       /* Page size */
38076
38077     assert( isOpen(pPager->fd) );
38078     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38079     nSector = pPager->sectorSize;
38080     szPage = pPager->pageSize;
38081
38082     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38083     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38084     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38085       return 0;
38086     }
38087   }
38088
38089   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38090 }
38091 #endif
38092
38093 /*
38094 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38095 ** on the cache using a hash function.  This is used for testing
38096 ** and debugging only.
38097 */
38098 #ifdef SQLITE_CHECK_PAGES
38099 /*
38100 ** Return a 32-bit hash of the page data for pPage.
38101 */
38102 static u32 pager_datahash(int nByte, unsigned char *pData){
38103   u32 hash = 0;
38104   int i;
38105   for(i=0; i<nByte; i++){
38106     hash = (hash*1039) + pData[i];
38107   }
38108   return hash;
38109 }
38110 static u32 pager_pagehash(PgHdr *pPage){
38111   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38112 }
38113 static void pager_set_pagehash(PgHdr *pPage){
38114   pPage->pageHash = pager_pagehash(pPage);
38115 }
38116
38117 /*
38118 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38119 ** is defined, and NDEBUG is not defined, an assert() statement checks
38120 ** that the page is either dirty or still matches the calculated page-hash.
38121 */
38122 #define CHECK_PAGE(x) checkPage(x)
38123 static void checkPage(PgHdr *pPg){
38124   Pager *pPager = pPg->pPager;
38125   assert( pPager->eState!=PAGER_ERROR );
38126   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38127 }
38128
38129 #else
38130 #define pager_datahash(X,Y)  0
38131 #define pager_pagehash(X)  0
38132 #define pager_set_pagehash(X)
38133 #define CHECK_PAGE(x)
38134 #endif  /* SQLITE_CHECK_PAGES */
38135
38136 /*
38137 ** When this is called the journal file for pager pPager must be open.
38138 ** This function attempts to read a master journal file name from the 
38139 ** end of the file and, if successful, copies it into memory supplied 
38140 ** by the caller. See comments above writeMasterJournal() for the format
38141 ** used to store a master journal file name at the end of a journal file.
38142 **
38143 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38144 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38145 ** enough space to write the master journal name). If the master journal
38146 ** name in the journal is longer than nMaster bytes (including a
38147 ** nul-terminator), then this is handled as if no master journal name
38148 ** were present in the journal.
38149 **
38150 ** If a master journal file name is present at the end of the journal
38151 ** file, then it is copied into the buffer pointed to by zMaster. A
38152 ** nul-terminator byte is appended to the buffer following the master
38153 ** journal file name.
38154 **
38155 ** If it is determined that no master journal file name is present 
38156 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38157 **
38158 ** If an error occurs while reading from the journal file, an SQLite
38159 ** error code is returned.
38160 */
38161 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38162   int rc;                    /* Return code */
38163   u32 len;                   /* Length in bytes of master journal name */
38164   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
38165   u32 cksum;                 /* MJ checksum value read from journal */
38166   u32 u;                     /* Unsigned loop counter */
38167   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38168   zMaster[0] = '\0';
38169
38170   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38171    || szJ<16
38172    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38173    || len>=nMaster 
38174    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38175    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38176    || memcmp(aMagic, aJournalMagic, 8)
38177    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38178   ){
38179     return rc;
38180   }
38181
38182   /* See if the checksum matches the master journal name */
38183   for(u=0; u<len; u++){
38184     cksum -= zMaster[u];
38185   }
38186   if( cksum ){
38187     /* If the checksum doesn't add up, then one or more of the disk sectors
38188     ** containing the master journal filename is corrupted. This means
38189     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38190     ** master-journal filename.
38191     */
38192     len = 0;
38193   }
38194   zMaster[len] = '\0';
38195    
38196   return SQLITE_OK;
38197 }
38198
38199 /*
38200 ** Return the offset of the sector boundary at or immediately 
38201 ** following the value in pPager->journalOff, assuming a sector 
38202 ** size of pPager->sectorSize bytes.
38203 **
38204 ** i.e for a sector size of 512:
38205 **
38206 **   Pager.journalOff          Return value
38207 **   ---------------------------------------
38208 **   0                         0
38209 **   512                       512
38210 **   100                       512
38211 **   2000                      2048
38212 ** 
38213 */
38214 static i64 journalHdrOffset(Pager *pPager){
38215   i64 offset = 0;
38216   i64 c = pPager->journalOff;
38217   if( c ){
38218     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38219   }
38220   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38221   assert( offset>=c );
38222   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38223   return offset;
38224 }
38225
38226 /*
38227 ** The journal file must be open when this function is called.
38228 **
38229 ** This function is a no-op if the journal file has not been written to
38230 ** within the current transaction (i.e. if Pager.journalOff==0).
38231 **
38232 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38233 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38234 ** zero the 28-byte header at the start of the journal file. In either case, 
38235 ** if the pager is not in no-sync mode, sync the journal file immediately 
38236 ** after writing or truncating it.
38237 **
38238 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38239 ** following the truncation or zeroing described above the size of the 
38240 ** journal file in bytes is larger than this value, then truncate the
38241 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38242 ** not need to be synced following this operation.
38243 **
38244 ** If an IO error occurs, abandon processing and return the IO error code.
38245 ** Otherwise, return SQLITE_OK.
38246 */
38247 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38248   int rc = SQLITE_OK;                               /* Return code */
38249   assert( isOpen(pPager->jfd) );
38250   if( pPager->journalOff ){
38251     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38252
38253     IOTRACE(("JZEROHDR %p\n", pPager))
38254     if( doTruncate || iLimit==0 ){
38255       rc = sqlite3OsTruncate(pPager->jfd, 0);
38256     }else{
38257       static const char zeroHdr[28] = {0};
38258       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38259     }
38260     if( rc==SQLITE_OK && !pPager->noSync ){
38261       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38262     }
38263
38264     /* At this point the transaction is committed but the write lock 
38265     ** is still held on the file. If there is a size limit configured for 
38266     ** the persistent journal and the journal file currently consumes more
38267     ** space than that limit allows for, truncate it now. There is no need
38268     ** to sync the file following this operation.
38269     */
38270     if( rc==SQLITE_OK && iLimit>0 ){
38271       i64 sz;
38272       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38273       if( rc==SQLITE_OK && sz>iLimit ){
38274         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38275       }
38276     }
38277   }
38278   return rc;
38279 }
38280
38281 /*
38282 ** The journal file must be open when this routine is called. A journal
38283 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38284 ** current location.
38285 **
38286 ** The format for the journal header is as follows:
38287 ** - 8 bytes: Magic identifying journal format.
38288 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38289 ** - 4 bytes: Random number used for page hash.
38290 ** - 4 bytes: Initial database page count.
38291 ** - 4 bytes: Sector size used by the process that wrote this journal.
38292 ** - 4 bytes: Database page size.
38293 ** 
38294 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38295 */
38296 static int writeJournalHdr(Pager *pPager){
38297   int rc = SQLITE_OK;                 /* Return code */
38298   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38299   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38300   u32 nWrite;                         /* Bytes of header sector written */
38301   int ii;                             /* Loop counter */
38302
38303   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38304
38305   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38306     nHeader = JOURNAL_HDR_SZ(pPager);
38307   }
38308
38309   /* If there are active savepoints and any of them were created 
38310   ** since the most recent journal header was written, update the 
38311   ** PagerSavepoint.iHdrOffset fields now.
38312   */
38313   for(ii=0; ii<pPager->nSavepoint; ii++){
38314     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38315       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38316     }
38317   }
38318
38319   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38320
38321   /* 
38322   ** Write the nRec Field - the number of page records that follow this
38323   ** journal header. Normally, zero is written to this value at this time.
38324   ** After the records are added to the journal (and the journal synced, 
38325   ** if in full-sync mode), the zero is overwritten with the true number
38326   ** of records (see syncJournal()).
38327   **
38328   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38329   ** reading the journal this value tells SQLite to assume that the
38330   ** rest of the journal file contains valid page records. This assumption
38331   ** is dangerous, as if a failure occurred whilst writing to the journal
38332   ** file it may contain some garbage data. There are two scenarios
38333   ** where this risk can be ignored:
38334   **
38335   **   * When the pager is in no-sync mode. Corruption can follow a
38336   **     power failure in this case anyway.
38337   **
38338   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38339   **     that garbage data is never appended to the journal file.
38340   */
38341   assert( isOpen(pPager->fd) || pPager->noSync );
38342   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38343    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
38344   ){
38345     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38346     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38347   }else{
38348     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38349   }
38350
38351   /* The random check-hash initialiser */ 
38352   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38353   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38354   /* The initial database size */
38355   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38356   /* The assumed sector size for this process */
38357   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38358
38359   /* The page size */
38360   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38361
38362   /* Initializing the tail of the buffer is not necessary.  Everything
38363   ** works find if the following memset() is omitted.  But initializing
38364   ** the memory prevents valgrind from complaining, so we are willing to
38365   ** take the performance hit.
38366   */
38367   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38368          nHeader-(sizeof(aJournalMagic)+20));
38369
38370   /* In theory, it is only necessary to write the 28 bytes that the 
38371   ** journal header consumes to the journal file here. Then increment the 
38372   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
38373   ** record is written to the following sector (leaving a gap in the file
38374   ** that will be implicitly filled in by the OS).
38375   **
38376   ** However it has been discovered that on some systems this pattern can 
38377   ** be significantly slower than contiguously writing data to the file,
38378   ** even if that means explicitly writing data to the block of 
38379   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38380   ** is done. 
38381   **
38382   ** The loop is required here in case the sector-size is larger than the 
38383   ** database page size. Since the zHeader buffer is only Pager.pageSize
38384   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38385   ** to populate the entire journal header sector.
38386   */ 
38387   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38388     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38389     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38390     assert( pPager->journalHdr <= pPager->journalOff );
38391     pPager->journalOff += nHeader;
38392   }
38393
38394   return rc;
38395 }
38396
38397 /*
38398 ** The journal file must be open when this is called. A journal header file
38399 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38400 ** file. The current location in the journal file is given by
38401 ** pPager->journalOff. See comments above function writeJournalHdr() for
38402 ** a description of the journal header format.
38403 **
38404 ** If the header is read successfully, *pNRec is set to the number of
38405 ** page records following this header and *pDbSize is set to the size of the
38406 ** database before the transaction began, in pages. Also, pPager->cksumInit
38407 ** is set to the value read from the journal header. SQLITE_OK is returned
38408 ** in this case.
38409 **
38410 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38411 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38412 ** cannot be read from the journal file an error code is returned.
38413 */
38414 static int readJournalHdr(
38415   Pager *pPager,               /* Pager object */
38416   int isHot,
38417   i64 journalSize,             /* Size of the open journal file in bytes */
38418   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38419   u32 *pDbSize                 /* OUT: Value of original database size field */
38420 ){
38421   int rc;                      /* Return code */
38422   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38423   i64 iHdrOff;                 /* Offset of journal header being read */
38424
38425   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38426
38427   /* Advance Pager.journalOff to the start of the next sector. If the
38428   ** journal file is too small for there to be a header stored at this
38429   ** point, return SQLITE_DONE.
38430   */
38431   pPager->journalOff = journalHdrOffset(pPager);
38432   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38433     return SQLITE_DONE;
38434   }
38435   iHdrOff = pPager->journalOff;
38436
38437   /* Read in the first 8 bytes of the journal header. If they do not match
38438   ** the  magic string found at the start of each journal header, return
38439   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38440   ** proceed.
38441   */
38442   if( isHot || iHdrOff!=pPager->journalHdr ){
38443     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38444     if( rc ){
38445       return rc;
38446     }
38447     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38448       return SQLITE_DONE;
38449     }
38450   }
38451
38452   /* Read the first three 32-bit fields of the journal header: The nRec
38453   ** field, the checksum-initializer and the database size at the start
38454   ** of the transaction. Return an error code if anything goes wrong.
38455   */
38456   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38457    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38458    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38459   ){
38460     return rc;
38461   }
38462
38463   if( pPager->journalOff==0 ){
38464     u32 iPageSize;               /* Page-size field of journal header */
38465     u32 iSectorSize;             /* Sector-size field of journal header */
38466
38467     /* Read the page-size and sector-size journal header fields. */
38468     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38469      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38470     ){
38471       return rc;
38472     }
38473
38474     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38475     ** journal header to zero. In this case, assume that the Pager.pageSize
38476     ** variable is already set to the correct page size.
38477     */
38478     if( iPageSize==0 ){
38479       iPageSize = pPager->pageSize;
38480     }
38481
38482     /* Check that the values read from the page-size and sector-size fields
38483     ** are within range. To be 'in range', both values need to be a power
38484     ** of two greater than or equal to 512 or 32, and not greater than their 
38485     ** respective compile time maximum limits.
38486     */
38487     if( iPageSize<512                  || iSectorSize<32
38488      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38489      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
38490     ){
38491       /* If the either the page-size or sector-size in the journal-header is 
38492       ** invalid, then the process that wrote the journal-header must have 
38493       ** crashed before the header was synced. In this case stop reading 
38494       ** the journal file here.
38495       */
38496       return SQLITE_DONE;
38497     }
38498
38499     /* Update the page-size to match the value read from the journal. 
38500     ** Use a testcase() macro to make sure that malloc failure within 
38501     ** PagerSetPagesize() is tested.
38502     */
38503     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38504     testcase( rc!=SQLITE_OK );
38505
38506     /* Update the assumed sector-size to match the value used by 
38507     ** the process that created this journal. If this journal was
38508     ** created by a process other than this one, then this routine
38509     ** is being called from within pager_playback(). The local value
38510     ** of Pager.sectorSize is restored at the end of that routine.
38511     */
38512     pPager->sectorSize = iSectorSize;
38513   }
38514
38515   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38516   return rc;
38517 }
38518
38519
38520 /*
38521 ** Write the supplied master journal name into the journal file for pager
38522 ** pPager at the current location. The master journal name must be the last
38523 ** thing written to a journal file. If the pager is in full-sync mode, the
38524 ** journal file descriptor is advanced to the next sector boundary before
38525 ** anything is written. The format is:
38526 **
38527 **   + 4 bytes: PAGER_MJ_PGNO.
38528 **   + N bytes: Master journal filename in utf-8.
38529 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38530 **   + 4 bytes: Master journal name checksum.
38531 **   + 8 bytes: aJournalMagic[].
38532 **
38533 ** The master journal page checksum is the sum of the bytes in the master
38534 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38535 **
38536 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
38537 ** this call is a no-op.
38538 */
38539 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38540   int rc;                          /* Return code */
38541   int nMaster;                     /* Length of string zMaster */
38542   i64 iHdrOff;                     /* Offset of header in journal file */
38543   i64 jrnlSize;                    /* Size of journal file on disk */
38544   u32 cksum = 0;                   /* Checksum of string zMaster */
38545
38546   assert( pPager->setMaster==0 );
38547   assert( !pagerUseWal(pPager) );
38548
38549   if( !zMaster 
38550    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38551    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
38552   ){
38553     return SQLITE_OK;
38554   }
38555   pPager->setMaster = 1;
38556   assert( isOpen(pPager->jfd) );
38557   assert( pPager->journalHdr <= pPager->journalOff );
38558
38559   /* Calculate the length in bytes and the checksum of zMaster */
38560   for(nMaster=0; zMaster[nMaster]; nMaster++){
38561     cksum += zMaster[nMaster];
38562   }
38563
38564   /* If in full-sync mode, advance to the next disk sector before writing
38565   ** the master journal name. This is in case the previous page written to
38566   ** the journal has already been synced.
38567   */
38568   if( pPager->fullSync ){
38569     pPager->journalOff = journalHdrOffset(pPager);
38570   }
38571   iHdrOff = pPager->journalOff;
38572
38573   /* Write the master journal data to the end of the journal file. If
38574   ** an error occurs, return the error code to the caller.
38575   */
38576   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38577    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38578    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38579    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38580    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38581   ){
38582     return rc;
38583   }
38584   pPager->journalOff += (nMaster+20);
38585
38586   /* If the pager is in peristent-journal mode, then the physical 
38587   ** journal-file may extend past the end of the master-journal name
38588   ** and 8 bytes of magic data just written to the file. This is 
38589   ** dangerous because the code to rollback a hot-journal file
38590   ** will not be able to find the master-journal name to determine 
38591   ** whether or not the journal is hot. 
38592   **
38593   ** Easiest thing to do in this scenario is to truncate the journal 
38594   ** file to the required size.
38595   */ 
38596   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38597    && jrnlSize>pPager->journalOff
38598   ){
38599     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38600   }
38601   return rc;
38602 }
38603
38604 /*
38605 ** Find a page in the hash table given its page number. Return
38606 ** a pointer to the page or NULL if the requested page is not 
38607 ** already in memory.
38608 */
38609 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38610   PgHdr *p;                         /* Return value */
38611
38612   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38613   ** fail, since no attempt to allocate dynamic memory will be made.
38614   */
38615   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38616   return p;
38617 }
38618
38619 /*
38620 ** Discard the entire contents of the in-memory page-cache.
38621 */
38622 static void pager_reset(Pager *pPager){
38623   sqlite3BackupRestart(pPager->pBackup);
38624   sqlite3PcacheClear(pPager->pPCache);
38625 }
38626
38627 /*
38628 ** Free all structures in the Pager.aSavepoint[] array and set both
38629 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38630 ** if it is open and the pager is not in exclusive mode.
38631 */
38632 static void releaseAllSavepoints(Pager *pPager){
38633   int ii;               /* Iterator for looping through Pager.aSavepoint */
38634   for(ii=0; ii<pPager->nSavepoint; ii++){
38635     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38636   }
38637   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38638     sqlite3OsClose(pPager->sjfd);
38639   }
38640   sqlite3_free(pPager->aSavepoint);
38641   pPager->aSavepoint = 0;
38642   pPager->nSavepoint = 0;
38643   pPager->nSubRec = 0;
38644 }
38645
38646 /*
38647 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
38648 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38649 ** or SQLITE_NOMEM if a malloc failure occurs.
38650 */
38651 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38652   int ii;                   /* Loop counter */
38653   int rc = SQLITE_OK;       /* Result code */
38654
38655   for(ii=0; ii<pPager->nSavepoint; ii++){
38656     PagerSavepoint *p = &pPager->aSavepoint[ii];
38657     if( pgno<=p->nOrig ){
38658       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38659       testcase( rc==SQLITE_NOMEM );
38660       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38661     }
38662   }
38663   return rc;
38664 }
38665
38666 /*
38667 ** This function is a no-op if the pager is in exclusive mode and not
38668 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38669 ** state.
38670 **
38671 ** If the pager is not in exclusive-access mode, the database file is
38672 ** completely unlocked. If the file is unlocked and the file-system does
38673 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38674 ** closed (if it is open).
38675 **
38676 ** If the pager is in ERROR state when this function is called, the 
38677 ** contents of the pager cache are discarded before switching back to 
38678 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38679 ** or not, any journal file left in the file-system will be treated
38680 ** as a hot-journal and rolled back the next time a read-transaction
38681 ** is opened (by this or by any other connection).
38682 */
38683 static void pager_unlock(Pager *pPager){
38684
38685   assert( pPager->eState==PAGER_READER 
38686        || pPager->eState==PAGER_OPEN 
38687        || pPager->eState==PAGER_ERROR 
38688   );
38689
38690   sqlite3BitvecDestroy(pPager->pInJournal);
38691   pPager->pInJournal = 0;
38692   releaseAllSavepoints(pPager);
38693
38694   if( pagerUseWal(pPager) ){
38695     assert( !isOpen(pPager->jfd) );
38696     sqlite3WalEndReadTransaction(pPager->pWal);
38697     pPager->eState = PAGER_OPEN;
38698   }else if( !pPager->exclusiveMode ){
38699     int rc;                       /* Error code returned by pagerUnlockDb() */
38700     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38701
38702     /* If the operating system support deletion of open files, then
38703     ** close the journal file when dropping the database lock.  Otherwise
38704     ** another connection with journal_mode=delete might delete the file
38705     ** out from under us.
38706     */
38707     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
38708     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
38709     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
38710     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
38711     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38712     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
38713     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38714      || 1!=(pPager->journalMode & 5)
38715     ){
38716       sqlite3OsClose(pPager->jfd);
38717     }
38718
38719     /* If the pager is in the ERROR state and the call to unlock the database
38720     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38721     ** above the #define for UNKNOWN_LOCK for an explanation of why this
38722     ** is necessary.
38723     */
38724     rc = pagerUnlockDb(pPager, NO_LOCK);
38725     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38726       pPager->eLock = UNKNOWN_LOCK;
38727     }
38728
38729     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38730     ** without clearing the error code. This is intentional - the error
38731     ** code is cleared and the cache reset in the block below.
38732     */
38733     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38734     pPager->changeCountDone = 0;
38735     pPager->eState = PAGER_OPEN;
38736   }
38737
38738   /* If Pager.errCode is set, the contents of the pager cache cannot be
38739   ** trusted. Now that there are no outstanding references to the pager,
38740   ** it can safely move back to PAGER_OPEN state. This happens in both
38741   ** normal and exclusive-locking mode.
38742   */
38743   if( pPager->errCode ){
38744     assert( !MEMDB );
38745     pager_reset(pPager);
38746     pPager->changeCountDone = pPager->tempFile;
38747     pPager->eState = PAGER_OPEN;
38748     pPager->errCode = SQLITE_OK;
38749   }
38750
38751   pPager->journalOff = 0;
38752   pPager->journalHdr = 0;
38753   pPager->setMaster = 0;
38754 }
38755
38756 /*
38757 ** This function is called whenever an IOERR or FULL error that requires
38758 ** the pager to transition into the ERROR state may ahve occurred.
38759 ** The first argument is a pointer to the pager structure, the second 
38760 ** the error-code about to be returned by a pager API function. The 
38761 ** value returned is a copy of the second argument to this function. 
38762 **
38763 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38764 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38765 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38766 ** all major API calls on the Pager will immediately return Pager.errCode.
38767 **
38768 ** The ERROR state indicates that the contents of the pager-cache 
38769 ** cannot be trusted. This state can be cleared by completely discarding 
38770 ** the contents of the pager-cache. If a transaction was active when
38771 ** the persistent error occurred, then the rollback journal may need
38772 ** to be replayed to restore the contents of the database file (as if
38773 ** it were a hot-journal).
38774 */
38775 static int pager_error(Pager *pPager, int rc){
38776   int rc2 = rc & 0xff;
38777   assert( rc==SQLITE_OK || !MEMDB );
38778   assert(
38779        pPager->errCode==SQLITE_FULL ||
38780        pPager->errCode==SQLITE_OK ||
38781        (pPager->errCode & 0xff)==SQLITE_IOERR
38782   );
38783   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38784     pPager->errCode = rc;
38785     pPager->eState = PAGER_ERROR;
38786   }
38787   return rc;
38788 }
38789
38790 /*
38791 ** This routine ends a transaction. A transaction is usually ended by 
38792 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
38793 ** after rollback of a hot-journal, or if an error occurs while opening
38794 ** the journal file or writing the very first journal-header of a
38795 ** database transaction.
38796 ** 
38797 ** This routine is never called in PAGER_ERROR state. If it is called
38798 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38799 ** exclusive than a RESERVED lock, it is a no-op.
38800 **
38801 ** Otherwise, any active savepoints are released.
38802 **
38803 ** If the journal file is open, then it is "finalized". Once a journal 
38804 ** file has been finalized it is not possible to use it to roll back a 
38805 ** transaction. Nor will it be considered to be a hot-journal by this
38806 ** or any other database connection. Exactly how a journal is finalized
38807 ** depends on whether or not the pager is running in exclusive mode and
38808 ** the current journal-mode (Pager.journalMode value), as follows:
38809 **
38810 **   journalMode==MEMORY
38811 **     Journal file descriptor is simply closed. This destroys an 
38812 **     in-memory journal.
38813 **
38814 **   journalMode==TRUNCATE
38815 **     Journal file is truncated to zero bytes in size.
38816 **
38817 **   journalMode==PERSIST
38818 **     The first 28 bytes of the journal file are zeroed. This invalidates
38819 **     the first journal header in the file, and hence the entire journal
38820 **     file. An invalid journal file cannot be rolled back.
38821 **
38822 **   journalMode==DELETE
38823 **     The journal file is closed and deleted using sqlite3OsDelete().
38824 **
38825 **     If the pager is running in exclusive mode, this method of finalizing
38826 **     the journal file is never used. Instead, if the journalMode is
38827 **     DELETE and the pager is in exclusive mode, the method described under
38828 **     journalMode==PERSIST is used instead.
38829 **
38830 ** After the journal is finalized, the pager moves to PAGER_READER state.
38831 ** If running in non-exclusive rollback mode, the lock on the file is 
38832 ** downgraded to a SHARED_LOCK.
38833 **
38834 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38835 ** any of the IO operations to finalize the journal file or unlock the
38836 ** database then the IO error code is returned to the user. If the 
38837 ** operation to finalize the journal file fails, then the code still
38838 ** tries to unlock the database file if not in exclusive mode. If the
38839 ** unlock operation fails as well, then the first error code related
38840 ** to the first error encountered (the journal finalization one) is
38841 ** returned.
38842 */
38843 static int pager_end_transaction(Pager *pPager, int hasMaster){
38844   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
38845   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
38846
38847   /* Do nothing if the pager does not have an open write transaction
38848   ** or at least a RESERVED lock. This function may be called when there
38849   ** is no write-transaction active but a RESERVED or greater lock is
38850   ** held under two circumstances:
38851   **
38852   **   1. After a successful hot-journal rollback, it is called with
38853   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38854   **
38855   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
38856   **      lock switches back to locking_mode=normal and then executes a
38857   **      read-transaction, this function is called with eState==PAGER_READER 
38858   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38859   */
38860   assert( assert_pager_state(pPager) );
38861   assert( pPager->eState!=PAGER_ERROR );
38862   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38863     return SQLITE_OK;
38864   }
38865
38866   releaseAllSavepoints(pPager);
38867   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38868   if( isOpen(pPager->jfd) ){
38869     assert( !pagerUseWal(pPager) );
38870
38871     /* Finalize the journal file. */
38872     if( sqlite3IsMemJournal(pPager->jfd) ){
38873       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38874       sqlite3OsClose(pPager->jfd);
38875     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38876       if( pPager->journalOff==0 ){
38877         rc = SQLITE_OK;
38878       }else{
38879         rc = sqlite3OsTruncate(pPager->jfd, 0);
38880       }
38881       pPager->journalOff = 0;
38882     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38883       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38884     ){
38885       rc = zeroJournalHdr(pPager, hasMaster);
38886       pPager->journalOff = 0;
38887     }else{
38888       /* This branch may be executed with Pager.journalMode==MEMORY if
38889       ** a hot-journal was just rolled back. In this case the journal
38890       ** file should be closed and deleted. If this connection writes to
38891       ** the database file, it will do so using an in-memory journal. 
38892       */
38893       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
38894            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38895            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
38896       );
38897       sqlite3OsClose(pPager->jfd);
38898       if( !pPager->tempFile ){
38899         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38900       }
38901     }
38902   }
38903
38904 #ifdef SQLITE_CHECK_PAGES
38905   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38906   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38907     PgHdr *p = pager_lookup(pPager, 1);
38908     if( p ){
38909       p->pageHash = 0;
38910       sqlite3PagerUnref(p);
38911     }
38912   }
38913 #endif
38914
38915   sqlite3BitvecDestroy(pPager->pInJournal);
38916   pPager->pInJournal = 0;
38917   pPager->nRec = 0;
38918   sqlite3PcacheCleanAll(pPager->pPCache);
38919   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38920
38921   if( pagerUseWal(pPager) ){
38922     /* Drop the WAL write-lock, if any. Also, if the connection was in 
38923     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
38924     ** lock held on the database file.
38925     */
38926     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38927     assert( rc2==SQLITE_OK );
38928   }
38929   if( !pPager->exclusiveMode 
38930    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38931   ){
38932     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38933     pPager->changeCountDone = 0;
38934   }
38935   pPager->eState = PAGER_READER;
38936   pPager->setMaster = 0;
38937
38938   return (rc==SQLITE_OK?rc2:rc);
38939 }
38940
38941 /*
38942 ** Execute a rollback if a transaction is active and unlock the 
38943 ** database file. 
38944 **
38945 ** If the pager has already entered the ERROR state, do not attempt 
38946 ** the rollback at this time. Instead, pager_unlock() is called. The
38947 ** call to pager_unlock() will discard all in-memory pages, unlock
38948 ** the database file and move the pager back to OPEN state. If this 
38949 ** means that there is a hot-journal left in the file-system, the next 
38950 ** connection to obtain a shared lock on the pager (which may be this one) 
38951 ** will roll it back.
38952 **
38953 ** If the pager has not already entered the ERROR state, but an IO or
38954 ** malloc error occurs during a rollback, then this will itself cause 
38955 ** the pager to enter the ERROR state. Which will be cleared by the
38956 ** call to pager_unlock(), as described above.
38957 */
38958 static void pagerUnlockAndRollback(Pager *pPager){
38959   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38960     assert( assert_pager_state(pPager) );
38961     if( pPager->eState>=PAGER_WRITER_LOCKED ){
38962       sqlite3BeginBenignMalloc();
38963       sqlite3PagerRollback(pPager);
38964       sqlite3EndBenignMalloc();
38965     }else if( !pPager->exclusiveMode ){
38966       assert( pPager->eState==PAGER_READER );
38967       pager_end_transaction(pPager, 0);
38968     }
38969   }
38970   pager_unlock(pPager);
38971 }
38972
38973 /*
38974 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38975 ** of data. Compute and return a checksum based ont the contents of the 
38976 ** page of data and the current value of pPager->cksumInit.
38977 **
38978 ** This is not a real checksum. It is really just the sum of the 
38979 ** random initial value (pPager->cksumInit) and every 200th byte
38980 ** of the page data, starting with byte offset (pPager->pageSize%200).
38981 ** Each byte is interpreted as an 8-bit unsigned integer.
38982 **
38983 ** Changing the formula used to compute this checksum results in an
38984 ** incompatible journal file format.
38985 **
38986 ** If journal corruption occurs due to a power failure, the most likely 
38987 ** scenario is that one end or the other of the record will be changed. 
38988 ** It is much less likely that the two ends of the journal record will be
38989 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
38990 ** though fast and simple, catches the mostly likely kind of corruption.
38991 */
38992 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38993   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
38994   int i = pPager->pageSize-200;          /* Loop counter */
38995   while( i>0 ){
38996     cksum += aData[i];
38997     i -= 200;
38998   }
38999   return cksum;
39000 }
39001
39002 /*
39003 ** Report the current page size and number of reserved bytes back
39004 ** to the codec.
39005 */
39006 #ifdef SQLITE_HAS_CODEC
39007 static void pagerReportSize(Pager *pPager){
39008   if( pPager->xCodecSizeChng ){
39009     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39010                            (int)pPager->nReserve);
39011   }
39012 }
39013 #else
39014 # define pagerReportSize(X)     /* No-op if we do not support a codec */
39015 #endif
39016
39017 /*
39018 ** Read a single page from either the journal file (if isMainJrnl==1) or
39019 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39020 ** The page begins at offset *pOffset into the file. The *pOffset
39021 ** value is increased to the start of the next page in the journal.
39022 **
39023 ** The main rollback journal uses checksums - the statement journal does 
39024 ** not.
39025 **
39026 ** If the page number of the page record read from the (sub-)journal file
39027 ** is greater than the current value of Pager.dbSize, then playback is
39028 ** skipped and SQLITE_OK is returned.
39029 **
39030 ** If pDone is not NULL, then it is a record of pages that have already
39031 ** been played back.  If the page at *pOffset has already been played back
39032 ** (if the corresponding pDone bit is set) then skip the playback.
39033 ** Make sure the pDone bit corresponding to the *pOffset page is set
39034 ** prior to returning.
39035 **
39036 ** If the page record is successfully read from the (sub-)journal file
39037 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39038 ** while reading the record from the (sub-)journal file or while writing
39039 ** to the database file, then the IO error code is returned. If data
39040 ** is successfully read from the (sub-)journal file but appears to be
39041 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39042 ** two circumstances:
39043 ** 
39044 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39045 **   * If the record is being rolled back from the main journal file
39046 **     and the checksum field does not match the record content.
39047 **
39048 ** Neither of these two scenarios are possible during a savepoint rollback.
39049 **
39050 ** If this is a savepoint rollback, then memory may have to be dynamically
39051 ** allocated by this function. If this is the case and an allocation fails,
39052 ** SQLITE_NOMEM is returned.
39053 */
39054 static int pager_playback_one_page(
39055   Pager *pPager,                /* The pager being played back */
39056   i64 *pOffset,                 /* Offset of record to playback */
39057   Bitvec *pDone,                /* Bitvec of pages already played back */
39058   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
39059   int isSavepnt                 /* True for a savepoint rollback */
39060 ){
39061   int rc;
39062   PgHdr *pPg;                   /* An existing page in the cache */
39063   Pgno pgno;                    /* The page number of a page in journal */
39064   u32 cksum;                    /* Checksum used for sanity checking */
39065   char *aData;                  /* Temporary storage for the page */
39066   sqlite3_file *jfd;            /* The file descriptor for the journal file */
39067   int isSynced;                 /* True if journal page is synced */
39068
39069   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
39070   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
39071   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
39072   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
39073
39074   aData = pPager->pTmpSpace;
39075   assert( aData );         /* Temp storage must have already been allocated */
39076   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39077
39078   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
39079   ** or savepoint rollback done at the request of the caller) or this is
39080   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39081   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39082   ** only reads from the main journal, not the sub-journal.
39083   */
39084   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39085        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39086   );
39087   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39088
39089   /* Read the page number and page data from the journal or sub-journal
39090   ** file. Return an error code to the caller if an IO error occurs.
39091   */
39092   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39093   rc = read32bits(jfd, *pOffset, &pgno);
39094   if( rc!=SQLITE_OK ) return rc;
39095   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39096   if( rc!=SQLITE_OK ) return rc;
39097   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39098
39099   /* Sanity checking on the page.  This is more important that I originally
39100   ** thought.  If a power failure occurs while the journal is being written,
39101   ** it could cause invalid data to be written into the journal.  We need to
39102   ** detect this invalid data (with high probability) and ignore it.
39103   */
39104   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39105     assert( !isSavepnt );
39106     return SQLITE_DONE;
39107   }
39108   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39109     return SQLITE_OK;
39110   }
39111   if( isMainJrnl ){
39112     rc = read32bits(jfd, (*pOffset)-4, &cksum);
39113     if( rc ) return rc;
39114     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39115       return SQLITE_DONE;
39116     }
39117   }
39118
39119   /* If this page has already been played by before during the current
39120   ** rollback, then don't bother to play it back again.
39121   */
39122   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39123     return rc;
39124   }
39125
39126   /* When playing back page 1, restore the nReserve setting
39127   */
39128   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39129     pPager->nReserve = ((u8*)aData)[20];
39130     pagerReportSize(pPager);
39131   }
39132
39133   /* If the pager is in CACHEMOD state, then there must be a copy of this
39134   ** page in the pager cache. In this case just update the pager cache,
39135   ** not the database file. The page is left marked dirty in this case.
39136   **
39137   ** An exception to the above rule: If the database is in no-sync mode
39138   ** and a page is moved during an incremental vacuum then the page may
39139   ** not be in the pager cache. Later: if a malloc() or IO error occurs
39140   ** during a Movepage() call, then the page may not be in the cache
39141   ** either. So the condition described in the above paragraph is not
39142   ** assert()able.
39143   **
39144   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39145   ** pager cache if it exists and the main file. The page is then marked 
39146   ** not dirty. Since this code is only executed in PAGER_OPEN state for
39147   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39148   ** if the pager is in OPEN state.
39149   **
39150   ** Ticket #1171:  The statement journal might contain page content that is
39151   ** different from the page content at the start of the transaction.
39152   ** This occurs when a page is changed prior to the start of a statement
39153   ** then changed again within the statement.  When rolling back such a
39154   ** statement we must not write to the original database unless we know
39155   ** for certain that original page contents are synced into the main rollback
39156   ** journal.  Otherwise, a power loss might leave modified data in the
39157   ** database file without an entry in the rollback journal that can
39158   ** restore the database to its original form.  Two conditions must be
39159   ** met before writing to the database files. (1) the database must be
39160   ** locked.  (2) we know that the original page content is fully synced
39161   ** in the main journal either because the page is not in cache or else
39162   ** the page is marked as needSync==0.
39163   **
39164   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
39165   ** is possible to fail a statement on a database that does not yet exist.
39166   ** Do not attempt to write if database file has never been opened.
39167   */
39168   if( pagerUseWal(pPager) ){
39169     pPg = 0;
39170   }else{
39171     pPg = pager_lookup(pPager, pgno);
39172   }
39173   assert( pPg || !MEMDB );
39174   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39175   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39176            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39177            (isMainJrnl?"main-journal":"sub-journal")
39178   ));
39179   if( isMainJrnl ){
39180     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39181   }else{
39182     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39183   }
39184   if( isOpen(pPager->fd)
39185    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39186    && isSynced
39187   ){
39188     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39189     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39190     assert( !pagerUseWal(pPager) );
39191     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39192     if( pgno>pPager->dbFileSize ){
39193       pPager->dbFileSize = pgno;
39194     }
39195     if( pPager->pBackup ){
39196       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39197       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39198       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39199     }
39200   }else if( !isMainJrnl && pPg==0 ){
39201     /* If this is a rollback of a savepoint and data was not written to
39202     ** the database and the page is not in-memory, there is a potential
39203     ** problem. When the page is next fetched by the b-tree layer, it 
39204     ** will be read from the database file, which may or may not be 
39205     ** current. 
39206     **
39207     ** There are a couple of different ways this can happen. All are quite
39208     ** obscure. When running in synchronous mode, this can only happen 
39209     ** if the page is on the free-list at the start of the transaction, then
39210     ** populated, then moved using sqlite3PagerMovepage().
39211     **
39212     ** The solution is to add an in-memory page to the cache containing
39213     ** the data just read from the sub-journal. Mark the page as dirty 
39214     ** and if the pager requires a journal-sync, then mark the page as 
39215     ** requiring a journal-sync before it is written.
39216     */
39217     assert( isSavepnt );
39218     assert( pPager->doNotSpill==0 );
39219     pPager->doNotSpill++;
39220     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39221     assert( pPager->doNotSpill==1 );
39222     pPager->doNotSpill--;
39223     if( rc!=SQLITE_OK ) return rc;
39224     pPg->flags &= ~PGHDR_NEED_READ;
39225     sqlite3PcacheMakeDirty(pPg);
39226   }
39227   if( pPg ){
39228     /* No page should ever be explicitly rolled back that is in use, except
39229     ** for page 1 which is held in use in order to keep the lock on the
39230     ** database active. However such a page may be rolled back as a result
39231     ** of an internal error resulting in an automatic call to
39232     ** sqlite3PagerRollback().
39233     */
39234     void *pData;
39235     pData = pPg->pData;
39236     memcpy(pData, (u8*)aData, pPager->pageSize);
39237     pPager->xReiniter(pPg);
39238     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39239       /* If the contents of this page were just restored from the main 
39240       ** journal file, then its content must be as they were when the 
39241       ** transaction was first opened. In this case we can mark the page
39242       ** as clean, since there will be no need to write it out to the
39243       ** database.
39244       **
39245       ** There is one exception to this rule. If the page is being rolled
39246       ** back as part of a savepoint (or statement) rollback from an 
39247       ** unsynced portion of the main journal file, then it is not safe
39248       ** to mark the page as clean. This is because marking the page as
39249       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39250       ** already in the journal file (recorded in Pager.pInJournal) and
39251       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39252       ** again within this transaction, it will be marked as dirty but
39253       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39254       ** be written out into the database file before its journal file
39255       ** segment is synced. If a crash occurs during or following this,
39256       ** database corruption may ensue.
39257       */
39258       assert( !pagerUseWal(pPager) );
39259       sqlite3PcacheMakeClean(pPg);
39260     }
39261     pager_set_pagehash(pPg);
39262
39263     /* If this was page 1, then restore the value of Pager.dbFileVers.
39264     ** Do this before any decoding. */
39265     if( pgno==1 ){
39266       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39267     }
39268
39269     /* Decode the page just read from disk */
39270     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39271     sqlite3PcacheRelease(pPg);
39272   }
39273   return rc;
39274 }
39275
39276 /*
39277 ** Parameter zMaster is the name of a master journal file. A single journal
39278 ** file that referred to the master journal file has just been rolled back.
39279 ** This routine checks if it is possible to delete the master journal file,
39280 ** and does so if it is.
39281 **
39282 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
39283 ** available for use within this function.
39284 **
39285 ** When a master journal file is created, it is populated with the names 
39286 ** of all of its child journals, one after another, formatted as utf-8 
39287 ** encoded text. The end of each child journal file is marked with a 
39288 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39289 ** file for a transaction involving two databases might be:
39290 **
39291 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39292 **
39293 ** A master journal file may only be deleted once all of its child 
39294 ** journals have been rolled back.
39295 **
39296 ** This function reads the contents of the master-journal file into 
39297 ** memory and loops through each of the child journal names. For
39298 ** each child journal, it checks if:
39299 **
39300 **   * if the child journal exists, and if so
39301 **   * if the child journal contains a reference to master journal 
39302 **     file zMaster
39303 **
39304 ** If a child journal can be found that matches both of the criteria
39305 ** above, this function returns without doing anything. Otherwise, if
39306 ** no such child journal can be found, file zMaster is deleted from
39307 ** the file-system using sqlite3OsDelete().
39308 **
39309 ** If an IO error within this function, an error code is returned. This
39310 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39311 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
39312 ** occur, SQLITE_OK is returned.
39313 **
39314 ** TODO: This function allocates a single block of memory to load
39315 ** the entire contents of the master journal file. This could be
39316 ** a couple of kilobytes or so - potentially larger than the page 
39317 ** size.
39318 */
39319 static int pager_delmaster(Pager *pPager, const char *zMaster){
39320   sqlite3_vfs *pVfs = pPager->pVfs;
39321   int rc;                   /* Return code */
39322   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39323   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39324   char *zMasterJournal = 0; /* Contents of master journal file */
39325   i64 nMasterJournal;       /* Size of master journal file */
39326   char *zJournal;           /* Pointer to one journal within MJ file */
39327   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39328   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39329
39330   /* Allocate space for both the pJournal and pMaster file descriptors.
39331   ** If successful, open the master journal file for reading.
39332   */
39333   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39334   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39335   if( !pMaster ){
39336     rc = SQLITE_NOMEM;
39337   }else{
39338     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39339     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39340   }
39341   if( rc!=SQLITE_OK ) goto delmaster_out;
39342
39343   /* Load the entire master journal file into space obtained from
39344   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39345   ** sufficient space (in zMasterPtr) to hold the names of master
39346   ** journal files extracted from regular rollback-journals.
39347   */
39348   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39349   if( rc!=SQLITE_OK ) goto delmaster_out;
39350   nMasterPtr = pVfs->mxPathname+1;
39351   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39352   if( !zMasterJournal ){
39353     rc = SQLITE_NOMEM;
39354     goto delmaster_out;
39355   }
39356   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39357   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39358   if( rc!=SQLITE_OK ) goto delmaster_out;
39359   zMasterJournal[nMasterJournal] = 0;
39360
39361   zJournal = zMasterJournal;
39362   while( (zJournal-zMasterJournal)<nMasterJournal ){
39363     int exists;
39364     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39365     if( rc!=SQLITE_OK ){
39366       goto delmaster_out;
39367     }
39368     if( exists ){
39369       /* One of the journals pointed to by the master journal exists.
39370       ** Open it and check if it points at the master journal. If
39371       ** so, return without deleting the master journal file.
39372       */
39373       int c;
39374       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39375       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39376       if( rc!=SQLITE_OK ){
39377         goto delmaster_out;
39378       }
39379
39380       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39381       sqlite3OsClose(pJournal);
39382       if( rc!=SQLITE_OK ){
39383         goto delmaster_out;
39384       }
39385
39386       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39387       if( c ){
39388         /* We have a match. Do not delete the master journal file. */
39389         goto delmaster_out;
39390       }
39391     }
39392     zJournal += (sqlite3Strlen30(zJournal)+1);
39393   }
39394  
39395   sqlite3OsClose(pMaster);
39396   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39397
39398 delmaster_out:
39399   sqlite3_free(zMasterJournal);
39400   if( pMaster ){
39401     sqlite3OsClose(pMaster);
39402     assert( !isOpen(pJournal) );
39403     sqlite3_free(pMaster);
39404   }
39405   return rc;
39406 }
39407
39408
39409 /*
39410 ** This function is used to change the actual size of the database 
39411 ** file in the file-system. This only happens when committing a transaction,
39412 ** or rolling back a transaction (including rolling back a hot-journal).
39413 **
39414 ** If the main database file is not open, or the pager is not in either
39415 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
39416 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
39417 ** If the file on disk is currently larger than nPage pages, then use the VFS
39418 ** xTruncate() method to truncate it.
39419 **
39420 ** Or, it might might be the case that the file on disk is smaller than 
39421 ** nPage pages. Some operating system implementations can get confused if 
39422 ** you try to truncate a file to some size that is larger than it 
39423 ** currently is, so detect this case and write a single zero byte to 
39424 ** the end of the new file instead.
39425 **
39426 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39427 ** the database file, return the error code to the caller.
39428 */
39429 static int pager_truncate(Pager *pPager, Pgno nPage){
39430   int rc = SQLITE_OK;
39431   assert( pPager->eState!=PAGER_ERROR );
39432   assert( pPager->eState!=PAGER_READER );
39433   
39434   if( isOpen(pPager->fd) 
39435    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
39436   ){
39437     i64 currentSize, newSize;
39438     int szPage = pPager->pageSize;
39439     assert( pPager->eLock==EXCLUSIVE_LOCK );
39440     /* TODO: Is it safe to use Pager.dbFileSize here? */
39441     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39442     newSize = szPage*(i64)nPage;
39443     if( rc==SQLITE_OK && currentSize!=newSize ){
39444       if( currentSize>newSize ){
39445         rc = sqlite3OsTruncate(pPager->fd, newSize);
39446       }else if( (currentSize+szPage)<=newSize ){
39447         char *pTmp = pPager->pTmpSpace;
39448         memset(pTmp, 0, szPage);
39449         testcase( (newSize-szPage) == currentSize );
39450         testcase( (newSize-szPage) >  currentSize );
39451         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39452       }
39453       if( rc==SQLITE_OK ){
39454         pPager->dbFileSize = nPage;
39455       }
39456     }
39457   }
39458   return rc;
39459 }
39460
39461 /*
39462 ** Set the value of the Pager.sectorSize variable for the given
39463 ** pager based on the value returned by the xSectorSize method
39464 ** of the open database file. The sector size will be used used 
39465 ** to determine the size and alignment of journal header and 
39466 ** master journal pointers within created journal files.
39467 **
39468 ** For temporary files the effective sector size is always 512 bytes.
39469 **
39470 ** Otherwise, for non-temporary files, the effective sector size is
39471 ** the value returned by the xSectorSize() method rounded up to 32 if
39472 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39473 ** is greater than MAX_SECTOR_SIZE.
39474 **
39475 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
39476 ** the effective sector size to its minimum value (512).  The purpose of
39477 ** pPager->sectorSize is to define the "blast radius" of bytes that
39478 ** might change if a crash occurs while writing to a single byte in
39479 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
39480 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
39481 ** size.  For backwards compatibility of the rollback journal file format,
39482 ** we cannot reduce the effective sector size below 512.
39483 */
39484 static void setSectorSize(Pager *pPager){
39485   assert( isOpen(pPager->fd) || pPager->tempFile );
39486
39487   if( pPager->tempFile
39488    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
39489               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
39490   ){
39491     /* Sector size doesn't matter for temporary files. Also, the file
39492     ** may not have been opened yet, in which case the OsSectorSize()
39493     ** call will segfault. */
39494     pPager->sectorSize = 512;
39495   }else{
39496     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
39497     if( pPager->sectorSize<32 ){
39498       pPager->sectorSize = 512;
39499     }
39500     if( pPager->sectorSize>MAX_SECTOR_SIZE ){
39501       assert( MAX_SECTOR_SIZE>=512 );
39502       pPager->sectorSize = MAX_SECTOR_SIZE;
39503     }
39504   }
39505 }
39506
39507 /*
39508 ** Playback the journal and thus restore the database file to
39509 ** the state it was in before we started making changes.  
39510 **
39511 ** The journal file format is as follows: 
39512 **
39513 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
39514 **  (2)  4 byte big-endian integer which is the number of valid page records
39515 **       in the journal.  If this value is 0xffffffff, then compute the
39516 **       number of page records from the journal size.
39517 **  (3)  4 byte big-endian integer which is the initial value for the 
39518 **       sanity checksum.
39519 **  (4)  4 byte integer which is the number of pages to truncate the
39520 **       database to during a rollback.
39521 **  (5)  4 byte big-endian integer which is the sector size.  The header
39522 **       is this many bytes in size.
39523 **  (6)  4 byte big-endian integer which is the page size.
39524 **  (7)  zero padding out to the next sector size.
39525 **  (8)  Zero or more pages instances, each as follows:
39526 **        +  4 byte page number.
39527 **        +  pPager->pageSize bytes of data.
39528 **        +  4 byte checksum
39529 **
39530 ** When we speak of the journal header, we mean the first 7 items above.
39531 ** Each entry in the journal is an instance of the 8th item.
39532 **
39533 ** Call the value from the second bullet "nRec".  nRec is the number of
39534 ** valid page entries in the journal.  In most cases, you can compute the
39535 ** value of nRec from the size of the journal file.  But if a power
39536 ** failure occurred while the journal was being written, it could be the
39537 ** case that the size of the journal file had already been increased but
39538 ** the extra entries had not yet made it safely to disk.  In such a case,
39539 ** the value of nRec computed from the file size would be too large.  For
39540 ** that reason, we always use the nRec value in the header.
39541 **
39542 ** If the nRec value is 0xffffffff it means that nRec should be computed
39543 ** from the file size.  This value is used when the user selects the
39544 ** no-sync option for the journal.  A power failure could lead to corruption
39545 ** in this case.  But for things like temporary table (which will be
39546 ** deleted when the power is restored) we don't care.  
39547 **
39548 ** If the file opened as the journal file is not a well-formed
39549 ** journal file then all pages up to the first corrupted page are rolled
39550 ** back (or no pages if the journal header is corrupted). The journal file
39551 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39552 ** been encountered.
39553 **
39554 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39555 ** and an error code is returned.
39556 **
39557 ** The isHot parameter indicates that we are trying to rollback a journal
39558 ** that might be a hot journal.  Or, it could be that the journal is 
39559 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39560 ** If the journal really is hot, reset the pager cache prior rolling
39561 ** back any content.  If the journal is merely persistent, no reset is
39562 ** needed.
39563 */
39564 static int pager_playback(Pager *pPager, int isHot){
39565   sqlite3_vfs *pVfs = pPager->pVfs;
39566   i64 szJ;                 /* Size of the journal file in bytes */
39567   u32 nRec;                /* Number of Records in the journal */
39568   u32 u;                   /* Unsigned loop counter */
39569   Pgno mxPg = 0;           /* Size of the original file in pages */
39570   int rc;                  /* Result code of a subroutine */
39571   int res = 1;             /* Value returned by sqlite3OsAccess() */
39572   char *zMaster = 0;       /* Name of master journal file if any */
39573   int needPagerReset;      /* True to reset page prior to first page rollback */
39574
39575   /* Figure out how many records are in the journal.  Abort early if
39576   ** the journal is empty.
39577   */
39578   assert( isOpen(pPager->jfd) );
39579   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39580   if( rc!=SQLITE_OK ){
39581     goto end_playback;
39582   }
39583
39584   /* Read the master journal name from the journal, if it is present.
39585   ** If a master journal file name is specified, but the file is not
39586   ** present on disk, then the journal is not hot and does not need to be
39587   ** played back.
39588   **
39589   ** TODO: Technically the following is an error because it assumes that
39590   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39591   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39592   **  mxPathname is 512, which is the same as the minimum allowable value
39593   ** for pageSize.
39594   */
39595   zMaster = pPager->pTmpSpace;
39596   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39597   if( rc==SQLITE_OK && zMaster[0] ){
39598     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39599   }
39600   zMaster = 0;
39601   if( rc!=SQLITE_OK || !res ){
39602     goto end_playback;
39603   }
39604   pPager->journalOff = 0;
39605   needPagerReset = isHot;
39606
39607   /* This loop terminates either when a readJournalHdr() or 
39608   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
39609   ** occurs. 
39610   */
39611   while( 1 ){
39612     /* Read the next journal header from the journal file.  If there are
39613     ** not enough bytes left in the journal file for a complete header, or
39614     ** it is corrupted, then a process must have failed while writing it.
39615     ** This indicates nothing more needs to be rolled back.
39616     */
39617     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39618     if( rc!=SQLITE_OK ){ 
39619       if( rc==SQLITE_DONE ){
39620         rc = SQLITE_OK;
39621       }
39622       goto end_playback;
39623     }
39624
39625     /* If nRec is 0xffffffff, then this journal was created by a process
39626     ** working in no-sync mode. This means that the rest of the journal
39627     ** file consists of pages, there are no more journal headers. Compute
39628     ** the value of nRec based on this assumption.
39629     */
39630     if( nRec==0xffffffff ){
39631       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39632       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39633     }
39634
39635     /* If nRec is 0 and this rollback is of a transaction created by this
39636     ** process and if this is the final header in the journal, then it means
39637     ** that this part of the journal was being filled but has not yet been
39638     ** synced to disk.  Compute the number of pages based on the remaining
39639     ** size of the file.
39640     **
39641     ** The third term of the test was added to fix ticket #2565.
39642     ** When rolling back a hot journal, nRec==0 always means that the next
39643     ** chunk of the journal contains zero pages to be rolled back.  But
39644     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39645     ** the journal, it means that the journal might contain additional
39646     ** pages that need to be rolled back and that the number of pages 
39647     ** should be computed based on the journal file size.
39648     */
39649     if( nRec==0 && !isHot &&
39650         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39651       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39652     }
39653
39654     /* If this is the first header read from the journal, truncate the
39655     ** database file back to its original size.
39656     */
39657     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39658       rc = pager_truncate(pPager, mxPg);
39659       if( rc!=SQLITE_OK ){
39660         goto end_playback;
39661       }
39662       pPager->dbSize = mxPg;
39663     }
39664
39665     /* Copy original pages out of the journal and back into the 
39666     ** database file and/or page cache.
39667     */
39668     for(u=0; u<nRec; u++){
39669       if( needPagerReset ){
39670         pager_reset(pPager);
39671         needPagerReset = 0;
39672       }
39673       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39674       if( rc!=SQLITE_OK ){
39675         if( rc==SQLITE_DONE ){
39676           pPager->journalOff = szJ;
39677           break;
39678         }else if( rc==SQLITE_IOERR_SHORT_READ ){
39679           /* If the journal has been truncated, simply stop reading and
39680           ** processing the journal. This might happen if the journal was
39681           ** not completely written and synced prior to a crash.  In that
39682           ** case, the database should have never been written in the
39683           ** first place so it is OK to simply abandon the rollback. */
39684           rc = SQLITE_OK;
39685           goto end_playback;
39686         }else{
39687           /* If we are unable to rollback, quit and return the error
39688           ** code.  This will cause the pager to enter the error state
39689           ** so that no further harm will be done.  Perhaps the next
39690           ** process to come along will be able to rollback the database.
39691           */
39692           goto end_playback;
39693         }
39694       }
39695     }
39696   }
39697   /*NOTREACHED*/
39698   assert( 0 );
39699
39700 end_playback:
39701   /* Following a rollback, the database file should be back in its original
39702   ** state prior to the start of the transaction, so invoke the
39703   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39704   ** assertion that the transaction counter was modified.
39705   */
39706 #ifdef SQLITE_DEBUG
39707   if( pPager->fd->pMethods ){
39708     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
39709   }
39710 #endif
39711
39712   /* If this playback is happening automatically as a result of an IO or 
39713   ** malloc error that occurred after the change-counter was updated but 
39714   ** before the transaction was committed, then the change-counter 
39715   ** modification may just have been reverted. If this happens in exclusive 
39716   ** mode, then subsequent transactions performed by the connection will not
39717   ** update the change-counter at all. This may lead to cache inconsistency
39718   ** problems for other processes at some point in the future. So, just
39719   ** in case this has happened, clear the changeCountDone flag now.
39720   */
39721   pPager->changeCountDone = pPager->tempFile;
39722
39723   if( rc==SQLITE_OK ){
39724     zMaster = pPager->pTmpSpace;
39725     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39726     testcase( rc!=SQLITE_OK );
39727   }
39728   if( rc==SQLITE_OK
39729    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39730   ){
39731     rc = sqlite3PagerSync(pPager);
39732   }
39733   if( rc==SQLITE_OK ){
39734     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39735     testcase( rc!=SQLITE_OK );
39736   }
39737   if( rc==SQLITE_OK && zMaster[0] && res ){
39738     /* If there was a master journal and this routine will return success,
39739     ** see if it is possible to delete the master journal.
39740     */
39741     rc = pager_delmaster(pPager, zMaster);
39742     testcase( rc!=SQLITE_OK );
39743   }
39744
39745   /* The Pager.sectorSize variable may have been updated while rolling
39746   ** back a journal created by a process with a different sector size
39747   ** value. Reset it to the correct value for this process.
39748   */
39749   setSectorSize(pPager);
39750   return rc;
39751 }
39752
39753
39754 /*
39755 ** Read the content for page pPg out of the database file and into 
39756 ** pPg->pData. A shared lock or greater must be held on the database
39757 ** file before this function is called.
39758 **
39759 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39760 ** the value read from the database file.
39761 **
39762 ** If an IO error occurs, then the IO error is returned to the caller.
39763 ** Otherwise, SQLITE_OK is returned.
39764 */
39765 static int readDbPage(PgHdr *pPg){
39766   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39767   Pgno pgno = pPg->pgno;       /* Page number to read */
39768   int rc = SQLITE_OK;          /* Return code */
39769   int isInWal = 0;             /* True if page is in log file */
39770   int pgsz = pPager->pageSize; /* Number of bytes to read */
39771
39772   assert( pPager->eState>=PAGER_READER && !MEMDB );
39773   assert( isOpen(pPager->fd) );
39774
39775   if( NEVER(!isOpen(pPager->fd)) ){
39776     assert( pPager->tempFile );
39777     memset(pPg->pData, 0, pPager->pageSize);
39778     return SQLITE_OK;
39779   }
39780
39781   if( pagerUseWal(pPager) ){
39782     /* Try to pull the page from the write-ahead log. */
39783     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39784   }
39785   if( rc==SQLITE_OK && !isInWal ){
39786     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39787     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39788     if( rc==SQLITE_IOERR_SHORT_READ ){
39789       rc = SQLITE_OK;
39790     }
39791   }
39792
39793   if( pgno==1 ){
39794     if( rc ){
39795       /* If the read is unsuccessful, set the dbFileVers[] to something
39796       ** that will never be a valid file version.  dbFileVers[] is a copy
39797       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
39798       ** zero or the size of the database in page. Bytes 32..35 and 35..39
39799       ** should be page numbers which are never 0xffffffff.  So filling
39800       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39801       **
39802       ** For an encrypted database, the situation is more complex:  bytes
39803       ** 24..39 of the database are white noise.  But the probability of
39804       ** white noising equaling 16 bytes of 0xff is vanishingly small so
39805       ** we should still be ok.
39806       */
39807       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39808     }else{
39809       u8 *dbFileVers = &((u8*)pPg->pData)[24];
39810       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39811     }
39812   }
39813   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39814
39815   PAGER_INCR(sqlite3_pager_readdb_count);
39816   PAGER_INCR(pPager->nRead);
39817   IOTRACE(("PGIN %p %d\n", pPager, pgno));
39818   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39819                PAGERID(pPager), pgno, pager_pagehash(pPg)));
39820
39821   return rc;
39822 }
39823
39824 /*
39825 ** Update the value of the change-counter at offsets 24 and 92 in
39826 ** the header and the sqlite version number at offset 96.
39827 **
39828 ** This is an unconditional update.  See also the pager_incr_changecounter()
39829 ** routine which only updates the change-counter if the update is actually
39830 ** needed, as determined by the pPager->changeCountDone state variable.
39831 */
39832 static void pager_write_changecounter(PgHdr *pPg){
39833   u32 change_counter;
39834
39835   /* Increment the value just read and write it back to byte 24. */
39836   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39837   put32bits(((char*)pPg->pData)+24, change_counter);
39838
39839   /* Also store the SQLite version number in bytes 96..99 and in
39840   ** bytes 92..95 store the change counter for which the version number
39841   ** is valid. */
39842   put32bits(((char*)pPg->pData)+92, change_counter);
39843   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39844 }
39845
39846 #ifndef SQLITE_OMIT_WAL
39847 /*
39848 ** This function is invoked once for each page that has already been 
39849 ** written into the log file when a WAL transaction is rolled back.
39850 ** Parameter iPg is the page number of said page. The pCtx argument 
39851 ** is actually a pointer to the Pager structure.
39852 **
39853 ** If page iPg is present in the cache, and has no outstanding references,
39854 ** it is discarded. Otherwise, if there are one or more outstanding
39855 ** references, the page content is reloaded from the database. If the
39856 ** attempt to reload content from the database is required and fails, 
39857 ** return an SQLite error code. Otherwise, SQLITE_OK.
39858 */
39859 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39860   int rc = SQLITE_OK;
39861   Pager *pPager = (Pager *)pCtx;
39862   PgHdr *pPg;
39863
39864   pPg = sqlite3PagerLookup(pPager, iPg);
39865   if( pPg ){
39866     if( sqlite3PcachePageRefcount(pPg)==1 ){
39867       sqlite3PcacheDrop(pPg);
39868     }else{
39869       rc = readDbPage(pPg);
39870       if( rc==SQLITE_OK ){
39871         pPager->xReiniter(pPg);
39872       }
39873       sqlite3PagerUnref(pPg);
39874     }
39875   }
39876
39877   /* Normally, if a transaction is rolled back, any backup processes are
39878   ** updated as data is copied out of the rollback journal and into the
39879   ** database. This is not generally possible with a WAL database, as
39880   ** rollback involves simply truncating the log file. Therefore, if one
39881   ** or more frames have already been written to the log (and therefore 
39882   ** also copied into the backup databases) as part of this transaction,
39883   ** the backups must be restarted.
39884   */
39885   sqlite3BackupRestart(pPager->pBackup);
39886
39887   return rc;
39888 }
39889
39890 /*
39891 ** This function is called to rollback a transaction on a WAL database.
39892 */
39893 static int pagerRollbackWal(Pager *pPager){
39894   int rc;                         /* Return Code */
39895   PgHdr *pList;                   /* List of dirty pages to revert */
39896
39897   /* For all pages in the cache that are currently dirty or have already
39898   ** been written (but not committed) to the log file, do one of the 
39899   ** following:
39900   **
39901   **   + Discard the cached page (if refcount==0), or
39902   **   + Reload page content from the database (if refcount>0).
39903   */
39904   pPager->dbSize = pPager->dbOrigSize;
39905   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39906   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39907   while( pList && rc==SQLITE_OK ){
39908     PgHdr *pNext = pList->pDirty;
39909     rc = pagerUndoCallback((void *)pPager, pList->pgno);
39910     pList = pNext;
39911   }
39912
39913   return rc;
39914 }
39915
39916 /*
39917 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39918 ** the contents of the list of pages headed by pList (connected by pDirty),
39919 ** this function notifies any active backup processes that the pages have
39920 ** changed. 
39921 **
39922 ** The list of pages passed into this routine is always sorted by page number.
39923 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39924 */ 
39925 static int pagerWalFrames(
39926   Pager *pPager,                  /* Pager object */
39927   PgHdr *pList,                   /* List of frames to log */
39928   Pgno nTruncate,                 /* Database size after this commit */
39929   int isCommit                    /* True if this is a commit */
39930 ){
39931   int rc;                         /* Return code */
39932   int nList;                      /* Number of pages in pList */
39933 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39934   PgHdr *p;                       /* For looping over pages */
39935 #endif
39936
39937   assert( pPager->pWal );
39938   assert( pList );
39939 #ifdef SQLITE_DEBUG
39940   /* Verify that the page list is in accending order */
39941   for(p=pList; p && p->pDirty; p=p->pDirty){
39942     assert( p->pgno < p->pDirty->pgno );
39943   }
39944 #endif
39945
39946   assert( pList->pDirty==0 || isCommit );
39947   if( isCommit ){
39948     /* If a WAL transaction is being committed, there is no point in writing
39949     ** any pages with page numbers greater than nTruncate into the WAL file.
39950     ** They will never be read by any client. So remove them from the pDirty
39951     ** list here. */
39952     PgHdr *p;
39953     PgHdr **ppNext = &pList;
39954     nList = 0;
39955     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
39956       if( p->pgno<=nTruncate ){
39957         ppNext = &p->pDirty;
39958         nList++;
39959       }
39960     }
39961     assert( pList );
39962   }else{
39963     nList = 1;
39964   }
39965   pPager->aStat[PAGER_STAT_WRITE] += nList;
39966
39967   if( pList->pgno==1 ) pager_write_changecounter(pList);
39968   rc = sqlite3WalFrames(pPager->pWal, 
39969       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
39970   );
39971   if( rc==SQLITE_OK && pPager->pBackup ){
39972     PgHdr *p;
39973     for(p=pList; p; p=p->pDirty){
39974       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39975     }
39976   }
39977
39978 #ifdef SQLITE_CHECK_PAGES
39979   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39980   for(p=pList; p; p=p->pDirty){
39981     pager_set_pagehash(p);
39982   }
39983 #endif
39984
39985   return rc;
39986 }
39987
39988 /*
39989 ** Begin a read transaction on the WAL.
39990 **
39991 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39992 ** makes a snapshot of the database at the current point in time and preserves
39993 ** that snapshot for use by the reader in spite of concurrently changes by
39994 ** other writers or checkpointers.
39995 */
39996 static int pagerBeginReadTransaction(Pager *pPager){
39997   int rc;                         /* Return code */
39998   int changed = 0;                /* True if cache must be reset */
39999
40000   assert( pagerUseWal(pPager) );
40001   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40002
40003   /* sqlite3WalEndReadTransaction() was not called for the previous
40004   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
40005   ** are in locking_mode=NORMAL and EndRead() was previously called,
40006   ** the duplicate call is harmless.
40007   */
40008   sqlite3WalEndReadTransaction(pPager->pWal);
40009
40010   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40011   if( rc!=SQLITE_OK || changed ){
40012     pager_reset(pPager);
40013   }
40014
40015   return rc;
40016 }
40017 #endif
40018
40019 /*
40020 ** This function is called as part of the transition from PAGER_OPEN
40021 ** to PAGER_READER state to determine the size of the database file
40022 ** in pages (assuming the page size currently stored in Pager.pageSize).
40023 **
40024 ** If no error occurs, SQLITE_OK is returned and the size of the database
40025 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40026 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40027 */
40028 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40029   Pgno nPage;                     /* Value to return via *pnPage */
40030
40031   /* Query the WAL sub-system for the database size. The WalDbsize()
40032   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40033   ** if the database size is not available. The database size is not
40034   ** available from the WAL sub-system if the log file is empty or
40035   ** contains no valid committed transactions.
40036   */
40037   assert( pPager->eState==PAGER_OPEN );
40038   assert( pPager->eLock>=SHARED_LOCK );
40039   nPage = sqlite3WalDbsize(pPager->pWal);
40040
40041   /* If the database size was not available from the WAL sub-system,
40042   ** determine it based on the size of the database file. If the size
40043   ** of the database file is not an integer multiple of the page-size,
40044   ** round down to the nearest page. Except, any file larger than 0
40045   ** bytes in size is considered to contain at least one page.
40046   */
40047   if( nPage==0 ){
40048     i64 n = 0;                    /* Size of db file in bytes */
40049     assert( isOpen(pPager->fd) || pPager->tempFile );
40050     if( isOpen(pPager->fd) ){
40051       int rc = sqlite3OsFileSize(pPager->fd, &n);
40052       if( rc!=SQLITE_OK ){
40053         return rc;
40054       }
40055     }
40056     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
40057   }
40058
40059   /* If the current number of pages in the file is greater than the
40060   ** configured maximum pager number, increase the allowed limit so
40061   ** that the file can be read.
40062   */
40063   if( nPage>pPager->mxPgno ){
40064     pPager->mxPgno = (Pgno)nPage;
40065   }
40066
40067   *pnPage = nPage;
40068   return SQLITE_OK;
40069 }
40070
40071 #ifndef SQLITE_OMIT_WAL
40072 /*
40073 ** Check if the *-wal file that corresponds to the database opened by pPager
40074 ** exists if the database is not empy, or verify that the *-wal file does
40075 ** not exist (by deleting it) if the database file is empty.
40076 **
40077 ** If the database is not empty and the *-wal file exists, open the pager
40078 ** in WAL mode.  If the database is empty or if no *-wal file exists and
40079 ** if no error occurs, make sure Pager.journalMode is not set to
40080 ** PAGER_JOURNALMODE_WAL.
40081 **
40082 ** Return SQLITE_OK or an error code.
40083 **
40084 ** The caller must hold a SHARED lock on the database file to call this
40085 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
40086 ** a WAL on a none-empty database, this ensures there is no race condition 
40087 ** between the xAccess() below and an xDelete() being executed by some 
40088 ** other connection.
40089 */
40090 static int pagerOpenWalIfPresent(Pager *pPager){
40091   int rc = SQLITE_OK;
40092   assert( pPager->eState==PAGER_OPEN );
40093   assert( pPager->eLock>=SHARED_LOCK );
40094
40095   if( !pPager->tempFile ){
40096     int isWal;                    /* True if WAL file exists */
40097     Pgno nPage;                   /* Size of the database file */
40098
40099     rc = pagerPagecount(pPager, &nPage);
40100     if( rc ) return rc;
40101     if( nPage==0 ){
40102       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40103       isWal = 0;
40104     }else{
40105       rc = sqlite3OsAccess(
40106           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40107       );
40108     }
40109     if( rc==SQLITE_OK ){
40110       if( isWal ){
40111         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40112         rc = sqlite3PagerOpenWal(pPager, 0);
40113       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40114         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40115       }
40116     }
40117   }
40118   return rc;
40119 }
40120 #endif
40121
40122 /*
40123 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40124 ** the entire master journal file. The case pSavepoint==NULL occurs when 
40125 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
40126 ** savepoint.
40127 **
40128 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
40129 ** being rolled back), then the rollback consists of up to three stages,
40130 ** performed in the order specified:
40131 **
40132 **   * Pages are played back from the main journal starting at byte
40133 **     offset PagerSavepoint.iOffset and continuing to 
40134 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
40135 **     file if PagerSavepoint.iHdrOffset is zero.
40136 **
40137 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40138 **     back starting from the journal header immediately following 
40139 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
40140 **
40141 **   * Pages are then played back from the sub-journal file, starting
40142 **     with the PagerSavepoint.iSubRec and continuing to the end of
40143 **     the journal file.
40144 **
40145 ** Throughout the rollback process, each time a page is rolled back, the
40146 ** corresponding bit is set in a bitvec structure (variable pDone in the
40147 ** implementation below). This is used to ensure that a page is only
40148 ** rolled back the first time it is encountered in either journal.
40149 **
40150 ** If pSavepoint is NULL, then pages are only played back from the main
40151 ** journal file. There is no need for a bitvec in this case.
40152 **
40153 ** In either case, before playback commences the Pager.dbSize variable
40154 ** is reset to the value that it held at the start of the savepoint 
40155 ** (or transaction). No page with a page-number greater than this value
40156 ** is played back. If one is encountered it is simply skipped.
40157 */
40158 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40159   i64 szJ;                 /* Effective size of the main journal */
40160   i64 iHdrOff;             /* End of first segment of main-journal records */
40161   int rc = SQLITE_OK;      /* Return code */
40162   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
40163
40164   assert( pPager->eState!=PAGER_ERROR );
40165   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40166
40167   /* Allocate a bitvec to use to store the set of pages rolled back */
40168   if( pSavepoint ){
40169     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40170     if( !pDone ){
40171       return SQLITE_NOMEM;
40172     }
40173   }
40174
40175   /* Set the database size back to the value it was before the savepoint 
40176   ** being reverted was opened.
40177   */
40178   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40179   pPager->changeCountDone = pPager->tempFile;
40180
40181   if( !pSavepoint && pagerUseWal(pPager) ){
40182     return pagerRollbackWal(pPager);
40183   }
40184
40185   /* Use pPager->journalOff as the effective size of the main rollback
40186   ** journal.  The actual file might be larger than this in
40187   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40188   ** past pPager->journalOff is off-limits to us.
40189   */
40190   szJ = pPager->journalOff;
40191   assert( pagerUseWal(pPager)==0 || szJ==0 );
40192
40193   /* Begin by rolling back records from the main journal starting at
40194   ** PagerSavepoint.iOffset and continuing to the next journal header.
40195   ** There might be records in the main journal that have a page number
40196   ** greater than the current database size (pPager->dbSize) but those
40197   ** will be skipped automatically.  Pages are added to pDone as they
40198   ** are played back.
40199   */
40200   if( pSavepoint && !pagerUseWal(pPager) ){
40201     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40202     pPager->journalOff = pSavepoint->iOffset;
40203     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40204       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40205     }
40206     assert( rc!=SQLITE_DONE );
40207   }else{
40208     pPager->journalOff = 0;
40209   }
40210
40211   /* Continue rolling back records out of the main journal starting at
40212   ** the first journal header seen and continuing until the effective end
40213   ** of the main journal file.  Continue to skip out-of-range pages and
40214   ** continue adding pages rolled back to pDone.
40215   */
40216   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40217     u32 ii;            /* Loop counter */
40218     u32 nJRec = 0;     /* Number of Journal Records */
40219     u32 dummy;
40220     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40221     assert( rc!=SQLITE_DONE );
40222
40223     /*
40224     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40225     ** test is related to ticket #2565.  See the discussion in the
40226     ** pager_playback() function for additional information.
40227     */
40228     if( nJRec==0 
40229      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40230     ){
40231       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40232     }
40233     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40234       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40235     }
40236     assert( rc!=SQLITE_DONE );
40237   }
40238   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40239
40240   /* Finally,  rollback pages from the sub-journal.  Page that were
40241   ** previously rolled back out of the main journal (and are hence in pDone)
40242   ** will be skipped.  Out-of-range pages are also skipped.
40243   */
40244   if( pSavepoint ){
40245     u32 ii;            /* Loop counter */
40246     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
40247
40248     if( pagerUseWal(pPager) ){
40249       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40250     }
40251     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40252       assert( offset==(i64)ii*(4+pPager->pageSize) );
40253       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40254     }
40255     assert( rc!=SQLITE_DONE );
40256   }
40257
40258   sqlite3BitvecDestroy(pDone);
40259   if( rc==SQLITE_OK ){
40260     pPager->journalOff = szJ;
40261   }
40262
40263   return rc;
40264 }
40265
40266 /*
40267 ** Change the maximum number of in-memory pages that are allowed.
40268 */
40269 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40270   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40271 }
40272
40273 /*
40274 ** Free as much memory as possible from the pager.
40275 */
40276 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
40277   sqlite3PcacheShrink(pPager->pPCache);
40278 }
40279
40280 /*
40281 ** Adjust the robustness of the database to damage due to OS crashes
40282 ** or power failures by changing the number of syncs()s when writing
40283 ** the rollback journal.  There are three levels:
40284 **
40285 **    OFF       sqlite3OsSync() is never called.  This is the default
40286 **              for temporary and transient files.
40287 **
40288 **    NORMAL    The journal is synced once before writes begin on the
40289 **              database.  This is normally adequate protection, but
40290 **              it is theoretically possible, though very unlikely,
40291 **              that an inopertune power failure could leave the journal
40292 **              in a state which would cause damage to the database
40293 **              when it is rolled back.
40294 **
40295 **    FULL      The journal is synced twice before writes begin on the
40296 **              database (with some additional information - the nRec field
40297 **              of the journal header - being written in between the two
40298 **              syncs).  If we assume that writing a
40299 **              single disk sector is atomic, then this mode provides
40300 **              assurance that the journal will not be corrupted to the
40301 **              point of causing damage to the database during rollback.
40302 **
40303 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40304 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40305 ** prior to the start of checkpoint and that the database file is synced
40306 ** at the conclusion of the checkpoint if the entire content of the WAL
40307 ** was written back into the database.  But no sync operations occur for
40308 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40309 ** file is synced following each commit operation, in addition to the
40310 ** syncs associated with NORMAL.
40311 **
40312 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40313 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40314 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40315 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40316 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40317 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40318 ** the xSync primitive is called and is relevant to all platforms.
40319 **
40320 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40321 ** and FULL=3.
40322 */
40323 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40324 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40325   Pager *pPager,        /* The pager to set safety level for */
40326   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
40327   int bFullFsync,       /* PRAGMA fullfsync */
40328   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40329 ){
40330   assert( level>=1 && level<=3 );
40331   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40332   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40333   if( pPager->noSync ){
40334     pPager->syncFlags = 0;
40335     pPager->ckptSyncFlags = 0;
40336   }else if( bFullFsync ){
40337     pPager->syncFlags = SQLITE_SYNC_FULL;
40338     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40339   }else if( bCkptFullFsync ){
40340     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40341     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40342   }else{
40343     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40344     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40345   }
40346   pPager->walSyncFlags = pPager->syncFlags;
40347   if( pPager->fullSync ){
40348     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
40349   }
40350 }
40351 #endif
40352
40353 /*
40354 ** The following global variable is incremented whenever the library
40355 ** attempts to open a temporary file.  This information is used for
40356 ** testing and analysis only.  
40357 */
40358 #ifdef SQLITE_TEST
40359 SQLITE_API int sqlite3_opentemp_count = 0;
40360 #endif
40361
40362 /*
40363 ** Open a temporary file.
40364 **
40365 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
40366 ** or some other error code if we fail. The OS will automatically 
40367 ** delete the temporary file when it is closed.
40368 **
40369 ** The flags passed to the VFS layer xOpen() call are those specified
40370 ** by parameter vfsFlags ORed with the following:
40371 **
40372 **     SQLITE_OPEN_READWRITE
40373 **     SQLITE_OPEN_CREATE
40374 **     SQLITE_OPEN_EXCLUSIVE
40375 **     SQLITE_OPEN_DELETEONCLOSE
40376 */
40377 static int pagerOpentemp(
40378   Pager *pPager,        /* The pager object */
40379   sqlite3_file *pFile,  /* Write the file descriptor here */
40380   int vfsFlags          /* Flags passed through to the VFS */
40381 ){
40382   int rc;               /* Return code */
40383
40384 #ifdef SQLITE_TEST
40385   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40386 #endif
40387
40388   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40389             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40390   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40391   assert( rc!=SQLITE_OK || isOpen(pFile) );
40392   return rc;
40393 }
40394
40395 /*
40396 ** Set the busy handler function.
40397 **
40398 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
40399 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40400 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
40401 ** lock. It does *not* invoke the busy handler when upgrading from
40402 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40403 ** (which occurs during hot-journal rollback). Summary:
40404 **
40405 **   Transition                        | Invokes xBusyHandler
40406 **   --------------------------------------------------------
40407 **   NO_LOCK       -> SHARED_LOCK      | Yes
40408 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40409 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40410 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40411 **
40412 ** If the busy-handler callback returns non-zero, the lock is 
40413 ** retried. If it returns zero, then the SQLITE_BUSY error is
40414 ** returned to the caller of the pager API function.
40415 */
40416 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40417   Pager *pPager,                       /* Pager object */
40418   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40419   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40420 ){  
40421   pPager->xBusyHandler = xBusyHandler;
40422   pPager->pBusyHandlerArg = pBusyHandlerArg;
40423 }
40424
40425 /*
40426 ** Change the page size used by the Pager object. The new page size 
40427 ** is passed in *pPageSize.
40428 **
40429 ** If the pager is in the error state when this function is called, it
40430 ** is a no-op. The value returned is the error state error code (i.e. 
40431 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40432 **
40433 ** Otherwise, if all of the following are true:
40434 **
40435 **   * the new page size (value of *pPageSize) is valid (a power 
40436 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40437 **
40438 **   * there are no outstanding page references, and
40439 **
40440 **   * the database is either not an in-memory database or it is
40441 **     an in-memory database that currently consists of zero pages.
40442 **
40443 ** then the pager object page size is set to *pPageSize.
40444 **
40445 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
40446 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
40447 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
40448 ** In all other cases, SQLITE_OK is returned.
40449 **
40450 ** If the page size is not changed, either because one of the enumerated
40451 ** conditions above is not true, the pager was in error state when this
40452 ** function was called, or because the memory allocation attempt failed, 
40453 ** then *pPageSize is set to the old, retained page size before returning.
40454 */
40455 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40456   int rc = SQLITE_OK;
40457
40458   /* It is not possible to do a full assert_pager_state() here, as this
40459   ** function may be called from within PagerOpen(), before the state
40460   ** of the Pager object is internally consistent.
40461   **
40462   ** At one point this function returned an error if the pager was in 
40463   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40464   ** there is at least one outstanding page reference, this function
40465   ** is a no-op for that case anyhow.
40466   */
40467
40468   u32 pageSize = *pPageSize;
40469   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40470   if( (pPager->memDb==0 || pPager->dbSize==0)
40471    && sqlite3PcacheRefCount(pPager->pPCache)==0 
40472    && pageSize && pageSize!=(u32)pPager->pageSize 
40473   ){
40474     char *pNew = NULL;             /* New temp space */
40475     i64 nByte = 0;
40476
40477     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40478       rc = sqlite3OsFileSize(pPager->fd, &nByte);
40479     }
40480     if( rc==SQLITE_OK ){
40481       pNew = (char *)sqlite3PageMalloc(pageSize);
40482       if( !pNew ) rc = SQLITE_NOMEM;
40483     }
40484
40485     if( rc==SQLITE_OK ){
40486       pager_reset(pPager);
40487       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
40488       pPager->pageSize = pageSize;
40489       sqlite3PageFree(pPager->pTmpSpace);
40490       pPager->pTmpSpace = pNew;
40491       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40492     }
40493   }
40494
40495   *pPageSize = pPager->pageSize;
40496   if( rc==SQLITE_OK ){
40497     if( nReserve<0 ) nReserve = pPager->nReserve;
40498     assert( nReserve>=0 && nReserve<1000 );
40499     pPager->nReserve = (i16)nReserve;
40500     pagerReportSize(pPager);
40501   }
40502   return rc;
40503 }
40504
40505 /*
40506 ** Return a pointer to the "temporary page" buffer held internally
40507 ** by the pager.  This is a buffer that is big enough to hold the
40508 ** entire content of a database page.  This buffer is used internally
40509 ** during rollback and will be overwritten whenever a rollback
40510 ** occurs.  But other modules are free to use it too, as long as
40511 ** no rollbacks are happening.
40512 */
40513 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40514   return pPager->pTmpSpace;
40515 }
40516
40517 /*
40518 ** Attempt to set the maximum database page count if mxPage is positive. 
40519 ** Make no changes if mxPage is zero or negative.  And never reduce the
40520 ** maximum page count below the current size of the database.
40521 **
40522 ** Regardless of mxPage, return the current maximum page count.
40523 */
40524 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40525   if( mxPage>0 ){
40526     pPager->mxPgno = mxPage;
40527   }
40528   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
40529   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
40530   return pPager->mxPgno;
40531 }
40532
40533 /*
40534 ** The following set of routines are used to disable the simulated
40535 ** I/O error mechanism.  These routines are used to avoid simulated
40536 ** errors in places where we do not care about errors.
40537 **
40538 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
40539 ** and generate no code.
40540 */
40541 #ifdef SQLITE_TEST
40542 SQLITE_API extern int sqlite3_io_error_pending;
40543 SQLITE_API extern int sqlite3_io_error_hit;
40544 static int saved_cnt;
40545 void disable_simulated_io_errors(void){
40546   saved_cnt = sqlite3_io_error_pending;
40547   sqlite3_io_error_pending = -1;
40548 }
40549 void enable_simulated_io_errors(void){
40550   sqlite3_io_error_pending = saved_cnt;
40551 }
40552 #else
40553 # define disable_simulated_io_errors()
40554 # define enable_simulated_io_errors()
40555 #endif
40556
40557 /*
40558 ** Read the first N bytes from the beginning of the file into memory
40559 ** that pDest points to. 
40560 **
40561 ** If the pager was opened on a transient file (zFilename==""), or
40562 ** opened on a file less than N bytes in size, the output buffer is
40563 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
40564 ** function is used to read database headers, and a new transient or
40565 ** zero sized database has a header than consists entirely of zeroes.
40566 **
40567 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40568 ** the error code is returned to the caller and the contents of the
40569 ** output buffer undefined.
40570 */
40571 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40572   int rc = SQLITE_OK;
40573   memset(pDest, 0, N);
40574   assert( isOpen(pPager->fd) || pPager->tempFile );
40575
40576   /* This routine is only called by btree immediately after creating
40577   ** the Pager object.  There has not been an opportunity to transition
40578   ** to WAL mode yet.
40579   */
40580   assert( !pagerUseWal(pPager) );
40581
40582   if( isOpen(pPager->fd) ){
40583     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40584     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40585     if( rc==SQLITE_IOERR_SHORT_READ ){
40586       rc = SQLITE_OK;
40587     }
40588   }
40589   return rc;
40590 }
40591
40592 /*
40593 ** This function may only be called when a read-transaction is open on
40594 ** the pager. It returns the total number of pages in the database.
40595 **
40596 ** However, if the file is between 1 and <page-size> bytes in size, then 
40597 ** this is considered a 1 page file.
40598 */
40599 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40600   assert( pPager->eState>=PAGER_READER );
40601   assert( pPager->eState!=PAGER_WRITER_FINISHED );
40602   *pnPage = (int)pPager->dbSize;
40603 }
40604
40605
40606 /*
40607 ** Try to obtain a lock of type locktype on the database file. If
40608 ** a similar or greater lock is already held, this function is a no-op
40609 ** (returning SQLITE_OK immediately).
40610 **
40611 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
40612 ** the busy callback if the lock is currently not available. Repeat 
40613 ** until the busy callback returns false or until the attempt to 
40614 ** obtain the lock succeeds.
40615 **
40616 ** Return SQLITE_OK on success and an error code if we cannot obtain
40617 ** the lock. If the lock is obtained successfully, set the Pager.state 
40618 ** variable to locktype before returning.
40619 */
40620 static int pager_wait_on_lock(Pager *pPager, int locktype){
40621   int rc;                              /* Return code */
40622
40623   /* Check that this is either a no-op (because the requested lock is 
40624   ** already held, or one of the transistions that the busy-handler
40625   ** may be invoked during, according to the comment above
40626   ** sqlite3PagerSetBusyhandler().
40627   */
40628   assert( (pPager->eLock>=locktype)
40629        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40630        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40631   );
40632
40633   do {
40634     rc = pagerLockDb(pPager, locktype);
40635   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40636   return rc;
40637 }
40638
40639 /*
40640 ** Function assertTruncateConstraint(pPager) checks that one of the 
40641 ** following is true for all dirty pages currently in the page-cache:
40642 **
40643 **   a) The page number is less than or equal to the size of the 
40644 **      current database image, in pages, OR
40645 **
40646 **   b) if the page content were written at this time, it would not
40647 **      be necessary to write the current content out to the sub-journal
40648 **      (as determined by function subjRequiresPage()).
40649 **
40650 ** If the condition asserted by this function were not true, and the
40651 ** dirty page were to be discarded from the cache via the pagerStress()
40652 ** routine, pagerStress() would not write the current page content to
40653 ** the database file. If a savepoint transaction were rolled back after
40654 ** this happened, the correct behaviour would be to restore the current
40655 ** content of the page. However, since this content is not present in either
40656 ** the database file or the portion of the rollback journal and 
40657 ** sub-journal rolled back the content could not be restored and the
40658 ** database image would become corrupt. It is therefore fortunate that 
40659 ** this circumstance cannot arise.
40660 */
40661 #if defined(SQLITE_DEBUG)
40662 static void assertTruncateConstraintCb(PgHdr *pPg){
40663   assert( pPg->flags&PGHDR_DIRTY );
40664   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40665 }
40666 static void assertTruncateConstraint(Pager *pPager){
40667   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40668 }
40669 #else
40670 # define assertTruncateConstraint(pPager)
40671 #endif
40672
40673 /*
40674 ** Truncate the in-memory database file image to nPage pages. This 
40675 ** function does not actually modify the database file on disk. It 
40676 ** just sets the internal state of the pager object so that the 
40677 ** truncation will be done when the current transaction is committed.
40678 */
40679 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40680   assert( pPager->dbSize>=nPage );
40681   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40682   pPager->dbSize = nPage;
40683   assertTruncateConstraint(pPager);
40684 }
40685
40686
40687 /*
40688 ** This function is called before attempting a hot-journal rollback. It
40689 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40690 ** size of the journal file so that the pager_playback() routine knows
40691 ** that the entire journal file has been synced.
40692 **
40693 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
40694 ** that if a power-failure occurs during the rollback, the process that
40695 ** attempts rollback following system recovery sees the same journal
40696 ** content as this process.
40697 **
40698 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
40699 ** an SQLite error code.
40700 */
40701 static int pagerSyncHotJournal(Pager *pPager){
40702   int rc = SQLITE_OK;
40703   if( !pPager->noSync ){
40704     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40705   }
40706   if( rc==SQLITE_OK ){
40707     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40708   }
40709   return rc;
40710 }
40711
40712 /*
40713 ** Shutdown the page cache.  Free all memory and close all files.
40714 **
40715 ** If a transaction was in progress when this routine is called, that
40716 ** transaction is rolled back.  All outstanding pages are invalidated
40717 ** and their memory is freed.  Any attempt to use a page associated
40718 ** with this page cache after this function returns will likely
40719 ** result in a coredump.
40720 **
40721 ** This function always succeeds. If a transaction is active an attempt
40722 ** is made to roll it back. If an error occurs during the rollback 
40723 ** a hot journal may be left in the filesystem but no error is returned
40724 ** to the caller.
40725 */
40726 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40727   u8 *pTmp = (u8 *)pPager->pTmpSpace;
40728
40729   assert( assert_pager_state(pPager) );
40730   disable_simulated_io_errors();
40731   sqlite3BeginBenignMalloc();
40732   /* pPager->errCode = 0; */
40733   pPager->exclusiveMode = 0;
40734 #ifndef SQLITE_OMIT_WAL
40735   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40736   pPager->pWal = 0;
40737 #endif
40738   pager_reset(pPager);
40739   if( MEMDB ){
40740     pager_unlock(pPager);
40741   }else{
40742     /* If it is open, sync the journal file before calling UnlockAndRollback.
40743     ** If this is not done, then an unsynced portion of the open journal 
40744     ** file may be played back into the database. If a power failure occurs 
40745     ** while this is happening, the database could become corrupt.
40746     **
40747     ** If an error occurs while trying to sync the journal, shift the pager
40748     ** into the ERROR state. This causes UnlockAndRollback to unlock the
40749     ** database and close the journal file without attempting to roll it
40750     ** back or finalize it. The next database user will have to do hot-journal
40751     ** rollback before accessing the database file.
40752     */
40753     if( isOpen(pPager->jfd) ){
40754       pager_error(pPager, pagerSyncHotJournal(pPager));
40755     }
40756     pagerUnlockAndRollback(pPager);
40757   }
40758   sqlite3EndBenignMalloc();
40759   enable_simulated_io_errors();
40760   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40761   IOTRACE(("CLOSE %p\n", pPager))
40762   sqlite3OsClose(pPager->jfd);
40763   sqlite3OsClose(pPager->fd);
40764   sqlite3PageFree(pTmp);
40765   sqlite3PcacheClose(pPager->pPCache);
40766
40767 #ifdef SQLITE_HAS_CODEC
40768   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40769 #endif
40770
40771   assert( !pPager->aSavepoint && !pPager->pInJournal );
40772   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40773
40774   sqlite3_free(pPager);
40775   return SQLITE_OK;
40776 }
40777
40778 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40779 /*
40780 ** Return the page number for page pPg.
40781 */
40782 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40783   return pPg->pgno;
40784 }
40785 #endif
40786
40787 /*
40788 ** Increment the reference count for page pPg.
40789 */
40790 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40791   sqlite3PcacheRef(pPg);
40792 }
40793
40794 /*
40795 ** Sync the journal. In other words, make sure all the pages that have
40796 ** been written to the journal have actually reached the surface of the
40797 ** disk and can be restored in the event of a hot-journal rollback.
40798 **
40799 ** If the Pager.noSync flag is set, then this function is a no-op.
40800 ** Otherwise, the actions required depend on the journal-mode and the 
40801 ** device characteristics of the file-system, as follows:
40802 **
40803 **   * If the journal file is an in-memory journal file, no action need
40804 **     be taken.
40805 **
40806 **   * Otherwise, if the device does not support the SAFE_APPEND property,
40807 **     then the nRec field of the most recently written journal header
40808 **     is updated to contain the number of journal records that have
40809 **     been written following it. If the pager is operating in full-sync
40810 **     mode, then the journal file is synced before this field is updated.
40811 **
40812 **   * If the device does not support the SEQUENTIAL property, then 
40813 **     journal file is synced.
40814 **
40815 ** Or, in pseudo-code:
40816 **
40817 **   if( NOT <in-memory journal> ){
40818 **     if( NOT SAFE_APPEND ){
40819 **       if( <full-sync mode> ) xSync(<journal file>);
40820 **       <update nRec field>
40821 **     } 
40822 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
40823 **   }
40824 **
40825 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
40826 ** page currently held in memory before returning SQLITE_OK. If an IO
40827 ** error is encountered, then the IO error code is returned to the caller.
40828 */
40829 static int syncJournal(Pager *pPager, int newHdr){
40830   int rc;                         /* Return code */
40831
40832   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40833        || pPager->eState==PAGER_WRITER_DBMOD
40834   );
40835   assert( assert_pager_state(pPager) );
40836   assert( !pagerUseWal(pPager) );
40837
40838   rc = sqlite3PagerExclusiveLock(pPager);
40839   if( rc!=SQLITE_OK ) return rc;
40840
40841   if( !pPager->noSync ){
40842     assert( !pPager->tempFile );
40843     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40844       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40845       assert( isOpen(pPager->jfd) );
40846
40847       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40848         /* This block deals with an obscure problem. If the last connection
40849         ** that wrote to this database was operating in persistent-journal
40850         ** mode, then the journal file may at this point actually be larger
40851         ** than Pager.journalOff bytes. If the next thing in the journal
40852         ** file happens to be a journal-header (written as part of the
40853         ** previous connection's transaction), and a crash or power-failure 
40854         ** occurs after nRec is updated but before this connection writes 
40855         ** anything else to the journal file (or commits/rolls back its 
40856         ** transaction), then SQLite may become confused when doing the 
40857         ** hot-journal rollback following recovery. It may roll back all
40858         ** of this connections data, then proceed to rolling back the old,
40859         ** out-of-date data that follows it. Database corruption.
40860         **
40861         ** To work around this, if the journal file does appear to contain
40862         ** a valid header following Pager.journalOff, then write a 0x00
40863         ** byte to the start of it to prevent it from being recognized.
40864         **
40865         ** Variable iNextHdrOffset is set to the offset at which this
40866         ** problematic header will occur, if it exists. aMagic is used 
40867         ** as a temporary buffer to inspect the first couple of bytes of
40868         ** the potential journal header.
40869         */
40870         i64 iNextHdrOffset;
40871         u8 aMagic[8];
40872         u8 zHeader[sizeof(aJournalMagic)+4];
40873
40874         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40875         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40876
40877         iNextHdrOffset = journalHdrOffset(pPager);
40878         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40879         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40880           static const u8 zerobyte = 0;
40881           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40882         }
40883         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40884           return rc;
40885         }
40886
40887         /* Write the nRec value into the journal file header. If in
40888         ** full-synchronous mode, sync the journal first. This ensures that
40889         ** all data has really hit the disk before nRec is updated to mark
40890         ** it as a candidate for rollback.
40891         **
40892         ** This is not required if the persistent media supports the
40893         ** SAFE_APPEND property. Because in this case it is not possible 
40894         ** for garbage data to be appended to the file, the nRec field
40895         ** is populated with 0xFFFFFFFF when the journal header is written
40896         ** and never needs to be updated.
40897         */
40898         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40899           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40900           IOTRACE(("JSYNC %p\n", pPager))
40901           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40902           if( rc!=SQLITE_OK ) return rc;
40903         }
40904         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40905         rc = sqlite3OsWrite(
40906             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40907         );
40908         if( rc!=SQLITE_OK ) return rc;
40909       }
40910       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40911         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40912         IOTRACE(("JSYNC %p\n", pPager))
40913         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
40914           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40915         );
40916         if( rc!=SQLITE_OK ) return rc;
40917       }
40918
40919       pPager->journalHdr = pPager->journalOff;
40920       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40921         pPager->nRec = 0;
40922         rc = writeJournalHdr(pPager);
40923         if( rc!=SQLITE_OK ) return rc;
40924       }
40925     }else{
40926       pPager->journalHdr = pPager->journalOff;
40927     }
40928   }
40929
40930   /* Unless the pager is in noSync mode, the journal file was just 
40931   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
40932   ** all pages.
40933   */
40934   sqlite3PcacheClearSyncFlags(pPager->pPCache);
40935   pPager->eState = PAGER_WRITER_DBMOD;
40936   assert( assert_pager_state(pPager) );
40937   return SQLITE_OK;
40938 }
40939
40940 /*
40941 ** The argument is the first in a linked list of dirty pages connected
40942 ** by the PgHdr.pDirty pointer. This function writes each one of the
40943 ** in-memory pages in the list to the database file. The argument may
40944 ** be NULL, representing an empty list. In this case this function is
40945 ** a no-op.
40946 **
40947 ** The pager must hold at least a RESERVED lock when this function
40948 ** is called. Before writing anything to the database file, this lock
40949 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40950 ** SQLITE_BUSY is returned and no data is written to the database file.
40951 ** 
40952 ** If the pager is a temp-file pager and the actual file-system file
40953 ** is not yet open, it is created and opened before any data is 
40954 ** written out.
40955 **
40956 ** Once the lock has been upgraded and, if necessary, the file opened,
40957 ** the pages are written out to the database file in list order. Writing
40958 ** a page is skipped if it meets either of the following criteria:
40959 **
40960 **   * The page number is greater than Pager.dbSize, or
40961 **   * The PGHDR_DONT_WRITE flag is set on the page.
40962 **
40963 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40964 ** is updated accordingly. If page 1 is written out, then the value cached
40965 ** in Pager.dbFileVers[] is updated to match the new value stored in
40966 ** the database file.
40967 **
40968 ** If everything is successful, SQLITE_OK is returned. If an IO error 
40969 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40970 ** be obtained, SQLITE_BUSY is returned.
40971 */
40972 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40973   int rc = SQLITE_OK;                  /* Return code */
40974
40975   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40976   assert( !pagerUseWal(pPager) );
40977   assert( pPager->eState==PAGER_WRITER_DBMOD );
40978   assert( pPager->eLock==EXCLUSIVE_LOCK );
40979
40980   /* If the file is a temp-file has not yet been opened, open it now. It
40981   ** is not possible for rc to be other than SQLITE_OK if this branch
40982   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40983   */
40984   if( !isOpen(pPager->fd) ){
40985     assert( pPager->tempFile && rc==SQLITE_OK );
40986     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40987   }
40988
40989   /* Before the first write, give the VFS a hint of what the final
40990   ** file size will be.
40991   */
40992   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40993   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40994     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40995     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40996     pPager->dbHintSize = pPager->dbSize;
40997   }
40998
40999   while( rc==SQLITE_OK && pList ){
41000     Pgno pgno = pList->pgno;
41001
41002     /* If there are dirty pages in the page cache with page numbers greater
41003     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41004     ** make the file smaller (presumably by auto-vacuum code). Do not write
41005     ** any such pages to the file.
41006     **
41007     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41008     ** set (set by sqlite3PagerDontWrite()).
41009     */
41010     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41011       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
41012       char *pData;                                   /* Data to write */    
41013
41014       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41015       if( pList->pgno==1 ) pager_write_changecounter(pList);
41016
41017       /* Encode the database */
41018       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41019
41020       /* Write out the page data. */
41021       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41022
41023       /* If page 1 was just written, update Pager.dbFileVers to match
41024       ** the value now stored in the database file. If writing this 
41025       ** page caused the database file to grow, update dbFileSize. 
41026       */
41027       if( pgno==1 ){
41028         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41029       }
41030       if( pgno>pPager->dbFileSize ){
41031         pPager->dbFileSize = pgno;
41032       }
41033       pPager->aStat[PAGER_STAT_WRITE]++;
41034
41035       /* Update any backup objects copying the contents of this pager. */
41036       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41037
41038       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41039                    PAGERID(pPager), pgno, pager_pagehash(pList)));
41040       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41041       PAGER_INCR(sqlite3_pager_writedb_count);
41042     }else{
41043       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41044     }
41045     pager_set_pagehash(pList);
41046     pList = pList->pDirty;
41047   }
41048
41049   return rc;
41050 }
41051
41052 /*
41053 ** Ensure that the sub-journal file is open. If it is already open, this 
41054 ** function is a no-op.
41055 **
41056 ** SQLITE_OK is returned if everything goes according to plan. An 
41057 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
41058 ** fails.
41059 */
41060 static int openSubJournal(Pager *pPager){
41061   int rc = SQLITE_OK;
41062   if( !isOpen(pPager->sjfd) ){
41063     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41064       sqlite3MemJournalOpen(pPager->sjfd);
41065     }else{
41066       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41067     }
41068   }
41069   return rc;
41070 }
41071
41072 /*
41073 ** Append a record of the current state of page pPg to the sub-journal. 
41074 ** It is the callers responsibility to use subjRequiresPage() to check 
41075 ** that it is really required before calling this function.
41076 **
41077 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41078 ** for all open savepoints before returning.
41079 **
41080 ** This function returns SQLITE_OK if everything is successful, an IO
41081 ** error code if the attempt to write to the sub-journal fails, or 
41082 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41083 ** bitvec.
41084 */
41085 static int subjournalPage(PgHdr *pPg){
41086   int rc = SQLITE_OK;
41087   Pager *pPager = pPg->pPager;
41088   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41089
41090     /* Open the sub-journal, if it has not already been opened */
41091     assert( pPager->useJournal );
41092     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41093     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41094     assert( pagerUseWal(pPager) 
41095          || pageInJournal(pPg) 
41096          || pPg->pgno>pPager->dbOrigSize 
41097     );
41098     rc = openSubJournal(pPager);
41099
41100     /* If the sub-journal was opened successfully (or was already open),
41101     ** write the journal record into the file.  */
41102     if( rc==SQLITE_OK ){
41103       void *pData = pPg->pData;
41104       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
41105       char *pData2;
41106   
41107       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41108       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41109       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41110       if( rc==SQLITE_OK ){
41111         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41112       }
41113     }
41114   }
41115   if( rc==SQLITE_OK ){
41116     pPager->nSubRec++;
41117     assert( pPager->nSavepoint>0 );
41118     rc = addToSavepointBitvecs(pPager, pPg->pgno);
41119   }
41120   return rc;
41121 }
41122
41123 /*
41124 ** This function is called by the pcache layer when it has reached some
41125 ** soft memory limit. The first argument is a pointer to a Pager object
41126 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41127 ** database). The second argument is a reference to a page that is 
41128 ** currently dirty but has no outstanding references. The page
41129 ** is always associated with the Pager object passed as the first 
41130 ** argument.
41131 **
41132 ** The job of this function is to make pPg clean by writing its contents
41133 ** out to the database file, if possible. This may involve syncing the
41134 ** journal file. 
41135 **
41136 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41137 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41138 ** page clean, the IO error code is returned. If the page cannot be
41139 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41140 ** is returned by sqlite3PcacheMakeClean() is not called.
41141 */
41142 static int pagerStress(void *p, PgHdr *pPg){
41143   Pager *pPager = (Pager *)p;
41144   int rc = SQLITE_OK;
41145
41146   assert( pPg->pPager==pPager );
41147   assert( pPg->flags&PGHDR_DIRTY );
41148
41149   /* The doNotSyncSpill flag is set during times when doing a sync of
41150   ** journal (and adding a new header) is not allowed.  This occurs
41151   ** during calls to sqlite3PagerWrite() while trying to journal multiple
41152   ** pages belonging to the same sector.
41153   **
41154   ** The doNotSpill flag inhibits all cache spilling regardless of whether
41155   ** or not a sync is required.  This is set during a rollback.
41156   **
41157   ** Spilling is also prohibited when in an error state since that could
41158   ** lead to database corruption.   In the current implementaton it 
41159   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
41160   ** while in the error state, hence it is impossible for this routine to
41161   ** be called in the error state.  Nevertheless, we include a NEVER()
41162   ** test for the error state as a safeguard against future changes.
41163   */
41164   if( NEVER(pPager->errCode) ) return SQLITE_OK;
41165   if( pPager->doNotSpill ) return SQLITE_OK;
41166   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41167     return SQLITE_OK;
41168   }
41169
41170   pPg->pDirty = 0;
41171   if( pagerUseWal(pPager) ){
41172     /* Write a single frame for this page to the log. */
41173     if( subjRequiresPage(pPg) ){ 
41174       rc = subjournalPage(pPg); 
41175     }
41176     if( rc==SQLITE_OK ){
41177       rc = pagerWalFrames(pPager, pPg, 0, 0);
41178     }
41179   }else{
41180   
41181     /* Sync the journal file if required. */
41182     if( pPg->flags&PGHDR_NEED_SYNC 
41183      || pPager->eState==PAGER_WRITER_CACHEMOD
41184     ){
41185       rc = syncJournal(pPager, 1);
41186     }
41187   
41188     /* If the page number of this page is larger than the current size of
41189     ** the database image, it may need to be written to the sub-journal.
41190     ** This is because the call to pager_write_pagelist() below will not
41191     ** actually write data to the file in this case.
41192     **
41193     ** Consider the following sequence of events:
41194     **
41195     **   BEGIN;
41196     **     <journal page X>
41197     **     <modify page X>
41198     **     SAVEPOINT sp;
41199     **       <shrink database file to Y pages>
41200     **       pagerStress(page X)
41201     **     ROLLBACK TO sp;
41202     **
41203     ** If (X>Y), then when pagerStress is called page X will not be written
41204     ** out to the database file, but will be dropped from the cache. Then,
41205     ** following the "ROLLBACK TO sp" statement, reading page X will read
41206     ** data from the database file. This will be the copy of page X as it
41207     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41208     ** was executed.
41209     **
41210     ** The solution is to write the current data for page X into the 
41211     ** sub-journal file now (if it is not already there), so that it will
41212     ** be restored to its current value when the "ROLLBACK TO sp" is 
41213     ** executed.
41214     */
41215     if( NEVER(
41216         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41217     ) ){
41218       rc = subjournalPage(pPg);
41219     }
41220   
41221     /* Write the contents of the page out to the database file. */
41222     if( rc==SQLITE_OK ){
41223       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41224       rc = pager_write_pagelist(pPager, pPg);
41225     }
41226   }
41227
41228   /* Mark the page as clean. */
41229   if( rc==SQLITE_OK ){
41230     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41231     sqlite3PcacheMakeClean(pPg);
41232   }
41233
41234   return pager_error(pPager, rc); 
41235 }
41236
41237
41238 /*
41239 ** Allocate and initialize a new Pager object and put a pointer to it
41240 ** in *ppPager. The pager should eventually be freed by passing it
41241 ** to sqlite3PagerClose().
41242 **
41243 ** The zFilename argument is the path to the database file to open.
41244 ** If zFilename is NULL then a randomly-named temporary file is created
41245 ** and used as the file to be cached. Temporary files are be deleted
41246 ** automatically when they are closed. If zFilename is ":memory:" then 
41247 ** all information is held in cache. It is never written to disk. 
41248 ** This can be used to implement an in-memory database.
41249 **
41250 ** The nExtra parameter specifies the number of bytes of space allocated
41251 ** along with each page reference. This space is available to the user
41252 ** via the sqlite3PagerGetExtra() API.
41253 **
41254 ** The flags argument is used to specify properties that affect the
41255 ** operation of the pager. It should be passed some bitwise combination
41256 ** of the PAGER_* flags.
41257 **
41258 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41259 ** of the xOpen() method of the supplied VFS when opening files. 
41260 **
41261 ** If the pager object is allocated and the specified file opened 
41262 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41263 ** the new pager object. If an error occurs, *ppPager is set to NULL
41264 ** and error code returned. This function may return SQLITE_NOMEM
41265 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
41266 ** various SQLITE_IO_XXX errors.
41267 */
41268 SQLITE_PRIVATE int sqlite3PagerOpen(
41269   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41270   Pager **ppPager,         /* OUT: Return the Pager structure here */
41271   const char *zFilename,   /* Name of the database file to open */
41272   int nExtra,              /* Extra bytes append to each in-memory page */
41273   int flags,               /* flags controlling this file */
41274   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41275   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41276 ){
41277   u8 *pPtr;
41278   Pager *pPager = 0;       /* Pager object to allocate and return */
41279   int rc = SQLITE_OK;      /* Return code */
41280   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41281   int memDb = 0;           /* True if this is an in-memory file */
41282   int readOnly = 0;        /* True if this is a read-only file */
41283   int journalFileSize;     /* Bytes to allocate for each journal fd */
41284   char *zPathname = 0;     /* Full path to database file */
41285   int nPathname = 0;       /* Number of bytes in zPathname */
41286   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41287   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41288   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41289   const char *zUri = 0;    /* URI args to copy */
41290   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41291
41292   /* Figure out how much space is required for each journal file-handle
41293   ** (there are two of them, the main journal and the sub-journal). This
41294   ** is the maximum space required for an in-memory journal file handle 
41295   ** and a regular journal file-handle. Note that a "regular journal-handle"
41296   ** may be a wrapper capable of caching the first portion of the journal
41297   ** file in memory to implement the atomic-write optimization (see 
41298   ** source file journal.c).
41299   */
41300   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41301     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41302   }else{
41303     journalFileSize = ROUND8(sqlite3MemJournalSize());
41304   }
41305
41306   /* Set the output variable to NULL in case an error occurs. */
41307   *ppPager = 0;
41308
41309 #ifndef SQLITE_OMIT_MEMORYDB
41310   if( flags & PAGER_MEMORY ){
41311     memDb = 1;
41312     if( zFilename && zFilename[0] ){
41313       zPathname = sqlite3DbStrDup(0, zFilename);
41314       if( zPathname==0  ) return SQLITE_NOMEM;
41315       nPathname = sqlite3Strlen30(zPathname);
41316       zFilename = 0;
41317     }
41318   }
41319 #endif
41320
41321   /* Compute and store the full pathname in an allocated buffer pointed
41322   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41323   ** leave both nPathname and zPathname set to 0.
41324   */
41325   if( zFilename && zFilename[0] ){
41326     const char *z;
41327     nPathname = pVfs->mxPathname+1;
41328     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
41329     if( zPathname==0 ){
41330       return SQLITE_NOMEM;
41331     }
41332     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41333     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41334     nPathname = sqlite3Strlen30(zPathname);
41335     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41336     while( *z ){
41337       z += sqlite3Strlen30(z)+1;
41338       z += sqlite3Strlen30(z)+1;
41339     }
41340     nUri = (int)(&z[1] - zUri);
41341     assert( nUri>=0 );
41342     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41343       /* This branch is taken when the journal path required by
41344       ** the database being opened will be more than pVfs->mxPathname
41345       ** bytes in length. This means the database cannot be opened,
41346       ** as it will not be possible to open the journal file or even
41347       ** check for a hot-journal before reading.
41348       */
41349       rc = SQLITE_CANTOPEN_BKPT;
41350     }
41351     if( rc!=SQLITE_OK ){
41352       sqlite3DbFree(0, zPathname);
41353       return rc;
41354     }
41355   }
41356
41357   /* Allocate memory for the Pager structure, PCache object, the
41358   ** three file descriptors, the database file name and the journal 
41359   ** file name. The layout in memory is as follows:
41360   **
41361   **     Pager object                    (sizeof(Pager) bytes)
41362   **     PCache object                   (sqlite3PcacheSize() bytes)
41363   **     Database file handle            (pVfs->szOsFile bytes)
41364   **     Sub-journal file handle         (journalFileSize bytes)
41365   **     Main journal file handle        (journalFileSize bytes)
41366   **     Database file name              (nPathname+1 bytes)
41367   **     Journal file name               (nPathname+8+1 bytes)
41368   */
41369   pPtr = (u8 *)sqlite3MallocZero(
41370     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41371     ROUND8(pcacheSize) +           /* PCache object */
41372     ROUND8(pVfs->szOsFile) +       /* The main db file */
41373     journalFileSize * 2 +          /* The two journal files */ 
41374     nPathname + 1 + nUri +         /* zFilename */
41375     nPathname + 8 + 2              /* zJournal */
41376 #ifndef SQLITE_OMIT_WAL
41377     + nPathname + 4 + 2            /* zWal */
41378 #endif
41379   );
41380   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41381   if( !pPtr ){
41382     sqlite3DbFree(0, zPathname);
41383     return SQLITE_NOMEM;
41384   }
41385   pPager =              (Pager*)(pPtr);
41386   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41387   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41388   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41389   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41390   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41391   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41392
41393   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41394   if( zPathname ){
41395     assert( nPathname>0 );
41396     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41397     memcpy(pPager->zFilename, zPathname, nPathname);
41398     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41399     memcpy(pPager->zJournal, zPathname, nPathname);
41400     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
41401     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41402 #ifndef SQLITE_OMIT_WAL
41403     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41404     memcpy(pPager->zWal, zPathname, nPathname);
41405     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
41406     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41407 #endif
41408     sqlite3DbFree(0, zPathname);
41409   }
41410   pPager->pVfs = pVfs;
41411   pPager->vfsFlags = vfsFlags;
41412
41413   /* Open the pager file.
41414   */
41415   if( zFilename && zFilename[0] ){
41416     int fout = 0;                    /* VFS flags returned by xOpen() */
41417     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41418     assert( !memDb );
41419     readOnly = (fout&SQLITE_OPEN_READONLY);
41420
41421     /* If the file was successfully opened for read/write access,
41422     ** choose a default page size in case we have to create the
41423     ** database file. The default page size is the maximum of:
41424     **
41425     **    + SQLITE_DEFAULT_PAGE_SIZE,
41426     **    + The value returned by sqlite3OsSectorSize()
41427     **    + The largest page size that can be written atomically.
41428     */
41429     if( rc==SQLITE_OK && !readOnly ){
41430       setSectorSize(pPager);
41431       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41432       if( szPageDflt<pPager->sectorSize ){
41433         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41434           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41435         }else{
41436           szPageDflt = (u32)pPager->sectorSize;
41437         }
41438       }
41439 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41440       {
41441         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41442         int ii;
41443         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41444         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41445         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41446         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41447           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41448             szPageDflt = ii;
41449           }
41450         }
41451       }
41452 #endif
41453     }
41454   }else{
41455     /* If a temporary file is requested, it is not opened immediately.
41456     ** In this case we accept the default page size and delay actually
41457     ** opening the file until the first call to OsWrite().
41458     **
41459     ** This branch is also run for an in-memory database. An in-memory
41460     ** database is the same as a temp-file that is never written out to
41461     ** disk and uses an in-memory rollback journal.
41462     */ 
41463     tempFile = 1;
41464     pPager->eState = PAGER_READER;
41465     pPager->eLock = EXCLUSIVE_LOCK;
41466     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41467   }
41468
41469   /* The following call to PagerSetPagesize() serves to set the value of 
41470   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41471   */
41472   if( rc==SQLITE_OK ){
41473     assert( pPager->memDb==0 );
41474     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41475     testcase( rc!=SQLITE_OK );
41476   }
41477
41478   /* If an error occurred in either of the blocks above, free the 
41479   ** Pager structure and close the file.
41480   */
41481   if( rc!=SQLITE_OK ){
41482     assert( !pPager->pTmpSpace );
41483     sqlite3OsClose(pPager->fd);
41484     sqlite3_free(pPager);
41485     return rc;
41486   }
41487
41488   /* Initialize the PCache object. */
41489   assert( nExtra<1000 );
41490   nExtra = ROUND8(nExtra);
41491   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41492                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41493
41494   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41495   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41496
41497   pPager->useJournal = (u8)useJournal;
41498   /* pPager->stmtOpen = 0; */
41499   /* pPager->stmtInUse = 0; */
41500   /* pPager->nRef = 0; */
41501   /* pPager->stmtSize = 0; */
41502   /* pPager->stmtJSize = 0; */
41503   /* pPager->nPage = 0; */
41504   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41505   /* pPager->state = PAGER_UNLOCK; */
41506 #if 0
41507   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41508 #endif
41509   /* pPager->errMask = 0; */
41510   pPager->tempFile = (u8)tempFile;
41511   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
41512           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41513   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41514   pPager->exclusiveMode = (u8)tempFile; 
41515   pPager->changeCountDone = pPager->tempFile;
41516   pPager->memDb = (u8)memDb;
41517   pPager->readOnly = (u8)readOnly;
41518   assert( useJournal || pPager->tempFile );
41519   pPager->noSync = pPager->tempFile;
41520   if( pPager->noSync ){
41521     assert( pPager->fullSync==0 );
41522     assert( pPager->syncFlags==0 );
41523     assert( pPager->walSyncFlags==0 );
41524     assert( pPager->ckptSyncFlags==0 );
41525   }else{
41526     pPager->fullSync = 1;
41527     pPager->syncFlags = SQLITE_SYNC_NORMAL;
41528     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
41529     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41530   }
41531   /* pPager->pFirst = 0; */
41532   /* pPager->pFirstSynced = 0; */
41533   /* pPager->pLast = 0; */
41534   pPager->nExtra = (u16)nExtra;
41535   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
41536   assert( isOpen(pPager->fd) || tempFile );
41537   setSectorSize(pPager);
41538   if( !useJournal ){
41539     pPager->journalMode = PAGER_JOURNALMODE_OFF;
41540   }else if( memDb ){
41541     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
41542   }
41543   /* pPager->xBusyHandler = 0; */
41544   /* pPager->pBusyHandlerArg = 0; */
41545   pPager->xReiniter = xReinit;
41546   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
41547
41548   *ppPager = pPager;
41549   return SQLITE_OK;
41550 }
41551
41552
41553
41554 /*
41555 ** This function is called after transitioning from PAGER_UNLOCK to
41556 ** PAGER_SHARED state. It tests if there is a hot journal present in
41557 ** the file-system for the given pager. A hot journal is one that 
41558 ** needs to be played back. According to this function, a hot-journal
41559 ** file exists if the following criteria are met:
41560 **
41561 **   * The journal file exists in the file system, and
41562 **   * No process holds a RESERVED or greater lock on the database file, and
41563 **   * The database file itself is greater than 0 bytes in size, and
41564 **   * The first byte of the journal file exists and is not 0x00.
41565 **
41566 ** If the current size of the database file is 0 but a journal file
41567 ** exists, that is probably an old journal left over from a prior
41568 ** database with the same name. In this case the journal file is
41569 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
41570 ** is returned.
41571 **
41572 ** This routine does not check if there is a master journal filename
41573 ** at the end of the file. If there is, and that master journal file
41574 ** does not exist, then the journal file is not really hot. In this
41575 ** case this routine will return a false-positive. The pager_playback()
41576 ** routine will discover that the journal file is not really hot and 
41577 ** will not roll it back. 
41578 **
41579 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
41580 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41581 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41582 ** to determine whether or not a hot-journal file exists, the IO error
41583 ** code is returned and the value of *pExists is undefined.
41584 */
41585 static int hasHotJournal(Pager *pPager, int *pExists){
41586   sqlite3_vfs * const pVfs = pPager->pVfs;
41587   int rc = SQLITE_OK;           /* Return code */
41588   int exists = 1;               /* True if a journal file is present */
41589   int jrnlOpen = !!isOpen(pPager->jfd);
41590
41591   assert( pPager->useJournal );
41592   assert( isOpen(pPager->fd) );
41593   assert( pPager->eState==PAGER_OPEN );
41594
41595   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41596     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41597   ));
41598
41599   *pExists = 0;
41600   if( !jrnlOpen ){
41601     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41602   }
41603   if( rc==SQLITE_OK && exists ){
41604     int locked = 0;             /* True if some process holds a RESERVED lock */
41605
41606     /* Race condition here:  Another process might have been holding the
41607     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
41608     ** call above, but then delete the journal and drop the lock before
41609     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
41610     ** is the case, this routine might think there is a hot journal when
41611     ** in fact there is none.  This results in a false-positive which will
41612     ** be dealt with by the playback routine.  Ticket #3883.
41613     */
41614     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41615     if( rc==SQLITE_OK && !locked ){
41616       Pgno nPage;                 /* Number of pages in database file */
41617
41618       /* Check the size of the database file. If it consists of 0 pages,
41619       ** then delete the journal file. See the header comment above for 
41620       ** the reasoning here.  Delete the obsolete journal file under
41621       ** a RESERVED lock to avoid race conditions and to avoid violating
41622       ** [H33020].
41623       */
41624       rc = pagerPagecount(pPager, &nPage);
41625       if( rc==SQLITE_OK ){
41626         if( nPage==0 ){
41627           sqlite3BeginBenignMalloc();
41628           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41629             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41630             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41631           }
41632           sqlite3EndBenignMalloc();
41633         }else{
41634           /* The journal file exists and no other connection has a reserved
41635           ** or greater lock on the database file. Now check that there is
41636           ** at least one non-zero bytes at the start of the journal file.
41637           ** If there is, then we consider this journal to be hot. If not, 
41638           ** it can be ignored.
41639           */
41640           if( !jrnlOpen ){
41641             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41642             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41643           }
41644           if( rc==SQLITE_OK ){
41645             u8 first = 0;
41646             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41647             if( rc==SQLITE_IOERR_SHORT_READ ){
41648               rc = SQLITE_OK;
41649             }
41650             if( !jrnlOpen ){
41651               sqlite3OsClose(pPager->jfd);
41652             }
41653             *pExists = (first!=0);
41654           }else if( rc==SQLITE_CANTOPEN ){
41655             /* If we cannot open the rollback journal file in order to see if
41656             ** its has a zero header, that might be due to an I/O error, or
41657             ** it might be due to the race condition described above and in
41658             ** ticket #3883.  Either way, assume that the journal is hot.
41659             ** This might be a false positive.  But if it is, then the
41660             ** automatic journal playback and recovery mechanism will deal
41661             ** with it under an EXCLUSIVE lock where we do not need to
41662             ** worry so much with race conditions.
41663             */
41664             *pExists = 1;
41665             rc = SQLITE_OK;
41666           }
41667         }
41668       }
41669     }
41670   }
41671
41672   return rc;
41673 }
41674
41675 /*
41676 ** This function is called to obtain a shared lock on the database file.
41677 ** It is illegal to call sqlite3PagerAcquire() until after this function
41678 ** has been successfully called. If a shared-lock is already held when
41679 ** this function is called, it is a no-op.
41680 **
41681 ** The following operations are also performed by this function.
41682 **
41683 **   1) If the pager is currently in PAGER_OPEN state (no lock held
41684 **      on the database file), then an attempt is made to obtain a
41685 **      SHARED lock on the database file. Immediately after obtaining
41686 **      the SHARED lock, the file-system is checked for a hot-journal,
41687 **      which is played back if present. Following any hot-journal 
41688 **      rollback, the contents of the cache are validated by checking
41689 **      the 'change-counter' field of the database file header and
41690 **      discarded if they are found to be invalid.
41691 **
41692 **   2) If the pager is running in exclusive-mode, and there are currently
41693 **      no outstanding references to any pages, and is in the error state,
41694 **      then an attempt is made to clear the error state by discarding
41695 **      the contents of the page cache and rolling back any open journal
41696 **      file.
41697 **
41698 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41699 ** occurs while locking the database, checking for a hot-journal file or 
41700 ** rolling back a journal file, the IO error code is returned.
41701 */
41702 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41703   int rc = SQLITE_OK;                /* Return code */
41704
41705   /* This routine is only called from b-tree and only when there are no
41706   ** outstanding pages. This implies that the pager state should either
41707   ** be OPEN or READER. READER is only possible if the pager is or was in 
41708   ** exclusive access mode.
41709   */
41710   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41711   assert( assert_pager_state(pPager) );
41712   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41713   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41714
41715   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41716     int bHotJournal = 1;          /* True if there exists a hot journal-file */
41717
41718     assert( !MEMDB );
41719
41720     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41721     if( rc!=SQLITE_OK ){
41722       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41723       goto failed;
41724     }
41725
41726     /* If a journal file exists, and there is no RESERVED lock on the
41727     ** database file, then it either needs to be played back or deleted.
41728     */
41729     if( pPager->eLock<=SHARED_LOCK ){
41730       rc = hasHotJournal(pPager, &bHotJournal);
41731     }
41732     if( rc!=SQLITE_OK ){
41733       goto failed;
41734     }
41735     if( bHotJournal ){
41736       /* Get an EXCLUSIVE lock on the database file. At this point it is
41737       ** important that a RESERVED lock is not obtained on the way to the
41738       ** EXCLUSIVE lock. If it were, another process might open the
41739       ** database file, detect the RESERVED lock, and conclude that the
41740       ** database is safe to read while this process is still rolling the 
41741       ** hot-journal back.
41742       ** 
41743       ** Because the intermediate RESERVED lock is not requested, any
41744       ** other process attempting to access the database file will get to 
41745       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
41746       ** on the database file.
41747       **
41748       ** Unless the pager is in locking_mode=exclusive mode, the lock is
41749       ** downgraded to SHARED_LOCK before this function returns.
41750       */
41751       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41752       if( rc!=SQLITE_OK ){
41753         goto failed;
41754       }
41755  
41756       /* If it is not already open and the file exists on disk, open the 
41757       ** journal for read/write access. Write access is required because 
41758       ** in exclusive-access mode the file descriptor will be kept open 
41759       ** and possibly used for a transaction later on. Also, write-access 
41760       ** is usually required to finalize the journal in journal_mode=persist 
41761       ** mode (and also for journal_mode=truncate on some systems).
41762       **
41763       ** If the journal does not exist, it usually means that some 
41764       ** other connection managed to get in and roll it back before 
41765       ** this connection obtained the exclusive lock above. Or, it 
41766       ** may mean that the pager was in the error-state when this
41767       ** function was called and the journal file does not exist.
41768       */
41769       if( !isOpen(pPager->jfd) ){
41770         sqlite3_vfs * const pVfs = pPager->pVfs;
41771         int bExists;              /* True if journal file exists */
41772         rc = sqlite3OsAccess(
41773             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41774         if( rc==SQLITE_OK && bExists ){
41775           int fout = 0;
41776           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41777           assert( !pPager->tempFile );
41778           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41779           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41780           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41781             rc = SQLITE_CANTOPEN_BKPT;
41782             sqlite3OsClose(pPager->jfd);
41783           }
41784         }
41785       }
41786  
41787       /* Playback and delete the journal.  Drop the database write
41788       ** lock and reacquire the read lock. Purge the cache before
41789       ** playing back the hot-journal so that we don't end up with
41790       ** an inconsistent cache.  Sync the hot journal before playing
41791       ** it back since the process that crashed and left the hot journal
41792       ** probably did not sync it and we are required to always sync
41793       ** the journal before playing it back.
41794       */
41795       if( isOpen(pPager->jfd) ){
41796         assert( rc==SQLITE_OK );
41797         rc = pagerSyncHotJournal(pPager);
41798         if( rc==SQLITE_OK ){
41799           rc = pager_playback(pPager, 1);
41800           pPager->eState = PAGER_OPEN;
41801         }
41802       }else if( !pPager->exclusiveMode ){
41803         pagerUnlockDb(pPager, SHARED_LOCK);
41804       }
41805
41806       if( rc!=SQLITE_OK ){
41807         /* This branch is taken if an error occurs while trying to open
41808         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41809         ** pager_unlock() routine will be called before returning to unlock
41810         ** the file. If the unlock attempt fails, then Pager.eLock must be
41811         ** set to UNKNOWN_LOCK (see the comment above the #define for 
41812         ** UNKNOWN_LOCK above for an explanation). 
41813         **
41814         ** In order to get pager_unlock() to do this, set Pager.eState to
41815         ** PAGER_ERROR now. This is not actually counted as a transition
41816         ** to ERROR state in the state diagram at the top of this file,
41817         ** since we know that the same call to pager_unlock() will very
41818         ** shortly transition the pager object to the OPEN state. Calling
41819         ** assert_pager_state() would fail now, as it should not be possible
41820         ** to be in ERROR state when there are zero outstanding page 
41821         ** references.
41822         */
41823         pager_error(pPager, rc);
41824         goto failed;
41825       }
41826
41827       assert( pPager->eState==PAGER_OPEN );
41828       assert( (pPager->eLock==SHARED_LOCK)
41829            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41830       );
41831     }
41832
41833     if( !pPager->tempFile 
41834      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
41835     ){
41836       /* The shared-lock has just been acquired on the database file
41837       ** and there are already pages in the cache (from a previous
41838       ** read or write transaction).  Check to see if the database
41839       ** has been modified.  If the database has changed, flush the
41840       ** cache.
41841       **
41842       ** Database changes is detected by looking at 15 bytes beginning
41843       ** at offset 24 into the file.  The first 4 of these 16 bytes are
41844       ** a 32-bit counter that is incremented with each change.  The
41845       ** other bytes change randomly with each file change when
41846       ** a codec is in use.
41847       ** 
41848       ** There is a vanishingly small chance that a change will not be 
41849       ** detected.  The chance of an undetected change is so small that
41850       ** it can be neglected.
41851       */
41852       Pgno nPage = 0;
41853       char dbFileVers[sizeof(pPager->dbFileVers)];
41854
41855       rc = pagerPagecount(pPager, &nPage);
41856       if( rc ) goto failed;
41857
41858       if( nPage>0 ){
41859         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41860         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41861         if( rc!=SQLITE_OK ){
41862           goto failed;
41863         }
41864       }else{
41865         memset(dbFileVers, 0, sizeof(dbFileVers));
41866       }
41867
41868       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41869         pager_reset(pPager);
41870       }
41871     }
41872
41873     /* If there is a WAL file in the file-system, open this database in WAL
41874     ** mode. Otherwise, the following function call is a no-op.
41875     */
41876     rc = pagerOpenWalIfPresent(pPager);
41877 #ifndef SQLITE_OMIT_WAL
41878     assert( pPager->pWal==0 || rc==SQLITE_OK );
41879 #endif
41880   }
41881
41882   if( pagerUseWal(pPager) ){
41883     assert( rc==SQLITE_OK );
41884     rc = pagerBeginReadTransaction(pPager);
41885   }
41886
41887   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41888     rc = pagerPagecount(pPager, &pPager->dbSize);
41889   }
41890
41891  failed:
41892   if( rc!=SQLITE_OK ){
41893     assert( !MEMDB );
41894     pager_unlock(pPager);
41895     assert( pPager->eState==PAGER_OPEN );
41896   }else{
41897     pPager->eState = PAGER_READER;
41898   }
41899   return rc;
41900 }
41901
41902 /*
41903 ** If the reference count has reached zero, rollback any active
41904 ** transaction and unlock the pager.
41905 **
41906 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41907 ** the rollback journal, the unlock is not performed and there is
41908 ** nothing to rollback, so this routine is a no-op.
41909 */ 
41910 static void pagerUnlockIfUnused(Pager *pPager){
41911   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41912     pagerUnlockAndRollback(pPager);
41913   }
41914 }
41915
41916 /*
41917 ** Acquire a reference to page number pgno in pager pPager (a page
41918 ** reference has type DbPage*). If the requested reference is 
41919 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41920 **
41921 ** If the requested page is already in the cache, it is returned. 
41922 ** Otherwise, a new page object is allocated and populated with data
41923 ** read from the database file. In some cases, the pcache module may
41924 ** choose not to allocate a new page object and may reuse an existing
41925 ** object with no outstanding references.
41926 **
41927 ** The extra data appended to a page is always initialized to zeros the 
41928 ** first time a page is loaded into memory. If the page requested is 
41929 ** already in the cache when this function is called, then the extra
41930 ** data is left as it was when the page object was last used.
41931 **
41932 ** If the database image is smaller than the requested page or if a 
41933 ** non-zero value is passed as the noContent parameter and the 
41934 ** requested page is not already stored in the cache, then no 
41935 ** actual disk read occurs. In this case the memory image of the 
41936 ** page is initialized to all zeros. 
41937 **
41938 ** If noContent is true, it means that we do not care about the contents
41939 ** of the page. This occurs in two seperate scenarios:
41940 **
41941 **   a) When reading a free-list leaf page from the database, and
41942 **
41943 **   b) When a savepoint is being rolled back and we need to load
41944 **      a new page into the cache to be filled with the data read
41945 **      from the savepoint journal.
41946 **
41947 ** If noContent is true, then the data returned is zeroed instead of
41948 ** being read from the database. Additionally, the bits corresponding
41949 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41950 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41951 ** savepoints are set. This means if the page is made writable at any
41952 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41953 ** will not be journaled. This saves IO.
41954 **
41955 ** The acquisition might fail for several reasons.  In all cases,
41956 ** an appropriate error code is returned and *ppPage is set to NULL.
41957 **
41958 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
41959 ** to find a page in the in-memory cache first.  If the page is not already
41960 ** in memory, this routine goes to disk to read it in whereas Lookup()
41961 ** just returns 0.  This routine acquires a read-lock the first time it
41962 ** has to go to disk, and could also playback an old journal if necessary.
41963 ** Since Lookup() never goes to disk, it never has to deal with locks
41964 ** or journal files.
41965 */
41966 SQLITE_PRIVATE int sqlite3PagerAcquire(
41967   Pager *pPager,      /* The pager open on the database file */
41968   Pgno pgno,          /* Page number to fetch */
41969   DbPage **ppPage,    /* Write a pointer to the page here */
41970   int noContent       /* Do not bother reading content from disk if true */
41971 ){
41972   int rc;
41973   PgHdr *pPg;
41974
41975   assert( pPager->eState>=PAGER_READER );
41976   assert( assert_pager_state(pPager) );
41977
41978   if( pgno==0 ){
41979     return SQLITE_CORRUPT_BKPT;
41980   }
41981
41982   /* If the pager is in the error state, return an error immediately. 
41983   ** Otherwise, request the page from the PCache layer. */
41984   if( pPager->errCode!=SQLITE_OK ){
41985     rc = pPager->errCode;
41986   }else{
41987     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41988   }
41989
41990   if( rc!=SQLITE_OK ){
41991     /* Either the call to sqlite3PcacheFetch() returned an error or the
41992     ** pager was already in the error-state when this function was called.
41993     ** Set pPg to 0 and jump to the exception handler.  */
41994     pPg = 0;
41995     goto pager_acquire_err;
41996   }
41997   assert( (*ppPage)->pgno==pgno );
41998   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41999
42000   if( (*ppPage)->pPager && !noContent ){
42001     /* In this case the pcache already contains an initialized copy of
42002     ** the page. Return without further ado.  */
42003     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42004     pPager->aStat[PAGER_STAT_HIT]++;
42005     return SQLITE_OK;
42006
42007   }else{
42008     /* The pager cache has created a new page. Its content needs to 
42009     ** be initialized.  */
42010
42011     pPg = *ppPage;
42012     pPg->pPager = pPager;
42013
42014     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42015     ** number greater than this, or the unused locking-page, is requested. */
42016     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42017       rc = SQLITE_CORRUPT_BKPT;
42018       goto pager_acquire_err;
42019     }
42020
42021     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42022       if( pgno>pPager->mxPgno ){
42023         rc = SQLITE_FULL;
42024         goto pager_acquire_err;
42025       }
42026       if( noContent ){
42027         /* Failure to set the bits in the InJournal bit-vectors is benign.
42028         ** It merely means that we might do some extra work to journal a 
42029         ** page that does not need to be journaled.  Nevertheless, be sure 
42030         ** to test the case where a malloc error occurs while trying to set 
42031         ** a bit in a bit vector.
42032         */
42033         sqlite3BeginBenignMalloc();
42034         if( pgno<=pPager->dbOrigSize ){
42035           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42036           testcase( rc==SQLITE_NOMEM );
42037         }
42038         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42039         testcase( rc==SQLITE_NOMEM );
42040         sqlite3EndBenignMalloc();
42041       }
42042       memset(pPg->pData, 0, pPager->pageSize);
42043       IOTRACE(("ZERO %p %d\n", pPager, pgno));
42044     }else{
42045       assert( pPg->pPager==pPager );
42046       pPager->aStat[PAGER_STAT_MISS]++;
42047       rc = readDbPage(pPg);
42048       if( rc!=SQLITE_OK ){
42049         goto pager_acquire_err;
42050       }
42051     }
42052     pager_set_pagehash(pPg);
42053   }
42054
42055   return SQLITE_OK;
42056
42057 pager_acquire_err:
42058   assert( rc!=SQLITE_OK );
42059   if( pPg ){
42060     sqlite3PcacheDrop(pPg);
42061   }
42062   pagerUnlockIfUnused(pPager);
42063
42064   *ppPage = 0;
42065   return rc;
42066 }
42067
42068 /*
42069 ** Acquire a page if it is already in the in-memory cache.  Do
42070 ** not read the page from disk.  Return a pointer to the page,
42071 ** or 0 if the page is not in cache. 
42072 **
42073 ** See also sqlite3PagerGet().  The difference between this routine
42074 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42075 ** in the page if the page is not already in cache.  This routine
42076 ** returns NULL if the page is not in cache or if a disk I/O error 
42077 ** has ever happened.
42078 */
42079 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42080   PgHdr *pPg = 0;
42081   assert( pPager!=0 );
42082   assert( pgno!=0 );
42083   assert( pPager->pPCache!=0 );
42084   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42085   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42086   return pPg;
42087 }
42088
42089 /*
42090 ** Release a page reference.
42091 **
42092 ** If the number of references to the page drop to zero, then the
42093 ** page is added to the LRU list.  When all references to all pages
42094 ** are released, a rollback occurs and the lock on the database is
42095 ** removed.
42096 */
42097 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42098   if( pPg ){
42099     Pager *pPager = pPg->pPager;
42100     sqlite3PcacheRelease(pPg);
42101     pagerUnlockIfUnused(pPager);
42102   }
42103 }
42104
42105 /*
42106 ** This function is called at the start of every write transaction.
42107 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
42108 ** file when this routine is called.
42109 **
42110 ** Open the journal file for pager pPager and write a journal header
42111 ** to the start of it. If there are active savepoints, open the sub-journal
42112 ** as well. This function is only used when the journal file is being 
42113 ** opened to write a rollback log for a transaction. It is not used 
42114 ** when opening a hot journal file to roll it back.
42115 **
42116 ** If the journal file is already open (as it may be in exclusive mode),
42117 ** then this function just writes a journal header to the start of the
42118 ** already open file. 
42119 **
42120 ** Whether or not the journal file is opened by this function, the
42121 ** Pager.pInJournal bitvec structure is allocated.
42122 **
42123 ** Return SQLITE_OK if everything is successful. Otherwise, return 
42124 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
42125 ** an IO error code if opening or writing the journal file fails.
42126 */
42127 static int pager_open_journal(Pager *pPager){
42128   int rc = SQLITE_OK;                        /* Return code */
42129   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
42130
42131   assert( pPager->eState==PAGER_WRITER_LOCKED );
42132   assert( assert_pager_state(pPager) );
42133   assert( pPager->pInJournal==0 );
42134   
42135   /* If already in the error state, this function is a no-op.  But on
42136   ** the other hand, this routine is never called if we are already in
42137   ** an error state. */
42138   if( NEVER(pPager->errCode) ) return pPager->errCode;
42139
42140   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42141     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42142     if( pPager->pInJournal==0 ){
42143       return SQLITE_NOMEM;
42144     }
42145   
42146     /* Open the journal file if it is not already open. */
42147     if( !isOpen(pPager->jfd) ){
42148       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42149         sqlite3MemJournalOpen(pPager->jfd);
42150       }else{
42151         const int flags =                   /* VFS flags to open journal file */
42152           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42153           (pPager->tempFile ? 
42154             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42155             (SQLITE_OPEN_MAIN_JOURNAL)
42156           );
42157   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42158         rc = sqlite3JournalOpen(
42159             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42160         );
42161   #else
42162         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42163   #endif
42164       }
42165       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42166     }
42167   
42168   
42169     /* Write the first journal header to the journal file and open 
42170     ** the sub-journal if necessary.
42171     */
42172     if( rc==SQLITE_OK ){
42173       /* TODO: Check if all of these are really required. */
42174       pPager->nRec = 0;
42175       pPager->journalOff = 0;
42176       pPager->setMaster = 0;
42177       pPager->journalHdr = 0;
42178       rc = writeJournalHdr(pPager);
42179     }
42180   }
42181
42182   if( rc!=SQLITE_OK ){
42183     sqlite3BitvecDestroy(pPager->pInJournal);
42184     pPager->pInJournal = 0;
42185   }else{
42186     assert( pPager->eState==PAGER_WRITER_LOCKED );
42187     pPager->eState = PAGER_WRITER_CACHEMOD;
42188   }
42189
42190   return rc;
42191 }
42192
42193 /*
42194 ** Begin a write-transaction on the specified pager object. If a 
42195 ** write-transaction has already been opened, this function is a no-op.
42196 **
42197 ** If the exFlag argument is false, then acquire at least a RESERVED
42198 ** lock on the database file. If exFlag is true, then acquire at least
42199 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
42200 ** functions need be called.
42201 **
42202 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42203 ** within this transaction will be opened as an in-memory file. This
42204 ** has no effect if the sub-journal is already opened (as it may be when
42205 ** running in exclusive mode) or if the transaction does not require a
42206 ** sub-journal. If the subjInMemory argument is zero, then any required
42207 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
42208 ** or using a temporary file otherwise.
42209 */
42210 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42211   int rc = SQLITE_OK;
42212
42213   if( pPager->errCode ) return pPager->errCode;
42214   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42215   pPager->subjInMemory = (u8)subjInMemory;
42216
42217   if( ALWAYS(pPager->eState==PAGER_READER) ){
42218     assert( pPager->pInJournal==0 );
42219
42220     if( pagerUseWal(pPager) ){
42221       /* If the pager is configured to use locking_mode=exclusive, and an
42222       ** exclusive lock on the database is not already held, obtain it now.
42223       */
42224       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42225         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42226         if( rc!=SQLITE_OK ){
42227           return rc;
42228         }
42229         sqlite3WalExclusiveMode(pPager->pWal, 1);
42230       }
42231
42232       /* Grab the write lock on the log file. If successful, upgrade to
42233       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42234       ** The busy-handler is not invoked if another connection already
42235       ** holds the write-lock. If possible, the upper layer will call it.
42236       */
42237       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42238     }else{
42239       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42240       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42241       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42242       ** lock, but not when obtaining the RESERVED lock.
42243       */
42244       rc = pagerLockDb(pPager, RESERVED_LOCK);
42245       if( rc==SQLITE_OK && exFlag ){
42246         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42247       }
42248     }
42249
42250     if( rc==SQLITE_OK ){
42251       /* Change to WRITER_LOCKED state.
42252       **
42253       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42254       ** when it has an open transaction, but never to DBMOD or FINISHED.
42255       ** This is because in those states the code to roll back savepoint 
42256       ** transactions may copy data from the sub-journal into the database 
42257       ** file as well as into the page cache. Which would be incorrect in 
42258       ** WAL mode.
42259       */
42260       pPager->eState = PAGER_WRITER_LOCKED;
42261       pPager->dbHintSize = pPager->dbSize;
42262       pPager->dbFileSize = pPager->dbSize;
42263       pPager->dbOrigSize = pPager->dbSize;
42264       pPager->journalOff = 0;
42265     }
42266
42267     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42268     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42269     assert( assert_pager_state(pPager) );
42270   }
42271
42272   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42273   return rc;
42274 }
42275
42276 /*
42277 ** Mark a single data page as writeable. The page is written into the 
42278 ** main journal or sub-journal as required. If the page is written into
42279 ** one of the journals, the corresponding bit is set in the 
42280 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42281 ** of any open savepoints as appropriate.
42282 */
42283 static int pager_write(PgHdr *pPg){
42284   void *pData = pPg->pData;
42285   Pager *pPager = pPg->pPager;
42286   int rc = SQLITE_OK;
42287
42288   /* This routine is not called unless a write-transaction has already 
42289   ** been started. The journal file may or may not be open at this point.
42290   ** It is never called in the ERROR state.
42291   */
42292   assert( pPager->eState==PAGER_WRITER_LOCKED
42293        || pPager->eState==PAGER_WRITER_CACHEMOD
42294        || pPager->eState==PAGER_WRITER_DBMOD
42295   );
42296   assert( assert_pager_state(pPager) );
42297
42298   /* If an error has been previously detected, report the same error
42299   ** again. This should not happen, but the check provides robustness. */
42300   if( NEVER(pPager->errCode) )  return pPager->errCode;
42301
42302   /* Higher-level routines never call this function if database is not
42303   ** writable.  But check anyway, just for robustness. */
42304   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42305
42306   CHECK_PAGE(pPg);
42307
42308   /* The journal file needs to be opened. Higher level routines have already
42309   ** obtained the necessary locks to begin the write-transaction, but the
42310   ** rollback journal might not yet be open. Open it now if this is the case.
42311   **
42312   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
42313   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42314   ** an error might occur and the pager would end up in WRITER_LOCKED state
42315   ** with pages marked as dirty in the cache.
42316   */
42317   if( pPager->eState==PAGER_WRITER_LOCKED ){
42318     rc = pager_open_journal(pPager);
42319     if( rc!=SQLITE_OK ) return rc;
42320   }
42321   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42322   assert( assert_pager_state(pPager) );
42323
42324   /* Mark the page as dirty.  If the page has already been written
42325   ** to the journal then we can return right away.
42326   */
42327   sqlite3PcacheMakeDirty(pPg);
42328   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42329     assert( !pagerUseWal(pPager) );
42330   }else{
42331   
42332     /* The transaction journal now exists and we have a RESERVED or an
42333     ** EXCLUSIVE lock on the main database file.  Write the current page to
42334     ** the transaction journal if it is not there already.
42335     */
42336     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42337       assert( pagerUseWal(pPager)==0 );
42338       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42339         u32 cksum;
42340         char *pData2;
42341         i64 iOff = pPager->journalOff;
42342
42343         /* We should never write to the journal file the page that
42344         ** contains the database locks.  The following assert verifies
42345         ** that we do not. */
42346         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42347
42348         assert( pPager->journalHdr<=pPager->journalOff );
42349         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42350         cksum = pager_cksum(pPager, (u8*)pData2);
42351
42352         /* Even if an IO or diskfull error occurs while journalling the
42353         ** page in the block above, set the need-sync flag for the page.
42354         ** Otherwise, when the transaction is rolled back, the logic in
42355         ** playback_one_page() will think that the page needs to be restored
42356         ** in the database file. And if an IO error occurs while doing so,
42357         ** then corruption may follow.
42358         */
42359         pPg->flags |= PGHDR_NEED_SYNC;
42360
42361         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42362         if( rc!=SQLITE_OK ) return rc;
42363         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42364         if( rc!=SQLITE_OK ) return rc;
42365         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42366         if( rc!=SQLITE_OK ) return rc;
42367
42368         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
42369                  pPager->journalOff, pPager->pageSize));
42370         PAGER_INCR(sqlite3_pager_writej_count);
42371         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42372              PAGERID(pPager), pPg->pgno, 
42373              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42374
42375         pPager->journalOff += 8 + pPager->pageSize;
42376         pPager->nRec++;
42377         assert( pPager->pInJournal!=0 );
42378         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42379         testcase( rc==SQLITE_NOMEM );
42380         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42381         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42382         if( rc!=SQLITE_OK ){
42383           assert( rc==SQLITE_NOMEM );
42384           return rc;
42385         }
42386       }else{
42387         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42388           pPg->flags |= PGHDR_NEED_SYNC;
42389         }
42390         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42391                 PAGERID(pPager), pPg->pgno,
42392                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42393       }
42394     }
42395   
42396     /* If the statement journal is open and the page is not in it,
42397     ** then write the current page to the statement journal.  Note that
42398     ** the statement journal format differs from the standard journal format
42399     ** in that it omits the checksums and the header.
42400     */
42401     if( subjRequiresPage(pPg) ){
42402       rc = subjournalPage(pPg);
42403     }
42404   }
42405
42406   /* Update the database size and return.
42407   */
42408   if( pPager->dbSize<pPg->pgno ){
42409     pPager->dbSize = pPg->pgno;
42410   }
42411   return rc;
42412 }
42413
42414 /*
42415 ** Mark a data page as writeable. This routine must be called before 
42416 ** making changes to a page. The caller must check the return value 
42417 ** of this function and be careful not to change any page data unless 
42418 ** this routine returns SQLITE_OK.
42419 **
42420 ** The difference between this function and pager_write() is that this
42421 ** function also deals with the special case where 2 or more pages
42422 ** fit on a single disk sector. In this case all co-resident pages
42423 ** must have been written to the journal file before returning.
42424 **
42425 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42426 ** as appropriate. Otherwise, SQLITE_OK.
42427 */
42428 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42429   int rc = SQLITE_OK;
42430
42431   PgHdr *pPg = pDbPage;
42432   Pager *pPager = pPg->pPager;
42433   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42434
42435   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42436   assert( pPager->eState!=PAGER_ERROR );
42437   assert( assert_pager_state(pPager) );
42438
42439   if( nPagePerSector>1 ){
42440     Pgno nPageCount;          /* Total number of pages in database file */
42441     Pgno pg1;                 /* First page of the sector pPg is located on. */
42442     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42443     int ii;                   /* Loop counter */
42444     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42445
42446     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42447     ** a journal header to be written between the pages journaled by
42448     ** this function.
42449     */
42450     assert( !MEMDB );
42451     assert( pPager->doNotSyncSpill==0 );
42452     pPager->doNotSyncSpill++;
42453
42454     /* This trick assumes that both the page-size and sector-size are
42455     ** an integer power of 2. It sets variable pg1 to the identifier
42456     ** of the first page of the sector pPg is located on.
42457     */
42458     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42459
42460     nPageCount = pPager->dbSize;
42461     if( pPg->pgno>nPageCount ){
42462       nPage = (pPg->pgno - pg1)+1;
42463     }else if( (pg1+nPagePerSector-1)>nPageCount ){
42464       nPage = nPageCount+1-pg1;
42465     }else{
42466       nPage = nPagePerSector;
42467     }
42468     assert(nPage>0);
42469     assert(pg1<=pPg->pgno);
42470     assert((pg1+nPage)>pPg->pgno);
42471
42472     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42473       Pgno pg = pg1+ii;
42474       PgHdr *pPage;
42475       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42476         if( pg!=PAGER_MJ_PGNO(pPager) ){
42477           rc = sqlite3PagerGet(pPager, pg, &pPage);
42478           if( rc==SQLITE_OK ){
42479             rc = pager_write(pPage);
42480             if( pPage->flags&PGHDR_NEED_SYNC ){
42481               needSync = 1;
42482             }
42483             sqlite3PagerUnref(pPage);
42484           }
42485         }
42486       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42487         if( pPage->flags&PGHDR_NEED_SYNC ){
42488           needSync = 1;
42489         }
42490         sqlite3PagerUnref(pPage);
42491       }
42492     }
42493
42494     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
42495     ** starting at pg1, then it needs to be set for all of them. Because
42496     ** writing to any of these nPage pages may damage the others, the
42497     ** journal file must contain sync()ed copies of all of them
42498     ** before any of them can be written out to the database file.
42499     */
42500     if( rc==SQLITE_OK && needSync ){
42501       assert( !MEMDB );
42502       for(ii=0; ii<nPage; ii++){
42503         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42504         if( pPage ){
42505           pPage->flags |= PGHDR_NEED_SYNC;
42506           sqlite3PagerUnref(pPage);
42507         }
42508       }
42509     }
42510
42511     assert( pPager->doNotSyncSpill==1 );
42512     pPager->doNotSyncSpill--;
42513   }else{
42514     rc = pager_write(pDbPage);
42515   }
42516   return rc;
42517 }
42518
42519 /*
42520 ** Return TRUE if the page given in the argument was previously passed
42521 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
42522 ** to change the content of the page.
42523 */
42524 #ifndef NDEBUG
42525 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42526   return pPg->flags&PGHDR_DIRTY;
42527 }
42528 #endif
42529
42530 /*
42531 ** A call to this routine tells the pager that it is not necessary to
42532 ** write the information on page pPg back to the disk, even though
42533 ** that page might be marked as dirty.  This happens, for example, when
42534 ** the page has been added as a leaf of the freelist and so its
42535 ** content no longer matters.
42536 **
42537 ** The overlying software layer calls this routine when all of the data
42538 ** on the given page is unused. The pager marks the page as clean so
42539 ** that it does not get written to disk.
42540 **
42541 ** Tests show that this optimization can quadruple the speed of large 
42542 ** DELETE operations.
42543 */
42544 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42545   Pager *pPager = pPg->pPager;
42546   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42547     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42548     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42549     pPg->flags |= PGHDR_DONT_WRITE;
42550     pager_set_pagehash(pPg);
42551   }
42552 }
42553
42554 /*
42555 ** This routine is called to increment the value of the database file 
42556 ** change-counter, stored as a 4-byte big-endian integer starting at 
42557 ** byte offset 24 of the pager file.  The secondary change counter at
42558 ** 92 is also updated, as is the SQLite version number at offset 96.
42559 **
42560 ** But this only happens if the pPager->changeCountDone flag is false.
42561 ** To avoid excess churning of page 1, the update only happens once.
42562 ** See also the pager_write_changecounter() routine that does an 
42563 ** unconditional update of the change counters.
42564 **
42565 ** If the isDirectMode flag is zero, then this is done by calling 
42566 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42567 ** page data. In this case the file will be updated when the current
42568 ** transaction is committed.
42569 **
42570 ** The isDirectMode flag may only be non-zero if the library was compiled
42571 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42572 ** if isDirect is non-zero, then the database file is updated directly
42573 ** by writing an updated version of page 1 using a call to the 
42574 ** sqlite3OsWrite() function.
42575 */
42576 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42577   int rc = SQLITE_OK;
42578
42579   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42580        || pPager->eState==PAGER_WRITER_DBMOD
42581   );
42582   assert( assert_pager_state(pPager) );
42583
42584   /* Declare and initialize constant integer 'isDirect'. If the
42585   ** atomic-write optimization is enabled in this build, then isDirect
42586   ** is initialized to the value passed as the isDirectMode parameter
42587   ** to this function. Otherwise, it is always set to zero.
42588   **
42589   ** The idea is that if the atomic-write optimization is not
42590   ** enabled at compile time, the compiler can omit the tests of
42591   ** 'isDirect' below, as well as the block enclosed in the
42592   ** "if( isDirect )" condition.
42593   */
42594 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42595 # define DIRECT_MODE 0
42596   assert( isDirectMode==0 );
42597   UNUSED_PARAMETER(isDirectMode);
42598 #else
42599 # define DIRECT_MODE isDirectMode
42600 #endif
42601
42602   if( !pPager->changeCountDone && pPager->dbSize>0 ){
42603     PgHdr *pPgHdr;                /* Reference to page 1 */
42604
42605     assert( !pPager->tempFile && isOpen(pPager->fd) );
42606
42607     /* Open page 1 of the file for writing. */
42608     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42609     assert( pPgHdr==0 || rc==SQLITE_OK );
42610
42611     /* If page one was fetched successfully, and this function is not
42612     ** operating in direct-mode, make page 1 writable.  When not in 
42613     ** direct mode, page 1 is always held in cache and hence the PagerGet()
42614     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42615     */
42616     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42617       rc = sqlite3PagerWrite(pPgHdr);
42618     }
42619
42620     if( rc==SQLITE_OK ){
42621       /* Actually do the update of the change counter */
42622       pager_write_changecounter(pPgHdr);
42623
42624       /* If running in direct mode, write the contents of page 1 to the file. */
42625       if( DIRECT_MODE ){
42626         const void *zBuf;
42627         assert( pPager->dbFileSize>0 );
42628         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42629         if( rc==SQLITE_OK ){
42630           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42631           pPager->aStat[PAGER_STAT_WRITE]++;
42632         }
42633         if( rc==SQLITE_OK ){
42634           pPager->changeCountDone = 1;
42635         }
42636       }else{
42637         pPager->changeCountDone = 1;
42638       }
42639     }
42640
42641     /* Release the page reference. */
42642     sqlite3PagerUnref(pPgHdr);
42643   }
42644   return rc;
42645 }
42646
42647 /*
42648 ** Sync the database file to disk. This is a no-op for in-memory databases
42649 ** or pages with the Pager.noSync flag set.
42650 **
42651 ** If successful, or if called on a pager for which it is a no-op, this
42652 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42653 */
42654 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42655   int rc = SQLITE_OK;
42656   if( !pPager->noSync ){
42657     assert( !MEMDB );
42658     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42659   }else if( isOpen(pPager->fd) ){
42660     assert( !MEMDB );
42661     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
42662     if( rc==SQLITE_NOTFOUND ){
42663       rc = SQLITE_OK;
42664     }
42665   }
42666   return rc;
42667 }
42668
42669 /*
42670 ** This function may only be called while a write-transaction is active in
42671 ** rollback. If the connection is in WAL mode, this call is a no-op. 
42672 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
42673 ** the database file, an attempt is made to obtain one.
42674 **
42675 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42676 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42677 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
42678 ** returned.
42679 */
42680 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42681   int rc = SQLITE_OK;
42682   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
42683        || pPager->eState==PAGER_WRITER_DBMOD 
42684        || pPager->eState==PAGER_WRITER_LOCKED 
42685   );
42686   assert( assert_pager_state(pPager) );
42687   if( 0==pagerUseWal(pPager) ){
42688     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42689   }
42690   return rc;
42691 }
42692
42693 /*
42694 ** Sync the database file for the pager pPager. zMaster points to the name
42695 ** of a master journal file that should be written into the individual
42696 ** journal file. zMaster may be NULL, which is interpreted as no master
42697 ** journal (a single database transaction).
42698 **
42699 ** This routine ensures that:
42700 **
42701 **   * The database file change-counter is updated,
42702 **   * the journal is synced (unless the atomic-write optimization is used),
42703 **   * all dirty pages are written to the database file, 
42704 **   * the database file is truncated (if required), and
42705 **   * the database file synced. 
42706 **
42707 ** The only thing that remains to commit the transaction is to finalize 
42708 ** (delete, truncate or zero the first part of) the journal file (or 
42709 ** delete the master journal file if specified).
42710 **
42711 ** Note that if zMaster==NULL, this does not overwrite a previous value
42712 ** passed to an sqlite3PagerCommitPhaseOne() call.
42713 **
42714 ** If the final parameter - noSync - is true, then the database file itself
42715 ** is not synced. The caller must call sqlite3PagerSync() directly to
42716 ** sync the database file before calling CommitPhaseTwo() to delete the
42717 ** journal file in this case.
42718 */
42719 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42720   Pager *pPager,                  /* Pager object */
42721   const char *zMaster,            /* If not NULL, the master journal name */
42722   int noSync                      /* True to omit the xSync on the db file */
42723 ){
42724   int rc = SQLITE_OK;             /* Return code */
42725
42726   assert( pPager->eState==PAGER_WRITER_LOCKED
42727        || pPager->eState==PAGER_WRITER_CACHEMOD
42728        || pPager->eState==PAGER_WRITER_DBMOD
42729        || pPager->eState==PAGER_ERROR
42730   );
42731   assert( assert_pager_state(pPager) );
42732
42733   /* If a prior error occurred, report that error again. */
42734   if( NEVER(pPager->errCode) ) return pPager->errCode;
42735
42736   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
42737       pPager->zFilename, zMaster, pPager->dbSize));
42738
42739   /* If no database changes have been made, return early. */
42740   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42741
42742   if( MEMDB ){
42743     /* If this is an in-memory db, or no pages have been written to, or this
42744     ** function has already been called, it is mostly a no-op.  However, any
42745     ** backup in progress needs to be restarted.
42746     */
42747     sqlite3BackupRestart(pPager->pBackup);
42748   }else{
42749     if( pagerUseWal(pPager) ){
42750       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42751       PgHdr *pPageOne = 0;
42752       if( pList==0 ){
42753         /* Must have at least one page for the WAL commit flag.
42754         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42755         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42756         pList = pPageOne;
42757         pList->pDirty = 0;
42758       }
42759       assert( rc==SQLITE_OK );
42760       if( ALWAYS(pList) ){
42761         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
42762       }
42763       sqlite3PagerUnref(pPageOne);
42764       if( rc==SQLITE_OK ){
42765         sqlite3PcacheCleanAll(pPager->pPCache);
42766       }
42767     }else{
42768       /* The following block updates the change-counter. Exactly how it
42769       ** does this depends on whether or not the atomic-update optimization
42770       ** was enabled at compile time, and if this transaction meets the 
42771       ** runtime criteria to use the operation: 
42772       **
42773       **    * The file-system supports the atomic-write property for
42774       **      blocks of size page-size, and 
42775       **    * This commit is not part of a multi-file transaction, and
42776       **    * Exactly one page has been modified and store in the journal file.
42777       **
42778       ** If the optimization was not enabled at compile time, then the
42779       ** pager_incr_changecounter() function is called to update the change
42780       ** counter in 'indirect-mode'. If the optimization is compiled in but
42781       ** is not applicable to this transaction, call sqlite3JournalCreate()
42782       ** to make sure the journal file has actually been created, then call
42783       ** pager_incr_changecounter() to update the change-counter in indirect
42784       ** mode. 
42785       **
42786       ** Otherwise, if the optimization is both enabled and applicable,
42787       ** then call pager_incr_changecounter() to update the change-counter
42788       ** in 'direct' mode. In this case the journal file will never be
42789       ** created for this transaction.
42790       */
42791   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42792       PgHdr *pPg;
42793       assert( isOpen(pPager->jfd) 
42794            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
42795            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
42796       );
42797       if( !zMaster && isOpen(pPager->jfd) 
42798        && pPager->journalOff==jrnlBufferSize(pPager) 
42799        && pPager->dbSize>=pPager->dbOrigSize
42800        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42801       ){
42802         /* Update the db file change counter via the direct-write method. The 
42803         ** following call will modify the in-memory representation of page 1 
42804         ** to include the updated change counter and then write page 1 
42805         ** directly to the database file. Because of the atomic-write 
42806         ** property of the host file-system, this is safe.
42807         */
42808         rc = pager_incr_changecounter(pPager, 1);
42809       }else{
42810         rc = sqlite3JournalCreate(pPager->jfd);
42811         if( rc==SQLITE_OK ){
42812           rc = pager_incr_changecounter(pPager, 0);
42813         }
42814       }
42815   #else
42816       rc = pager_incr_changecounter(pPager, 0);
42817   #endif
42818       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42819   
42820       /* If this transaction has made the database smaller, then all pages
42821       ** being discarded by the truncation must be written to the journal
42822       ** file. This can only happen in auto-vacuum mode.
42823       **
42824       ** Before reading the pages with page numbers larger than the 
42825       ** current value of Pager.dbSize, set dbSize back to the value
42826       ** that it took at the start of the transaction. Otherwise, the
42827       ** calls to sqlite3PagerGet() return zeroed pages instead of 
42828       ** reading data from the database file.
42829       */
42830   #ifndef SQLITE_OMIT_AUTOVACUUM
42831       if( pPager->dbSize<pPager->dbOrigSize 
42832        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42833       ){
42834         Pgno i;                                   /* Iterator variable */
42835         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42836         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
42837         pPager->dbSize = pPager->dbOrigSize;
42838         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42839           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42840             PgHdr *pPage;             /* Page to journal */
42841             rc = sqlite3PagerGet(pPager, i, &pPage);
42842             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42843             rc = sqlite3PagerWrite(pPage);
42844             sqlite3PagerUnref(pPage);
42845             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42846           }
42847         }
42848         pPager->dbSize = dbSize;
42849       } 
42850   #endif
42851   
42852       /* Write the master journal name into the journal file. If a master 
42853       ** journal file name has already been written to the journal file, 
42854       ** or if zMaster is NULL (no master journal), then this call is a no-op.
42855       */
42856       rc = writeMasterJournal(pPager, zMaster);
42857       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42858   
42859       /* Sync the journal file and write all dirty pages to the database.
42860       ** If the atomic-update optimization is being used, this sync will not 
42861       ** create the journal file or perform any real IO.
42862       **
42863       ** Because the change-counter page was just modified, unless the
42864       ** atomic-update optimization is used it is almost certain that the
42865       ** journal requires a sync here. However, in locking_mode=exclusive
42866       ** on a system under memory pressure it is just possible that this is 
42867       ** not the case. In this case it is likely enough that the redundant
42868       ** xSync() call will be changed to a no-op by the OS anyhow. 
42869       */
42870       rc = syncJournal(pPager, 0);
42871       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42872   
42873       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42874       if( rc!=SQLITE_OK ){
42875         assert( rc!=SQLITE_IOERR_BLOCKED );
42876         goto commit_phase_one_exit;
42877       }
42878       sqlite3PcacheCleanAll(pPager->pPCache);
42879   
42880       /* If the file on disk is not the same size as the database image,
42881       ** then use pager_truncate to grow or shrink the file here.
42882       */
42883       if( pPager->dbSize!=pPager->dbFileSize ){
42884         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42885         assert( pPager->eState==PAGER_WRITER_DBMOD );
42886         rc = pager_truncate(pPager, nNew);
42887         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42888       }
42889   
42890       /* Finally, sync the database file. */
42891       if( !noSync ){
42892         rc = sqlite3PagerSync(pPager);
42893       }
42894       IOTRACE(("DBSYNC %p\n", pPager))
42895     }
42896   }
42897
42898 commit_phase_one_exit:
42899   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42900     pPager->eState = PAGER_WRITER_FINISHED;
42901   }
42902   return rc;
42903 }
42904
42905
42906 /*
42907 ** When this function is called, the database file has been completely
42908 ** updated to reflect the changes made by the current transaction and
42909 ** synced to disk. The journal file still exists in the file-system 
42910 ** though, and if a failure occurs at this point it will eventually
42911 ** be used as a hot-journal and the current transaction rolled back.
42912 **
42913 ** This function finalizes the journal file, either by deleting, 
42914 ** truncating or partially zeroing it, so that it cannot be used 
42915 ** for hot-journal rollback. Once this is done the transaction is
42916 ** irrevocably committed.
42917 **
42918 ** If an error occurs, an IO error code is returned and the pager
42919 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42920 */
42921 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42922   int rc = SQLITE_OK;                  /* Return code */
42923
42924   /* This routine should not be called if a prior error has occurred.
42925   ** But if (due to a coding error elsewhere in the system) it does get
42926   ** called, just return the same error code without doing anything. */
42927   if( NEVER(pPager->errCode) ) return pPager->errCode;
42928
42929   assert( pPager->eState==PAGER_WRITER_LOCKED
42930        || pPager->eState==PAGER_WRITER_FINISHED
42931        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42932   );
42933   assert( assert_pager_state(pPager) );
42934
42935   /* An optimization. If the database was not actually modified during
42936   ** this transaction, the pager is running in exclusive-mode and is
42937   ** using persistent journals, then this function is a no-op.
42938   **
42939   ** The start of the journal file currently contains a single journal 
42940   ** header with the nRec field set to 0. If such a journal is used as
42941   ** a hot-journal during hot-journal rollback, 0 changes will be made
42942   ** to the database file. So there is no need to zero the journal 
42943   ** header. Since the pager is in exclusive mode, there is no need
42944   ** to drop any locks either.
42945   */
42946   if( pPager->eState==PAGER_WRITER_LOCKED 
42947    && pPager->exclusiveMode 
42948    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42949   ){
42950     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42951     pPager->eState = PAGER_READER;
42952     return SQLITE_OK;
42953   }
42954
42955   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42956   rc = pager_end_transaction(pPager, pPager->setMaster);
42957   return pager_error(pPager, rc);
42958 }
42959
42960 /*
42961 ** If a write transaction is open, then all changes made within the 
42962 ** transaction are reverted and the current write-transaction is closed.
42963 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42964 ** state if an error occurs.
42965 **
42966 ** If the pager is already in PAGER_ERROR state when this function is called,
42967 ** it returns Pager.errCode immediately. No work is performed in this case.
42968 **
42969 ** Otherwise, in rollback mode, this function performs two functions:
42970 **
42971 **   1) It rolls back the journal file, restoring all database file and 
42972 **      in-memory cache pages to the state they were in when the transaction
42973 **      was opened, and
42974 **
42975 **   2) It finalizes the journal file, so that it is not used for hot
42976 **      rollback at any point in the future.
42977 **
42978 ** Finalization of the journal file (task 2) is only performed if the 
42979 ** rollback is successful.
42980 **
42981 ** In WAL mode, all cache-entries containing data modified within the
42982 ** current transaction are either expelled from the cache or reverted to
42983 ** their pre-transaction state by re-reading data from the database or
42984 ** WAL files. The WAL transaction is then closed.
42985 */
42986 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42987   int rc = SQLITE_OK;                  /* Return code */
42988   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42989
42990   /* PagerRollback() is a no-op if called in READER or OPEN state. If
42991   ** the pager is already in the ERROR state, the rollback is not 
42992   ** attempted here. Instead, the error code is returned to the caller.
42993   */
42994   assert( assert_pager_state(pPager) );
42995   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42996   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42997
42998   if( pagerUseWal(pPager) ){
42999     int rc2;
43000     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43001     rc2 = pager_end_transaction(pPager, pPager->setMaster);
43002     if( rc==SQLITE_OK ) rc = rc2;
43003   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43004     int eState = pPager->eState;
43005     rc = pager_end_transaction(pPager, 0);
43006     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43007       /* This can happen using journal_mode=off. Move the pager to the error 
43008       ** state to indicate that the contents of the cache may not be trusted.
43009       ** Any active readers will get SQLITE_ABORT.
43010       */
43011       pPager->errCode = SQLITE_ABORT;
43012       pPager->eState = PAGER_ERROR;
43013       return rc;
43014     }
43015   }else{
43016     rc = pager_playback(pPager, 0);
43017   }
43018
43019   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43020   assert( rc==SQLITE_OK || rc==SQLITE_FULL
43021           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
43022
43023   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43024   ** cache. So call pager_error() on the way out to make any error persistent.
43025   */
43026   return pager_error(pPager, rc);
43027 }
43028
43029 /*
43030 ** Return TRUE if the database file is opened read-only.  Return FALSE
43031 ** if the database is (in theory) writable.
43032 */
43033 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43034   return pPager->readOnly;
43035 }
43036
43037 /*
43038 ** Return the number of references to the pager.
43039 */
43040 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43041   return sqlite3PcacheRefCount(pPager->pPCache);
43042 }
43043
43044 /*
43045 ** Return the approximate number of bytes of memory currently
43046 ** used by the pager and its associated cache.
43047 */
43048 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43049   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43050                                      + 5*sizeof(void*);
43051   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43052            + sqlite3MallocSize(pPager)
43053            + pPager->pageSize;
43054 }
43055
43056 /*
43057 ** Return the number of references to the specified page.
43058 */
43059 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43060   return sqlite3PcachePageRefcount(pPage);
43061 }
43062
43063 #ifdef SQLITE_TEST
43064 /*
43065 ** This routine is used for testing and analysis only.
43066 */
43067 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43068   static int a[11];
43069   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43070   a[1] = sqlite3PcachePagecount(pPager->pPCache);
43071   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43072   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43073   a[4] = pPager->eState;
43074   a[5] = pPager->errCode;
43075   a[6] = pPager->aStat[PAGER_STAT_HIT];
43076   a[7] = pPager->aStat[PAGER_STAT_MISS];
43077   a[8] = 0;  /* Used to be pPager->nOvfl */
43078   a[9] = pPager->nRead;
43079   a[10] = pPager->aStat[PAGER_STAT_WRITE];
43080   return a;
43081 }
43082 #endif
43083
43084 /*
43085 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
43086 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
43087 ** current cache hit or miss count, according to the value of eStat. If the 
43088 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
43089 ** returning.
43090 */
43091 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
43092
43093   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
43094        || eStat==SQLITE_DBSTATUS_CACHE_MISS
43095        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
43096   );
43097
43098   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
43099   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
43100   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
43101
43102   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
43103   if( reset ){
43104     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
43105   }
43106 }
43107
43108 /*
43109 ** Return true if this is an in-memory pager.
43110 */
43111 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43112   return MEMDB;
43113 }
43114
43115 /*
43116 ** Check that there are at least nSavepoint savepoints open. If there are
43117 ** currently less than nSavepoints open, then open one or more savepoints
43118 ** to make up the difference. If the number of savepoints is already
43119 ** equal to nSavepoint, then this function is a no-op.
43120 **
43121 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
43122 ** occurs while opening the sub-journal file, then an IO error code is
43123 ** returned. Otherwise, SQLITE_OK.
43124 */
43125 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43126   int rc = SQLITE_OK;                       /* Return code */
43127   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
43128
43129   assert( pPager->eState>=PAGER_WRITER_LOCKED );
43130   assert( assert_pager_state(pPager) );
43131
43132   if( nSavepoint>nCurrent && pPager->useJournal ){
43133     int ii;                                 /* Iterator variable */
43134     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
43135
43136     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43137     ** if the allocation fails. Otherwise, zero the new portion in case a 
43138     ** malloc failure occurs while populating it in the for(...) loop below.
43139     */
43140     aNew = (PagerSavepoint *)sqlite3Realloc(
43141         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43142     );
43143     if( !aNew ){
43144       return SQLITE_NOMEM;
43145     }
43146     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43147     pPager->aSavepoint = aNew;
43148
43149     /* Populate the PagerSavepoint structures just allocated. */
43150     for(ii=nCurrent; ii<nSavepoint; ii++){
43151       aNew[ii].nOrig = pPager->dbSize;
43152       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43153         aNew[ii].iOffset = pPager->journalOff;
43154       }else{
43155         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43156       }
43157       aNew[ii].iSubRec = pPager->nSubRec;
43158       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43159       if( !aNew[ii].pInSavepoint ){
43160         return SQLITE_NOMEM;
43161       }
43162       if( pagerUseWal(pPager) ){
43163         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43164       }
43165       pPager->nSavepoint = ii+1;
43166     }
43167     assert( pPager->nSavepoint==nSavepoint );
43168     assertTruncateConstraint(pPager);
43169   }
43170
43171   return rc;
43172 }
43173
43174 /*
43175 ** This function is called to rollback or release (commit) a savepoint.
43176 ** The savepoint to release or rollback need not be the most recently 
43177 ** created savepoint.
43178 **
43179 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43180 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43181 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43182 ** that have occurred since the specified savepoint was created.
43183 **
43184 ** The savepoint to rollback or release is identified by parameter 
43185 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43186 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43187 ** on the most recently created savepoint. If iSavepoint is greater than
43188 ** (Pager.nSavepoint-1), then this function is a no-op.
43189 **
43190 ** If a negative value is passed to this function, then the current
43191 ** transaction is rolled back. This is different to calling 
43192 ** sqlite3PagerRollback() because this function does not terminate
43193 ** the transaction or unlock the database, it just restores the 
43194 ** contents of the database to its original state. 
43195 **
43196 ** In any case, all savepoints with an index greater than iSavepoint 
43197 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43198 ** then savepoint iSavepoint is also destroyed.
43199 **
43200 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43201 ** or an IO error code if an IO error occurs while rolling back a 
43202 ** savepoint. If no errors occur, SQLITE_OK is returned.
43203 */ 
43204 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43205   int rc = pPager->errCode;       /* Return code */
43206
43207   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43208   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43209
43210   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43211     int ii;            /* Iterator variable */
43212     int nNew;          /* Number of remaining savepoints after this op. */
43213
43214     /* Figure out how many savepoints will still be active after this
43215     ** operation. Store this value in nNew. Then free resources associated 
43216     ** with any savepoints that are destroyed by this operation.
43217     */
43218     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43219     for(ii=nNew; ii<pPager->nSavepoint; ii++){
43220       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43221     }
43222     pPager->nSavepoint = nNew;
43223
43224     /* If this is a release of the outermost savepoint, truncate 
43225     ** the sub-journal to zero bytes in size. */
43226     if( op==SAVEPOINT_RELEASE ){
43227       if( nNew==0 && isOpen(pPager->sjfd) ){
43228         /* Only truncate if it is an in-memory sub-journal. */
43229         if( sqlite3IsMemJournal(pPager->sjfd) ){
43230           rc = sqlite3OsTruncate(pPager->sjfd, 0);
43231           assert( rc==SQLITE_OK );
43232         }
43233         pPager->nSubRec = 0;
43234       }
43235     }
43236     /* Else this is a rollback operation, playback the specified savepoint.
43237     ** If this is a temp-file, it is possible that the journal file has
43238     ** not yet been opened. In this case there have been no changes to
43239     ** the database file, so the playback operation can be skipped.
43240     */
43241     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43242       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43243       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43244       assert(rc!=SQLITE_DONE);
43245     }
43246   }
43247
43248   return rc;
43249 }
43250
43251 /*
43252 ** Return the full pathname of the database file.
43253 **
43254 ** Except, if the pager is in-memory only, then return an empty string if
43255 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
43256 ** used to report the filename to the user, for compatibility with legacy
43257 ** behavior.  But when the Btree needs to know the filename for matching to
43258 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
43259 ** participate in shared-cache.
43260 */
43261 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
43262   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
43263 }
43264
43265 /*
43266 ** Return the VFS structure for the pager.
43267 */
43268 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43269   return pPager->pVfs;
43270 }
43271
43272 /*
43273 ** Return the file handle for the database file associated
43274 ** with the pager.  This might return NULL if the file has
43275 ** not yet been opened.
43276 */
43277 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43278   return pPager->fd;
43279 }
43280
43281 /*
43282 ** Return the full pathname of the journal file.
43283 */
43284 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43285   return pPager->zJournal;
43286 }
43287
43288 /*
43289 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43290 ** if fsync()s are executed normally.
43291 */
43292 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43293   return pPager->noSync;
43294 }
43295
43296 #ifdef SQLITE_HAS_CODEC
43297 /*
43298 ** Set or retrieve the codec for this pager
43299 */
43300 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43301   Pager *pPager,
43302   void *(*xCodec)(void*,void*,Pgno,int),
43303   void (*xCodecSizeChng)(void*,int,int),
43304   void (*xCodecFree)(void*),
43305   void *pCodec
43306 ){
43307   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43308   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43309   pPager->xCodecSizeChng = xCodecSizeChng;
43310   pPager->xCodecFree = xCodecFree;
43311   pPager->pCodec = pCodec;
43312   pagerReportSize(pPager);
43313 }
43314 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43315   return pPager->pCodec;
43316 }
43317 #endif
43318
43319 #ifndef SQLITE_OMIT_AUTOVACUUM
43320 /*
43321 ** Move the page pPg to location pgno in the file.
43322 **
43323 ** There must be no references to the page previously located at
43324 ** pgno (which we call pPgOld) though that page is allowed to be
43325 ** in cache.  If the page previously located at pgno is not already
43326 ** in the rollback journal, it is not put there by by this routine.
43327 **
43328 ** References to the page pPg remain valid. Updating any
43329 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43330 ** allocated along with the page) is the responsibility of the caller.
43331 **
43332 ** A transaction must be active when this routine is called. It used to be
43333 ** required that a statement transaction was not active, but this restriction
43334 ** has been removed (CREATE INDEX needs to move a page when a statement
43335 ** transaction is active).
43336 **
43337 ** If the fourth argument, isCommit, is non-zero, then this page is being
43338 ** moved as part of a database reorganization just before the transaction 
43339 ** is being committed. In this case, it is guaranteed that the database page 
43340 ** pPg refers to will not be written to again within this transaction.
43341 **
43342 ** This function may return SQLITE_NOMEM or an IO error code if an error
43343 ** occurs. Otherwise, it returns SQLITE_OK.
43344 */
43345 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43346   PgHdr *pPgOld;               /* The page being overwritten. */
43347   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43348   int rc;                      /* Return code */
43349   Pgno origPgno;               /* The original page number */
43350
43351   assert( pPg->nRef>0 );
43352   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43353        || pPager->eState==PAGER_WRITER_DBMOD
43354   );
43355   assert( assert_pager_state(pPager) );
43356
43357   /* In order to be able to rollback, an in-memory database must journal
43358   ** the page we are moving from.
43359   */
43360   if( MEMDB ){
43361     rc = sqlite3PagerWrite(pPg);
43362     if( rc ) return rc;
43363   }
43364
43365   /* If the page being moved is dirty and has not been saved by the latest
43366   ** savepoint, then save the current contents of the page into the 
43367   ** sub-journal now. This is required to handle the following scenario:
43368   **
43369   **   BEGIN;
43370   **     <journal page X, then modify it in memory>
43371   **     SAVEPOINT one;
43372   **       <Move page X to location Y>
43373   **     ROLLBACK TO one;
43374   **
43375   ** If page X were not written to the sub-journal here, it would not
43376   ** be possible to restore its contents when the "ROLLBACK TO one"
43377   ** statement were is processed.
43378   **
43379   ** subjournalPage() may need to allocate space to store pPg->pgno into
43380   ** one or more savepoint bitvecs. This is the reason this function
43381   ** may return SQLITE_NOMEM.
43382   */
43383   if( pPg->flags&PGHDR_DIRTY
43384    && subjRequiresPage(pPg)
43385    && SQLITE_OK!=(rc = subjournalPage(pPg))
43386   ){
43387     return rc;
43388   }
43389
43390   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
43391       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43392   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43393
43394   /* If the journal needs to be sync()ed before page pPg->pgno can
43395   ** be written to, store pPg->pgno in local variable needSyncPgno.
43396   **
43397   ** If the isCommit flag is set, there is no need to remember that
43398   ** the journal needs to be sync()ed before database page pPg->pgno 
43399   ** can be written to. The caller has already promised not to write to it.
43400   */
43401   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43402     needSyncPgno = pPg->pgno;
43403     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43404     assert( pPg->flags&PGHDR_DIRTY );
43405   }
43406
43407   /* If the cache contains a page with page-number pgno, remove it
43408   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
43409   ** page pgno before the 'move' operation, it needs to be retained 
43410   ** for the page moved there.
43411   */
43412   pPg->flags &= ~PGHDR_NEED_SYNC;
43413   pPgOld = pager_lookup(pPager, pgno);
43414   assert( !pPgOld || pPgOld->nRef==1 );
43415   if( pPgOld ){
43416     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43417     if( MEMDB ){
43418       /* Do not discard pages from an in-memory database since we might
43419       ** need to rollback later.  Just move the page out of the way. */
43420       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43421     }else{
43422       sqlite3PcacheDrop(pPgOld);
43423     }
43424   }
43425
43426   origPgno = pPg->pgno;
43427   sqlite3PcacheMove(pPg, pgno);
43428   sqlite3PcacheMakeDirty(pPg);
43429
43430   /* For an in-memory database, make sure the original page continues
43431   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43432   ** as the original page since it has already been allocated.
43433   */
43434   if( MEMDB ){
43435     assert( pPgOld );
43436     sqlite3PcacheMove(pPgOld, origPgno);
43437     sqlite3PagerUnref(pPgOld);
43438   }
43439
43440   if( needSyncPgno ){
43441     /* If needSyncPgno is non-zero, then the journal file needs to be 
43442     ** sync()ed before any data is written to database file page needSyncPgno.
43443     ** Currently, no such page exists in the page-cache and the 
43444     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43445     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43446     ** flag.
43447     **
43448     ** If the attempt to load the page into the page-cache fails, (due
43449     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43450     ** array. Otherwise, if the page is loaded and written again in
43451     ** this transaction, it may be written to the database file before
43452     ** it is synced into the journal file. This way, it may end up in
43453     ** the journal file twice, but that is not a problem.
43454     */
43455     PgHdr *pPgHdr;
43456     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43457     if( rc!=SQLITE_OK ){
43458       if( needSyncPgno<=pPager->dbOrigSize ){
43459         assert( pPager->pTmpSpace!=0 );
43460         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43461       }
43462       return rc;
43463     }
43464     pPgHdr->flags |= PGHDR_NEED_SYNC;
43465     sqlite3PcacheMakeDirty(pPgHdr);
43466     sqlite3PagerUnref(pPgHdr);
43467   }
43468
43469   return SQLITE_OK;
43470 }
43471 #endif
43472
43473 /*
43474 ** Return a pointer to the data for the specified page.
43475 */
43476 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43477   assert( pPg->nRef>0 || pPg->pPager->memDb );
43478   return pPg->pData;
43479 }
43480
43481 /*
43482 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
43483 ** allocated along with the specified page.
43484 */
43485 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43486   return pPg->pExtra;
43487 }
43488
43489 /*
43490 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43491 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
43492 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43493 ** the locking-mode is set to the value specified.
43494 **
43495 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43496 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43497 ** locking-mode.
43498 */
43499 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43500   assert( eMode==PAGER_LOCKINGMODE_QUERY
43501             || eMode==PAGER_LOCKINGMODE_NORMAL
43502             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43503   assert( PAGER_LOCKINGMODE_QUERY<0 );
43504   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43505   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43506   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43507     pPager->exclusiveMode = (u8)eMode;
43508   }
43509   return (int)pPager->exclusiveMode;
43510 }
43511
43512 /*
43513 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43514 **
43515 **    PAGER_JOURNALMODE_DELETE
43516 **    PAGER_JOURNALMODE_TRUNCATE
43517 **    PAGER_JOURNALMODE_PERSIST
43518 **    PAGER_JOURNALMODE_OFF
43519 **    PAGER_JOURNALMODE_MEMORY
43520 **    PAGER_JOURNALMODE_WAL
43521 **
43522 ** The journalmode is set to the value specified if the change is allowed.
43523 ** The change may be disallowed for the following reasons:
43524 **
43525 **   *  An in-memory database can only have its journal_mode set to _OFF
43526 **      or _MEMORY.
43527 **
43528 **   *  Temporary databases cannot have _WAL journalmode.
43529 **
43530 ** The returned indicate the current (possibly updated) journal-mode.
43531 */
43532 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43533   u8 eOld = pPager->journalMode;    /* Prior journalmode */
43534
43535 #ifdef SQLITE_DEBUG
43536   /* The print_pager_state() routine is intended to be used by the debugger
43537   ** only.  We invoke it once here to suppress a compiler warning. */
43538   print_pager_state(pPager);
43539 #endif
43540
43541
43542   /* The eMode parameter is always valid */
43543   assert(      eMode==PAGER_JOURNALMODE_DELETE
43544             || eMode==PAGER_JOURNALMODE_TRUNCATE
43545             || eMode==PAGER_JOURNALMODE_PERSIST
43546             || eMode==PAGER_JOURNALMODE_OFF 
43547             || eMode==PAGER_JOURNALMODE_WAL 
43548             || eMode==PAGER_JOURNALMODE_MEMORY );
43549
43550   /* This routine is only called from the OP_JournalMode opcode, and
43551   ** the logic there will never allow a temporary file to be changed
43552   ** to WAL mode.
43553   */
43554   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43555
43556   /* Do allow the journalmode of an in-memory database to be set to
43557   ** anything other than MEMORY or OFF
43558   */
43559   if( MEMDB ){
43560     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43561     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43562       eMode = eOld;
43563     }
43564   }
43565
43566   if( eMode!=eOld ){
43567
43568     /* Change the journal mode. */
43569     assert( pPager->eState!=PAGER_ERROR );
43570     pPager->journalMode = (u8)eMode;
43571
43572     /* When transistioning from TRUNCATE or PERSIST to any other journal
43573     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43574     ** delete the journal file.
43575     */
43576     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43577     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43578     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43579     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43580     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43581     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43582
43583     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43584     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43585
43586       /* In this case we would like to delete the journal file. If it is
43587       ** not possible, then that is not a problem. Deleting the journal file
43588       ** here is an optimization only.
43589       **
43590       ** Before deleting the journal file, obtain a RESERVED lock on the
43591       ** database file. This ensures that the journal file is not deleted
43592       ** while it is in use by some other client.
43593       */
43594       sqlite3OsClose(pPager->jfd);
43595       if( pPager->eLock>=RESERVED_LOCK ){
43596         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43597       }else{
43598         int rc = SQLITE_OK;
43599         int state = pPager->eState;
43600         assert( state==PAGER_OPEN || state==PAGER_READER );
43601         if( state==PAGER_OPEN ){
43602           rc = sqlite3PagerSharedLock(pPager);
43603         }
43604         if( pPager->eState==PAGER_READER ){
43605           assert( rc==SQLITE_OK );
43606           rc = pagerLockDb(pPager, RESERVED_LOCK);
43607         }
43608         if( rc==SQLITE_OK ){
43609           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43610         }
43611         if( rc==SQLITE_OK && state==PAGER_READER ){
43612           pagerUnlockDb(pPager, SHARED_LOCK);
43613         }else if( state==PAGER_OPEN ){
43614           pager_unlock(pPager);
43615         }
43616         assert( state==pPager->eState );
43617       }
43618     }
43619   }
43620
43621   /* Return the new journal mode */
43622   return (int)pPager->journalMode;
43623 }
43624
43625 /*
43626 ** Return the current journal mode.
43627 */
43628 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43629   return (int)pPager->journalMode;
43630 }
43631
43632 /*
43633 ** Return TRUE if the pager is in a state where it is OK to change the
43634 ** journalmode.  Journalmode changes can only happen when the database
43635 ** is unmodified.
43636 */
43637 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43638   assert( assert_pager_state(pPager) );
43639   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43640   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43641   return 1;
43642 }
43643
43644 /*
43645 ** Get/set the size-limit used for persistent journal files.
43646 **
43647 ** Setting the size limit to -1 means no limit is enforced.
43648 ** An attempt to set a limit smaller than -1 is a no-op.
43649 */
43650 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43651   if( iLimit>=-1 ){
43652     pPager->journalSizeLimit = iLimit;
43653     sqlite3WalLimit(pPager->pWal, iLimit);
43654   }
43655   return pPager->journalSizeLimit;
43656 }
43657
43658 /*
43659 ** Return a pointer to the pPager->pBackup variable. The backup module
43660 ** in backup.c maintains the content of this variable. This module
43661 ** uses it opaquely as an argument to sqlite3BackupRestart() and
43662 ** sqlite3BackupUpdate() only.
43663 */
43664 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43665   return &pPager->pBackup;
43666 }
43667
43668 #ifndef SQLITE_OMIT_VACUUM
43669 /*
43670 ** Unless this is an in-memory or temporary database, clear the pager cache.
43671 */
43672 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
43673   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
43674 }
43675 #endif
43676
43677 #ifndef SQLITE_OMIT_WAL
43678 /*
43679 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
43680 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43681 ** or wal_blocking_checkpoint() API functions.
43682 **
43683 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43684 */
43685 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43686   int rc = SQLITE_OK;
43687   if( pPager->pWal ){
43688     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43689         pPager->xBusyHandler, pPager->pBusyHandlerArg,
43690         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
43691         pnLog, pnCkpt
43692     );
43693   }
43694   return rc;
43695 }
43696
43697 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
43698   return sqlite3WalCallback(pPager->pWal);
43699 }
43700
43701 /*
43702 ** Return true if the underlying VFS for the given pager supports the
43703 ** primitives necessary for write-ahead logging.
43704 */
43705 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
43706   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
43707   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
43708 }
43709
43710 /*
43711 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
43712 ** is obtained instead, immediately release it.
43713 */
43714 static int pagerExclusiveLock(Pager *pPager){
43715   int rc;                         /* Return code */
43716
43717   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43718   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43719   if( rc!=SQLITE_OK ){
43720     /* If the attempt to grab the exclusive lock failed, release the 
43721     ** pending lock that may have been obtained instead.  */
43722     pagerUnlockDb(pPager, SHARED_LOCK);
43723   }
43724
43725   return rc;
43726 }
43727
43728 /*
43729 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
43730 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43731 ** lock on the database file and use heap-memory to store the wal-index
43732 ** in. Otherwise, use the normal shared-memory.
43733 */
43734 static int pagerOpenWal(Pager *pPager){
43735   int rc = SQLITE_OK;
43736
43737   assert( pPager->pWal==0 && pPager->tempFile==0 );
43738   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43739
43740   /* If the pager is already in exclusive-mode, the WAL module will use 
43741   ** heap-memory for the wal-index instead of the VFS shared-memory 
43742   ** implementation. Take the exclusive lock now, before opening the WAL
43743   ** file, to make sure this is safe.
43744   */
43745   if( pPager->exclusiveMode ){
43746     rc = pagerExclusiveLock(pPager);
43747   }
43748
43749   /* Open the connection to the log file. If this operation fails, 
43750   ** (e.g. due to malloc() failure), return an error code.
43751   */
43752   if( rc==SQLITE_OK ){
43753     rc = sqlite3WalOpen(pPager->pVfs, 
43754         pPager->fd, pPager->zWal, pPager->exclusiveMode,
43755         pPager->journalSizeLimit, &pPager->pWal
43756     );
43757   }
43758
43759   return rc;
43760 }
43761
43762
43763 /*
43764 ** The caller must be holding a SHARED lock on the database file to call
43765 ** this function.
43766 **
43767 ** If the pager passed as the first argument is open on a real database
43768 ** file (not a temp file or an in-memory database), and the WAL file
43769 ** is not already open, make an attempt to open it now. If successful,
43770 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
43771 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43772 ** not modified in either case.
43773 **
43774 ** If the pager is open on a temp-file (or in-memory database), or if
43775 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43776 ** without doing anything.
43777 */
43778 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43779   Pager *pPager,                  /* Pager object */
43780   int *pbOpen                     /* OUT: Set to true if call is a no-op */
43781 ){
43782   int rc = SQLITE_OK;             /* Return code */
43783
43784   assert( assert_pager_state(pPager) );
43785   assert( pPager->eState==PAGER_OPEN   || pbOpen );
43786   assert( pPager->eState==PAGER_READER || !pbOpen );
43787   assert( pbOpen==0 || *pbOpen==0 );
43788   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43789
43790   if( !pPager->tempFile && !pPager->pWal ){
43791     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43792
43793     /* Close any rollback journal previously open */
43794     sqlite3OsClose(pPager->jfd);
43795
43796     rc = pagerOpenWal(pPager);
43797     if( rc==SQLITE_OK ){
43798       pPager->journalMode = PAGER_JOURNALMODE_WAL;
43799       pPager->eState = PAGER_OPEN;
43800     }
43801   }else{
43802     *pbOpen = 1;
43803   }
43804
43805   return rc;
43806 }
43807
43808 /*
43809 ** This function is called to close the connection to the log file prior
43810 ** to switching from WAL to rollback mode.
43811 **
43812 ** Before closing the log file, this function attempts to take an 
43813 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43814 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43815 ** If successful, the EXCLUSIVE lock is not released before returning.
43816 */
43817 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43818   int rc = SQLITE_OK;
43819
43820   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43821
43822   /* If the log file is not already open, but does exist in the file-system,
43823   ** it may need to be checkpointed before the connection can switch to
43824   ** rollback mode. Open it now so this can happen.
43825   */
43826   if( !pPager->pWal ){
43827     int logexists = 0;
43828     rc = pagerLockDb(pPager, SHARED_LOCK);
43829     if( rc==SQLITE_OK ){
43830       rc = sqlite3OsAccess(
43831           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43832       );
43833     }
43834     if( rc==SQLITE_OK && logexists ){
43835       rc = pagerOpenWal(pPager);
43836     }
43837   }
43838     
43839   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43840   ** the database file, the log and log-summary files will be deleted.
43841   */
43842   if( rc==SQLITE_OK && pPager->pWal ){
43843     rc = pagerExclusiveLock(pPager);
43844     if( rc==SQLITE_OK ){
43845       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43846                            pPager->pageSize, (u8*)pPager->pTmpSpace);
43847       pPager->pWal = 0;
43848     }
43849   }
43850   return rc;
43851 }
43852
43853 #ifdef SQLITE_ENABLE_ZIPVFS
43854 /*
43855 ** A read-lock must be held on the pager when this function is called. If
43856 ** the pager is in WAL mode and the WAL file currently contains one or more
43857 ** frames, return the size in bytes of the page images stored within the
43858 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
43859 ** is empty, return 0.
43860 */
43861 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
43862   assert( pPager->eState==PAGER_READER );
43863   return sqlite3WalFramesize(pPager->pWal);
43864 }
43865 #endif
43866
43867 #ifdef SQLITE_HAS_CODEC
43868 /*
43869 ** This function is called by the wal module when writing page content
43870 ** into the log file.
43871 **
43872 ** This function returns a pointer to a buffer containing the encrypted
43873 ** page content. If a malloc fails, this function may return NULL.
43874 */
43875 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43876   void *aData = 0;
43877   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43878   return aData;
43879 }
43880 #endif /* SQLITE_HAS_CODEC */
43881
43882 #endif /* !SQLITE_OMIT_WAL */
43883
43884 #endif /* SQLITE_OMIT_DISKIO */
43885
43886 /************** End of pager.c ***********************************************/
43887 /************** Begin file wal.c *********************************************/
43888 /*
43889 ** 2010 February 1
43890 **
43891 ** The author disclaims copyright to this source code.  In place of
43892 ** a legal notice, here is a blessing:
43893 **
43894 **    May you do good and not evil.
43895 **    May you find forgiveness for yourself and forgive others.
43896 **    May you share freely, never taking more than you give.
43897 **
43898 *************************************************************************
43899 **
43900 ** This file contains the implementation of a write-ahead log (WAL) used in 
43901 ** "journal_mode=WAL" mode.
43902 **
43903 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43904 **
43905 ** A WAL file consists of a header followed by zero or more "frames".
43906 ** Each frame records the revised content of a single page from the
43907 ** database file.  All changes to the database are recorded by writing
43908 ** frames into the WAL.  Transactions commit when a frame is written that
43909 ** contains a commit marker.  A single WAL can and usually does record 
43910 ** multiple transactions.  Periodically, the content of the WAL is
43911 ** transferred back into the database file in an operation called a
43912 ** "checkpoint".
43913 **
43914 ** A single WAL file can be used multiple times.  In other words, the
43915 ** WAL can fill up with frames and then be checkpointed and then new
43916 ** frames can overwrite the old ones.  A WAL always grows from beginning
43917 ** toward the end.  Checksums and counters attached to each frame are
43918 ** used to determine which frames within the WAL are valid and which
43919 ** are leftovers from prior checkpoints.
43920 **
43921 ** The WAL header is 32 bytes in size and consists of the following eight
43922 ** big-endian 32-bit unsigned integer values:
43923 **
43924 **     0: Magic number.  0x377f0682 or 0x377f0683
43925 **     4: File format version.  Currently 3007000
43926 **     8: Database page size.  Example: 1024
43927 **    12: Checkpoint sequence number
43928 **    16: Salt-1, random integer incremented with each checkpoint
43929 **    20: Salt-2, a different random integer changing with each ckpt
43930 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
43931 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
43932 **
43933 ** Immediately following the wal-header are zero or more frames. Each
43934 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43935 ** of page data. The frame-header is six big-endian 32-bit unsigned 
43936 ** integer values, as follows:
43937 **
43938 **     0: Page number.
43939 **     4: For commit records, the size of the database image in pages 
43940 **        after the commit. For all other records, zero.
43941 **     8: Salt-1 (copied from the header)
43942 **    12: Salt-2 (copied from the header)
43943 **    16: Checksum-1.
43944 **    20: Checksum-2.
43945 **
43946 ** A frame is considered valid if and only if the following conditions are
43947 ** true:
43948 **
43949 **    (1) The salt-1 and salt-2 values in the frame-header match
43950 **        salt values in the wal-header
43951 **
43952 **    (2) The checksum values in the final 8 bytes of the frame-header
43953 **        exactly match the checksum computed consecutively on the
43954 **        WAL header and the first 8 bytes and the content of all frames
43955 **        up to and including the current frame.
43956 **
43957 ** The checksum is computed using 32-bit big-endian integers if the
43958 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43959 ** is computed using little-endian if the magic number is 0x377f0682.
43960 ** The checksum values are always stored in the frame header in a
43961 ** big-endian format regardless of which byte order is used to compute
43962 ** the checksum.  The checksum is computed by interpreting the input as
43963 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
43964 ** algorithm used for the checksum is as follows:
43965 ** 
43966 **   for i from 0 to n-1 step 2:
43967 **     s0 += x[i] + s1;
43968 **     s1 += x[i+1] + s0;
43969 **   endfor
43970 **
43971 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43972 ** in reverse order (the largest fibonacci weight occurs on the first element
43973 ** of the sequence being summed.)  The s1 value spans all 32-bit 
43974 ** terms of the sequence whereas s0 omits the final term.
43975 **
43976 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43977 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43978 ** The VFS.xSync operations serve as write barriers - all writes launched
43979 ** before the xSync must complete before any write that launches after the
43980 ** xSync begins.
43981 **
43982 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43983 ** value is randomized.  This prevents old and new frames in the WAL from
43984 ** being considered valid at the same time and being checkpointing together
43985 ** following a crash.
43986 **
43987 ** READER ALGORITHM
43988 **
43989 ** To read a page from the database (call it page number P), a reader
43990 ** first checks the WAL to see if it contains page P.  If so, then the
43991 ** last valid instance of page P that is a followed by a commit frame
43992 ** or is a commit frame itself becomes the value read.  If the WAL
43993 ** contains no copies of page P that are valid and which are a commit
43994 ** frame or are followed by a commit frame, then page P is read from
43995 ** the database file.
43996 **
43997 ** To start a read transaction, the reader records the index of the last
43998 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
43999 ** for all subsequent read operations.  New transactions can be appended
44000 ** to the WAL, but as long as the reader uses its original mxFrame value
44001 ** and ignores the newly appended content, it will see a consistent snapshot
44002 ** of the database from a single point in time.  This technique allows
44003 ** multiple concurrent readers to view different versions of the database
44004 ** content simultaneously.
44005 **
44006 ** The reader algorithm in the previous paragraphs works correctly, but 
44007 ** because frames for page P can appear anywhere within the WAL, the
44008 ** reader has to scan the entire WAL looking for page P frames.  If the
44009 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44010 ** and read performance suffers.  To overcome this problem, a separate
44011 ** data structure called the wal-index is maintained to expedite the
44012 ** search for frames of a particular page.
44013 ** 
44014 ** WAL-INDEX FORMAT
44015 **
44016 ** Conceptually, the wal-index is shared memory, though VFS implementations
44017 ** might choose to implement the wal-index using a mmapped file.  Because
44018 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
44019 ** on a network filesystem.  All users of the database must be able to
44020 ** share memory.
44021 **
44022 ** The wal-index is transient.  After a crash, the wal-index can (and should
44023 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
44024 ** to either truncate or zero the header of the wal-index when the last
44025 ** connection to it closes.  Because the wal-index is transient, it can
44026 ** use an architecture-specific format; it does not have to be cross-platform.
44027 ** Hence, unlike the database and WAL file formats which store all values
44028 ** as big endian, the wal-index can store multi-byte values in the native
44029 ** byte order of the host computer.
44030 **
44031 ** The purpose of the wal-index is to answer this question quickly:  Given
44032 ** a page number P and a maximum frame index M, return the index of the 
44033 ** last frame in the wal before frame M for page P in the WAL, or return
44034 ** NULL if there are no frames for page P in the WAL prior to M.
44035 **
44036 ** The wal-index consists of a header region, followed by an one or
44037 ** more index blocks.  
44038 **
44039 ** The wal-index header contains the total number of frames within the WAL
44040 ** in the mxFrame field.
44041 **
44042 ** Each index block except for the first contains information on 
44043 ** HASHTABLE_NPAGE frames. The first index block contains information on
44044 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
44045 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44046 ** first index block are the same size as all other index blocks in the
44047 ** wal-index.
44048 **
44049 ** Each index block contains two sections, a page-mapping that contains the
44050 ** database page number associated with each wal frame, and a hash-table 
44051 ** that allows readers to query an index block for a specific page number.
44052 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44053 ** for the first index block) 32-bit page numbers. The first entry in the 
44054 ** first index-block contains the database page number corresponding to the
44055 ** first frame in the WAL file. The first entry in the second index block
44056 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44057 ** the log, and so on.
44058 **
44059 ** The last index block in a wal-index usually contains less than the full
44060 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44061 ** depending on the contents of the WAL file. This does not change the
44062 ** allocated size of the page-mapping array - the page-mapping array merely
44063 ** contains unused entries.
44064 **
44065 ** Even without using the hash table, the last frame for page P
44066 ** can be found by scanning the page-mapping sections of each index block
44067 ** starting with the last index block and moving toward the first, and
44068 ** within each index block, starting at the end and moving toward the
44069 ** beginning.  The first entry that equals P corresponds to the frame
44070 ** holding the content for that page.
44071 **
44072 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44073 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44074 ** hash table for each page number in the mapping section, so the hash 
44075 ** table is never more than half full.  The expected number of collisions 
44076 ** prior to finding a match is 1.  Each entry of the hash table is an
44077 ** 1-based index of an entry in the mapping section of the same
44078 ** index block.   Let K be the 1-based index of the largest entry in
44079 ** the mapping section.  (For index blocks other than the last, K will
44080 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44081 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
44082 ** contain a value of 0.
44083 **
44084 ** To look for page P in the hash table, first compute a hash iKey on
44085 ** P as follows:
44086 **
44087 **      iKey = (P * 383) % HASHTABLE_NSLOT
44088 **
44089 ** Then start scanning entries of the hash table, starting with iKey
44090 ** (wrapping around to the beginning when the end of the hash table is
44091 ** reached) until an unused hash slot is found. Let the first unused slot
44092 ** be at index iUnused.  (iUnused might be less than iKey if there was
44093 ** wrap-around.) Because the hash table is never more than half full,
44094 ** the search is guaranteed to eventually hit an unused entry.  Let 
44095 ** iMax be the value between iKey and iUnused, closest to iUnused,
44096 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
44097 ** no hash slot such that aHash[i]==p) then page P is not in the
44098 ** current index block.  Otherwise the iMax-th mapping entry of the
44099 ** current index block corresponds to the last entry that references 
44100 ** page P.
44101 **
44102 ** A hash search begins with the last index block and moves toward the
44103 ** first index block, looking for entries corresponding to page P.  On
44104 ** average, only two or three slots in each index block need to be
44105 ** examined in order to either find the last entry for page P, or to
44106 ** establish that no such entry exists in the block.  Each index block
44107 ** holds over 4000 entries.  So two or three index blocks are sufficient
44108 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
44109 ** comparisons (on average) suffice to either locate a frame in the
44110 ** WAL or to establish that the frame does not exist in the WAL.  This
44111 ** is much faster than scanning the entire 10MB WAL.
44112 **
44113 ** Note that entries are added in order of increasing K.  Hence, one
44114 ** reader might be using some value K0 and a second reader that started
44115 ** at a later time (after additional transactions were added to the WAL
44116 ** and to the wal-index) might be using a different value K1, where K1>K0.
44117 ** Both readers can use the same hash table and mapping section to get
44118 ** the correct result.  There may be entries in the hash table with
44119 ** K>K0 but to the first reader, those entries will appear to be unused
44120 ** slots in the hash table and so the first reader will get an answer as
44121 ** if no values greater than K0 had ever been inserted into the hash table
44122 ** in the first place - which is what reader one wants.  Meanwhile, the
44123 ** second reader using K1 will see additional values that were inserted
44124 ** later, which is exactly what reader two wants.  
44125 **
44126 ** When a rollback occurs, the value of K is decreased. Hash table entries
44127 ** that correspond to frames greater than the new K value are removed
44128 ** from the hash table at this point.
44129 */
44130 #ifndef SQLITE_OMIT_WAL
44131
44132
44133 /*
44134 ** Trace output macros
44135 */
44136 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44137 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44138 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
44139 #else
44140 # define WALTRACE(X)
44141 #endif
44142
44143 /*
44144 ** The maximum (and only) versions of the wal and wal-index formats
44145 ** that may be interpreted by this version of SQLite.
44146 **
44147 ** If a client begins recovering a WAL file and finds that (a) the checksum
44148 ** values in the wal-header are correct and (b) the version field is not
44149 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44150 **
44151 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
44152 ** checksum test is successful) and finds that the version field is not
44153 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44154 ** returns SQLITE_CANTOPEN.
44155 */
44156 #define WAL_MAX_VERSION      3007000
44157 #define WALINDEX_MAX_VERSION 3007000
44158
44159 /*
44160 ** Indices of various locking bytes.   WAL_NREADER is the number
44161 ** of available reader locks and should be at least 3.
44162 */
44163 #define WAL_WRITE_LOCK         0
44164 #define WAL_ALL_BUT_WRITE      1
44165 #define WAL_CKPT_LOCK          1
44166 #define WAL_RECOVER_LOCK       2
44167 #define WAL_READ_LOCK(I)       (3+(I))
44168 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
44169
44170
44171 /* Object declarations */
44172 typedef struct WalIndexHdr WalIndexHdr;
44173 typedef struct WalIterator WalIterator;
44174 typedef struct WalCkptInfo WalCkptInfo;
44175
44176
44177 /*
44178 ** The following object holds a copy of the wal-index header content.
44179 **
44180 ** The actual header in the wal-index consists of two copies of this
44181 ** object.
44182 **
44183 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44184 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
44185 ** added in 3.7.1 when support for 64K pages was added.  
44186 */
44187 struct WalIndexHdr {
44188   u32 iVersion;                   /* Wal-index version */
44189   u32 unused;                     /* Unused (padding) field */
44190   u32 iChange;                    /* Counter incremented each transaction */
44191   u8 isInit;                      /* 1 when initialized */
44192   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
44193   u16 szPage;                     /* Database page size in bytes. 1==64K */
44194   u32 mxFrame;                    /* Index of last valid frame in the WAL */
44195   u32 nPage;                      /* Size of database in pages */
44196   u32 aFrameCksum[2];             /* Checksum of last frame in log */
44197   u32 aSalt[2];                   /* Two salt values copied from WAL header */
44198   u32 aCksum[2];                  /* Checksum over all prior fields */
44199 };
44200
44201 /*
44202 ** A copy of the following object occurs in the wal-index immediately
44203 ** following the second copy of the WalIndexHdr.  This object stores
44204 ** information used by checkpoint.
44205 **
44206 ** nBackfill is the number of frames in the WAL that have been written
44207 ** back into the database. (We call the act of moving content from WAL to
44208 ** database "backfilling".)  The nBackfill number is never greater than
44209 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
44210 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44211 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44212 ** mxFrame back to zero when the WAL is reset.
44213 **
44214 ** There is one entry in aReadMark[] for each reader lock.  If a reader
44215 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44216 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
44217 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
44218 ** a special case; its value is never used and it exists as a place-holder
44219 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
44220 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44221 ** directly from the database.
44222 **
44223 ** The value of aReadMark[K] may only be changed by a thread that
44224 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
44225 ** aReadMark[K] cannot changed while there is a reader is using that mark
44226 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44227 **
44228 ** The checkpointer may only transfer frames from WAL to database where
44229 ** the frame numbers are less than or equal to every aReadMark[] that is
44230 ** in use (that is, every aReadMark[j] for which there is a corresponding
44231 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
44232 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44233 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
44234 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44235 ** in the WAL has been backfilled into the database) then new readers
44236 ** will choose aReadMark[0] which has value 0 and hence such reader will
44237 ** get all their all content directly from the database file and ignore 
44238 ** the WAL.
44239 **
44240 ** Writers normally append new frames to the end of the WAL.  However,
44241 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44242 ** written back into the database) and if no readers are using the WAL
44243 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44244 ** the writer will first "reset" the WAL back to the beginning and start
44245 ** writing new content beginning at frame 1.
44246 **
44247 ** We assume that 32-bit loads are atomic and so no locks are needed in
44248 ** order to read from any aReadMark[] entries.
44249 */
44250 struct WalCkptInfo {
44251   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
44252   u32 aReadMark[WAL_NREADER];     /* Reader marks */
44253 };
44254 #define READMARK_NOT_USED  0xffffffff
44255
44256
44257 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44258 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44259 ** only support mandatory file-locks, we do not read or write data
44260 ** from the region of the file on which locks are applied.
44261 */
44262 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44263 #define WALINDEX_LOCK_RESERVED 16
44264 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44265
44266 /* Size of header before each frame in wal */
44267 #define WAL_FRAME_HDRSIZE 24
44268
44269 /* Size of write ahead log header, including checksum. */
44270 /* #define WAL_HDRSIZE 24 */
44271 #define WAL_HDRSIZE 32
44272
44273 /* WAL magic value. Either this value, or the same value with the least
44274 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44275 ** big-endian format in the first 4 bytes of a WAL file.
44276 **
44277 ** If the LSB is set, then the checksums for each frame within the WAL
44278 ** file are calculated by treating all data as an array of 32-bit 
44279 ** big-endian words. Otherwise, they are calculated by interpreting 
44280 ** all data as 32-bit little-endian words.
44281 */
44282 #define WAL_MAGIC 0x377f0682
44283
44284 /*
44285 ** Return the offset of frame iFrame in the write-ahead log file, 
44286 ** assuming a database page size of szPage bytes. The offset returned
44287 ** is to the start of the write-ahead log frame-header.
44288 */
44289 #define walFrameOffset(iFrame, szPage) (                               \
44290   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44291 )
44292
44293 /*
44294 ** An open write-ahead log file is represented by an instance of the
44295 ** following object.
44296 */
44297 struct Wal {
44298   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44299   sqlite3_file *pDbFd;       /* File handle for the database file */
44300   sqlite3_file *pWalFd;      /* File handle for WAL file */
44301   u32 iCallback;             /* Value to pass to log callback (or 0) */
44302   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44303   int nWiData;               /* Size of array apWiData */
44304   int szFirstBlock;          /* Size of first block written to WAL file */
44305   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44306   u32 szPage;                /* Database page size */
44307   i16 readLock;              /* Which read lock is being held.  -1 for none */
44308   u8 syncFlags;              /* Flags to use to sync header writes */
44309   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44310   u8 writeLock;              /* True if in a write transaction */
44311   u8 ckptLock;               /* True if holding a checkpoint lock */
44312   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44313   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
44314   u8 syncHeader;             /* Fsync the WAL header if true */
44315   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
44316   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44317   const char *zWalName;      /* Name of WAL file */
44318   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44319 #ifdef SQLITE_DEBUG
44320   u8 lockError;              /* True if a locking error has occurred */
44321 #endif
44322 };
44323
44324 /*
44325 ** Candidate values for Wal.exclusiveMode.
44326 */
44327 #define WAL_NORMAL_MODE     0
44328 #define WAL_EXCLUSIVE_MODE  1     
44329 #define WAL_HEAPMEMORY_MODE 2
44330
44331 /*
44332 ** Possible values for WAL.readOnly
44333 */
44334 #define WAL_RDWR        0    /* Normal read/write connection */
44335 #define WAL_RDONLY      1    /* The WAL file is readonly */
44336 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44337
44338 /*
44339 ** Each page of the wal-index mapping contains a hash-table made up of
44340 ** an array of HASHTABLE_NSLOT elements of the following type.
44341 */
44342 typedef u16 ht_slot;
44343
44344 /*
44345 ** This structure is used to implement an iterator that loops through
44346 ** all frames in the WAL in database page order. Where two or more frames
44347 ** correspond to the same database page, the iterator visits only the 
44348 ** frame most recently written to the WAL (in other words, the frame with
44349 ** the largest index).
44350 **
44351 ** The internals of this structure are only accessed by:
44352 **
44353 **   walIteratorInit() - Create a new iterator,
44354 **   walIteratorNext() - Step an iterator,
44355 **   walIteratorFree() - Free an iterator.
44356 **
44357 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44358 */
44359 struct WalIterator {
44360   int iPrior;                     /* Last result returned from the iterator */
44361   int nSegment;                   /* Number of entries in aSegment[] */
44362   struct WalSegment {
44363     int iNext;                    /* Next slot in aIndex[] not yet returned */
44364     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44365     u32 *aPgno;                   /* Array of page numbers. */
44366     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44367     int iZero;                    /* Frame number associated with aPgno[0] */
44368   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44369 };
44370
44371 /*
44372 ** Define the parameters of the hash tables in the wal-index file. There
44373 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44374 ** wal-index.
44375 **
44376 ** Changing any of these constants will alter the wal-index format and
44377 ** create incompatibilities.
44378 */
44379 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44380 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44381 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44382
44383 /* 
44384 ** The block of page numbers associated with the first hash-table in a
44385 ** wal-index is smaller than usual. This is so that there is a complete
44386 ** hash-table on each aligned 32KB page of the wal-index.
44387 */
44388 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44389
44390 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44391 #define WALINDEX_PGSZ   (                                         \
44392     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44393 )
44394
44395 /*
44396 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44397 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44398 ** numbered from zero.
44399 **
44400 ** If this call is successful, *ppPage is set to point to the wal-index
44401 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44402 ** then an SQLite error code is returned and *ppPage is set to 0.
44403 */
44404 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44405   int rc = SQLITE_OK;
44406
44407   /* Enlarge the pWal->apWiData[] array if required */
44408   if( pWal->nWiData<=iPage ){
44409     int nByte = sizeof(u32*)*(iPage+1);
44410     volatile u32 **apNew;
44411     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44412     if( !apNew ){
44413       *ppPage = 0;
44414       return SQLITE_NOMEM;
44415     }
44416     memset((void*)&apNew[pWal->nWiData], 0,
44417            sizeof(u32*)*(iPage+1-pWal->nWiData));
44418     pWal->apWiData = apNew;
44419     pWal->nWiData = iPage+1;
44420   }
44421
44422   /* Request a pointer to the required page from the VFS */
44423   if( pWal->apWiData[iPage]==0 ){
44424     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44425       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44426       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44427     }else{
44428       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
44429           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44430       );
44431       if( rc==SQLITE_READONLY ){
44432         pWal->readOnly |= WAL_SHM_RDONLY;
44433         rc = SQLITE_OK;
44434       }
44435     }
44436   }
44437
44438   *ppPage = pWal->apWiData[iPage];
44439   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44440   return rc;
44441 }
44442
44443 /*
44444 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44445 */
44446 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44447   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44448   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44449 }
44450
44451 /*
44452 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44453 */
44454 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44455   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44456   return (volatile WalIndexHdr*)pWal->apWiData[0];
44457 }
44458
44459 /*
44460 ** The argument to this macro must be of type u32. On a little-endian
44461 ** architecture, it returns the u32 value that results from interpreting
44462 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44463 ** returns the value that would be produced by intepreting the 4 bytes
44464 ** of the input value as a little-endian integer.
44465 */
44466 #define BYTESWAP32(x) ( \
44467     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44468   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44469 )
44470
44471 /*
44472 ** Generate or extend an 8 byte checksum based on the data in 
44473 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44474 ** initial values of 0 and 0 if aIn==NULL).
44475 **
44476 ** The checksum is written back into aOut[] before returning.
44477 **
44478 ** nByte must be a positive multiple of 8.
44479 */
44480 static void walChecksumBytes(
44481   int nativeCksum, /* True for native byte-order, false for non-native */
44482   u8 *a,           /* Content to be checksummed */
44483   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44484   const u32 *aIn,  /* Initial checksum value input */
44485   u32 *aOut        /* OUT: Final checksum value output */
44486 ){
44487   u32 s1, s2;
44488   u32 *aData = (u32 *)a;
44489   u32 *aEnd = (u32 *)&a[nByte];
44490
44491   if( aIn ){
44492     s1 = aIn[0];
44493     s2 = aIn[1];
44494   }else{
44495     s1 = s2 = 0;
44496   }
44497
44498   assert( nByte>=8 );
44499   assert( (nByte&0x00000007)==0 );
44500
44501   if( nativeCksum ){
44502     do {
44503       s1 += *aData++ + s2;
44504       s2 += *aData++ + s1;
44505     }while( aData<aEnd );
44506   }else{
44507     do {
44508       s1 += BYTESWAP32(aData[0]) + s2;
44509       s2 += BYTESWAP32(aData[1]) + s1;
44510       aData += 2;
44511     }while( aData<aEnd );
44512   }
44513
44514   aOut[0] = s1;
44515   aOut[1] = s2;
44516 }
44517
44518 static void walShmBarrier(Wal *pWal){
44519   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44520     sqlite3OsShmBarrier(pWal->pDbFd);
44521   }
44522 }
44523
44524 /*
44525 ** Write the header information in pWal->hdr into the wal-index.
44526 **
44527 ** The checksum on pWal->hdr is updated before it is written.
44528 */
44529 static void walIndexWriteHdr(Wal *pWal){
44530   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44531   const int nCksum = offsetof(WalIndexHdr, aCksum);
44532
44533   assert( pWal->writeLock );
44534   pWal->hdr.isInit = 1;
44535   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44536   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44537   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44538   walShmBarrier(pWal);
44539   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44540 }
44541
44542 /*
44543 ** This function encodes a single frame header and writes it to a buffer
44544 ** supplied by the caller. A frame-header is made up of a series of 
44545 ** 4-byte big-endian integers, as follows:
44546 **
44547 **     0: Page number.
44548 **     4: For commit records, the size of the database image in pages 
44549 **        after the commit. For all other records, zero.
44550 **     8: Salt-1 (copied from the wal-header)
44551 **    12: Salt-2 (copied from the wal-header)
44552 **    16: Checksum-1.
44553 **    20: Checksum-2.
44554 */
44555 static void walEncodeFrame(
44556   Wal *pWal,                      /* The write-ahead log */
44557   u32 iPage,                      /* Database page number for frame */
44558   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
44559   u8 *aData,                      /* Pointer to page data */
44560   u8 *aFrame                      /* OUT: Write encoded frame here */
44561 ){
44562   int nativeCksum;                /* True for native byte-order checksums */
44563   u32 *aCksum = pWal->hdr.aFrameCksum;
44564   assert( WAL_FRAME_HDRSIZE==24 );
44565   sqlite3Put4byte(&aFrame[0], iPage);
44566   sqlite3Put4byte(&aFrame[4], nTruncate);
44567   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44568
44569   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44570   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44571   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44572
44573   sqlite3Put4byte(&aFrame[16], aCksum[0]);
44574   sqlite3Put4byte(&aFrame[20], aCksum[1]);
44575 }
44576
44577 /*
44578 ** Check to see if the frame with header in aFrame[] and content
44579 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
44580 ** *pnTruncate and return true.  Return if the frame is not valid.
44581 */
44582 static int walDecodeFrame(
44583   Wal *pWal,                      /* The write-ahead log */
44584   u32 *piPage,                    /* OUT: Database page number for frame */
44585   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
44586   u8 *aData,                      /* Pointer to page data (for checksum) */
44587   u8 *aFrame                      /* Frame data */
44588 ){
44589   int nativeCksum;                /* True for native byte-order checksums */
44590   u32 *aCksum = pWal->hdr.aFrameCksum;
44591   u32 pgno;                       /* Page number of the frame */
44592   assert( WAL_FRAME_HDRSIZE==24 );
44593
44594   /* A frame is only valid if the salt values in the frame-header
44595   ** match the salt values in the wal-header. 
44596   */
44597   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44598     return 0;
44599   }
44600
44601   /* A frame is only valid if the page number is creater than zero.
44602   */
44603   pgno = sqlite3Get4byte(&aFrame[0]);
44604   if( pgno==0 ){
44605     return 0;
44606   }
44607
44608   /* A frame is only valid if a checksum of the WAL header,
44609   ** all prior frams, the first 16 bytes of this frame-header, 
44610   ** and the frame-data matches the checksum in the last 8 
44611   ** bytes of this frame-header.
44612   */
44613   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44614   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44615   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44616   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
44617    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
44618   ){
44619     /* Checksum failed. */
44620     return 0;
44621   }
44622
44623   /* If we reach this point, the frame is valid.  Return the page number
44624   ** and the new database size.
44625   */
44626   *piPage = pgno;
44627   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44628   return 1;
44629 }
44630
44631
44632 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44633 /*
44634 ** Names of locks.  This routine is used to provide debugging output and is not
44635 ** a part of an ordinary build.
44636 */
44637 static const char *walLockName(int lockIdx){
44638   if( lockIdx==WAL_WRITE_LOCK ){
44639     return "WRITE-LOCK";
44640   }else if( lockIdx==WAL_CKPT_LOCK ){
44641     return "CKPT-LOCK";
44642   }else if( lockIdx==WAL_RECOVER_LOCK ){
44643     return "RECOVER-LOCK";
44644   }else{
44645     static char zName[15];
44646     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44647                      lockIdx-WAL_READ_LOCK(0));
44648     return zName;
44649   }
44650 }
44651 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44652     
44653
44654 /*
44655 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
44656 ** A lock cannot be moved directly between shared and exclusive - it must go
44657 ** through the unlocked state first.
44658 **
44659 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44660 */
44661 static int walLockShared(Wal *pWal, int lockIdx){
44662   int rc;
44663   if( pWal->exclusiveMode ) return SQLITE_OK;
44664   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44665                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44666   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44667             walLockName(lockIdx), rc ? "failed" : "ok"));
44668   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44669   return rc;
44670 }
44671 static void walUnlockShared(Wal *pWal, int lockIdx){
44672   if( pWal->exclusiveMode ) return;
44673   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44674                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44675   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44676 }
44677 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44678   int rc;
44679   if( pWal->exclusiveMode ) return SQLITE_OK;
44680   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44681                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44682   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44683             walLockName(lockIdx), n, rc ? "failed" : "ok"));
44684   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44685   return rc;
44686 }
44687 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44688   if( pWal->exclusiveMode ) return;
44689   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44690                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44691   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44692              walLockName(lockIdx), n));
44693 }
44694
44695 /*
44696 ** Compute a hash on a page number.  The resulting hash value must land
44697 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
44698 ** the hash to the next value in the event of a collision.
44699 */
44700 static int walHash(u32 iPage){
44701   assert( iPage>0 );
44702   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44703   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
44704 }
44705 static int walNextHash(int iPriorHash){
44706   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
44707 }
44708
44709 /* 
44710 ** Return pointers to the hash table and page number array stored on
44711 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
44712 ** numbered starting from 0.
44713 **
44714 ** Set output variable *paHash to point to the start of the hash table
44715 ** in the wal-index file. Set *piZero to one less than the frame 
44716 ** number of the first frame indexed by this hash table. If a
44717 ** slot in the hash table is set to N, it refers to frame number 
44718 ** (*piZero+N) in the log.
44719 **
44720 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
44721 ** first frame indexed by the hash table, frame (*piZero+1).
44722 */
44723 static int walHashGet(
44724   Wal *pWal,                      /* WAL handle */
44725   int iHash,                      /* Find the iHash'th table */
44726   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
44727   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
44728   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
44729 ){
44730   int rc;                         /* Return code */
44731   volatile u32 *aPgno;
44732
44733   rc = walIndexPage(pWal, iHash, &aPgno);
44734   assert( rc==SQLITE_OK || iHash>0 );
44735
44736   if( rc==SQLITE_OK ){
44737     u32 iZero;
44738     volatile ht_slot *aHash;
44739
44740     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
44741     if( iHash==0 ){
44742       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
44743       iZero = 0;
44744     }else{
44745       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
44746     }
44747   
44748     *paPgno = &aPgno[-1];
44749     *paHash = aHash;
44750     *piZero = iZero;
44751   }
44752   return rc;
44753 }
44754
44755 /*
44756 ** Return the number of the wal-index page that contains the hash-table
44757 ** and page-number array that contain entries corresponding to WAL frame
44758 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
44759 ** are numbered starting from 0.
44760 */
44761 static int walFramePage(u32 iFrame){
44762   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44763   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44764        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44765        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44766        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44767        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44768   );
44769   return iHash;
44770 }
44771
44772 /*
44773 ** Return the page number associated with frame iFrame in this WAL.
44774 */
44775 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44776   int iHash = walFramePage(iFrame);
44777   if( iHash==0 ){
44778     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44779   }
44780   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44781 }
44782
44783 /*
44784 ** Remove entries from the hash table that point to WAL slots greater
44785 ** than pWal->hdr.mxFrame.
44786 **
44787 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44788 ** to a rollback or savepoint.
44789 **
44790 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44791 ** updated.  Any later hash tables will be automatically cleared when
44792 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44793 ** actually needed.
44794 */
44795 static void walCleanupHash(Wal *pWal){
44796   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
44797   volatile u32 *aPgno = 0;        /* Page number array for hash table */
44798   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
44799   int iLimit = 0;                 /* Zero values greater than this */
44800   int nByte;                      /* Number of bytes to zero in aPgno[] */
44801   int i;                          /* Used to iterate through aHash[] */
44802
44803   assert( pWal->writeLock );
44804   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44805   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44806   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44807
44808   if( pWal->hdr.mxFrame==0 ) return;
44809
44810   /* Obtain pointers to the hash-table and page-number array containing 
44811   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44812   ** that the page said hash-table and array reside on is already mapped.
44813   */
44814   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44815   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44816   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44817
44818   /* Zero all hash-table entries that correspond to frame numbers greater
44819   ** than pWal->hdr.mxFrame.
44820   */
44821   iLimit = pWal->hdr.mxFrame - iZero;
44822   assert( iLimit>0 );
44823   for(i=0; i<HASHTABLE_NSLOT; i++){
44824     if( aHash[i]>iLimit ){
44825       aHash[i] = 0;
44826     }
44827   }
44828   
44829   /* Zero the entries in the aPgno array that correspond to frames with
44830   ** frame numbers greater than pWal->hdr.mxFrame. 
44831   */
44832   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44833   memset((void *)&aPgno[iLimit+1], 0, nByte);
44834
44835 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44836   /* Verify that the every entry in the mapping region is still reachable
44837   ** via the hash table even after the cleanup.
44838   */
44839   if( iLimit ){
44840     int i;           /* Loop counter */
44841     int iKey;        /* Hash key */
44842     for(i=1; i<=iLimit; i++){
44843       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44844         if( aHash[iKey]==i ) break;
44845       }
44846       assert( aHash[iKey]==i );
44847     }
44848   }
44849 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44850 }
44851
44852
44853 /*
44854 ** Set an entry in the wal-index that will map database page number
44855 ** pPage into WAL frame iFrame.
44856 */
44857 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44858   int rc;                         /* Return code */
44859   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
44860   volatile u32 *aPgno = 0;        /* Page number array */
44861   volatile ht_slot *aHash = 0;    /* Hash table */
44862
44863   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44864
44865   /* Assuming the wal-index file was successfully mapped, populate the
44866   ** page number array and hash table entry.
44867   */
44868   if( rc==SQLITE_OK ){
44869     int iKey;                     /* Hash table key */
44870     int idx;                      /* Value to write to hash-table slot */
44871     int nCollide;                 /* Number of hash collisions */
44872
44873     idx = iFrame - iZero;
44874     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44875     
44876     /* If this is the first entry to be added to this hash-table, zero the
44877     ** entire hash table and aPgno[] array before proceding. 
44878     */
44879     if( idx==1 ){
44880       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44881       memset((void*)&aPgno[1], 0, nByte);
44882     }
44883
44884     /* If the entry in aPgno[] is already set, then the previous writer
44885     ** must have exited unexpectedly in the middle of a transaction (after
44886     ** writing one or more dirty pages to the WAL to free up memory). 
44887     ** Remove the remnants of that writers uncommitted transaction from 
44888     ** the hash-table before writing any new entries.
44889     */
44890     if( aPgno[idx] ){
44891       walCleanupHash(pWal);
44892       assert( !aPgno[idx] );
44893     }
44894
44895     /* Write the aPgno[] array entry and the hash-table slot. */
44896     nCollide = idx;
44897     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44898       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44899     }
44900     aPgno[idx] = iPage;
44901     aHash[iKey] = (ht_slot)idx;
44902
44903 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44904     /* Verify that the number of entries in the hash table exactly equals
44905     ** the number of entries in the mapping region.
44906     */
44907     {
44908       int i;           /* Loop counter */
44909       int nEntry = 0;  /* Number of entries in the hash table */
44910       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44911       assert( nEntry==idx );
44912     }
44913
44914     /* Verify that the every entry in the mapping region is reachable
44915     ** via the hash table.  This turns out to be a really, really expensive
44916     ** thing to check, so only do this occasionally - not on every
44917     ** iteration.
44918     */
44919     if( (idx&0x3ff)==0 ){
44920       int i;           /* Loop counter */
44921       for(i=1; i<=idx; i++){
44922         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44923           if( aHash[iKey]==i ) break;
44924         }
44925         assert( aHash[iKey]==i );
44926       }
44927     }
44928 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44929   }
44930
44931
44932   return rc;
44933 }
44934
44935
44936 /*
44937 ** Recover the wal-index by reading the write-ahead log file. 
44938 **
44939 ** This routine first tries to establish an exclusive lock on the
44940 ** wal-index to prevent other threads/processes from doing anything
44941 ** with the WAL or wal-index while recovery is running.  The
44942 ** WAL_RECOVER_LOCK is also held so that other threads will know
44943 ** that this thread is running recovery.  If unable to establish
44944 ** the necessary locks, this routine returns SQLITE_BUSY.
44945 */
44946 static int walIndexRecover(Wal *pWal){
44947   int rc;                         /* Return Code */
44948   i64 nSize;                      /* Size of log file */
44949   u32 aFrameCksum[2] = {0, 0};
44950   int iLock;                      /* Lock offset to lock for checkpoint */
44951   int nLock;                      /* Number of locks to hold */
44952
44953   /* Obtain an exclusive lock on all byte in the locking range not already
44954   ** locked by the caller. The caller is guaranteed to have locked the
44955   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44956   ** If successful, the same bytes that are locked here are unlocked before
44957   ** this function returns.
44958   */
44959   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44960   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44961   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44962   assert( pWal->writeLock );
44963   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44964   nLock = SQLITE_SHM_NLOCK - iLock;
44965   rc = walLockExclusive(pWal, iLock, nLock);
44966   if( rc ){
44967     return rc;
44968   }
44969   WALTRACE(("WAL%p: recovery begin...\n", pWal));
44970
44971   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44972
44973   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44974   if( rc!=SQLITE_OK ){
44975     goto recovery_error;
44976   }
44977
44978   if( nSize>WAL_HDRSIZE ){
44979     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
44980     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
44981     int szFrame;                  /* Number of bytes in buffer aFrame[] */
44982     u8 *aData;                    /* Pointer to data part of aFrame buffer */
44983     int iFrame;                   /* Index of last frame read */
44984     i64 iOffset;                  /* Next offset to read from log file */
44985     int szPage;                   /* Page size according to the log */
44986     u32 magic;                    /* Magic value read from WAL header */
44987     u32 version;                  /* Magic value read from WAL header */
44988     int isValid;                  /* True if this frame is valid */
44989
44990     /* Read in the WAL header. */
44991     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44992     if( rc!=SQLITE_OK ){
44993       goto recovery_error;
44994     }
44995
44996     /* If the database page size is not a power of two, or is greater than
44997     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
44998     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44999     ** WAL file.
45000     */
45001     magic = sqlite3Get4byte(&aBuf[0]);
45002     szPage = sqlite3Get4byte(&aBuf[8]);
45003     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
45004      || szPage&(szPage-1) 
45005      || szPage>SQLITE_MAX_PAGE_SIZE 
45006      || szPage<512 
45007     ){
45008       goto finished;
45009     }
45010     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45011     pWal->szPage = szPage;
45012     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45013     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45014
45015     /* Verify that the WAL header checksum is correct */
45016     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
45017         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45018     );
45019     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45020      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45021     ){
45022       goto finished;
45023     }
45024
45025     /* Verify that the version number on the WAL format is one that
45026     ** are able to understand */
45027     version = sqlite3Get4byte(&aBuf[4]);
45028     if( version!=WAL_MAX_VERSION ){
45029       rc = SQLITE_CANTOPEN_BKPT;
45030       goto finished;
45031     }
45032
45033     /* Malloc a buffer to read frames into. */
45034     szFrame = szPage + WAL_FRAME_HDRSIZE;
45035     aFrame = (u8 *)sqlite3_malloc(szFrame);
45036     if( !aFrame ){
45037       rc = SQLITE_NOMEM;
45038       goto recovery_error;
45039     }
45040     aData = &aFrame[WAL_FRAME_HDRSIZE];
45041
45042     /* Read all frames from the log file. */
45043     iFrame = 0;
45044     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45045       u32 pgno;                   /* Database page number for frame */
45046       u32 nTruncate;              /* dbsize field from frame header */
45047
45048       /* Read and decode the next log frame. */
45049       iFrame++;
45050       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45051       if( rc!=SQLITE_OK ) break;
45052       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45053       if( !isValid ) break;
45054       rc = walIndexAppend(pWal, iFrame, pgno);
45055       if( rc!=SQLITE_OK ) break;
45056
45057       /* If nTruncate is non-zero, this is a commit record. */
45058       if( nTruncate ){
45059         pWal->hdr.mxFrame = iFrame;
45060         pWal->hdr.nPage = nTruncate;
45061         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45062         testcase( szPage<=32768 );
45063         testcase( szPage>=65536 );
45064         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45065         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45066       }
45067     }
45068
45069     sqlite3_free(aFrame);
45070   }
45071
45072 finished:
45073   if( rc==SQLITE_OK ){
45074     volatile WalCkptInfo *pInfo;
45075     int i;
45076     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45077     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45078     walIndexWriteHdr(pWal);
45079
45080     /* Reset the checkpoint-header. This is safe because this thread is 
45081     ** currently holding locks that exclude all other readers, writers and
45082     ** checkpointers.
45083     */
45084     pInfo = walCkptInfo(pWal);
45085     pInfo->nBackfill = 0;
45086     pInfo->aReadMark[0] = 0;
45087     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45088     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
45089
45090     /* If more than one frame was recovered from the log file, report an
45091     ** event via sqlite3_log(). This is to help with identifying performance
45092     ** problems caused by applications routinely shutting down without
45093     ** checkpointing the log file.
45094     */
45095     if( pWal->hdr.nPage ){
45096       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45097           pWal->hdr.nPage, pWal->zWalName
45098       );
45099     }
45100   }
45101
45102 recovery_error:
45103   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45104   walUnlockExclusive(pWal, iLock, nLock);
45105   return rc;
45106 }
45107
45108 /*
45109 ** Close an open wal-index.
45110 */
45111 static void walIndexClose(Wal *pWal, int isDelete){
45112   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45113     int i;
45114     for(i=0; i<pWal->nWiData; i++){
45115       sqlite3_free((void *)pWal->apWiData[i]);
45116       pWal->apWiData[i] = 0;
45117     }
45118   }else{
45119     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45120   }
45121 }
45122
45123 /* 
45124 ** Open a connection to the WAL file zWalName. The database file must 
45125 ** already be opened on connection pDbFd. The buffer that zWalName points
45126 ** to must remain valid for the lifetime of the returned Wal* handle.
45127 **
45128 ** A SHARED lock should be held on the database file when this function
45129 ** is called. The purpose of this SHARED lock is to prevent any other
45130 ** client from unlinking the WAL or wal-index file. If another process
45131 ** were to do this just after this client opened one of these files, the
45132 ** system would be badly broken.
45133 **
45134 ** If the log file is successfully opened, SQLITE_OK is returned and 
45135 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45136 ** an SQLite error code is returned and *ppWal is left unmodified.
45137 */
45138 SQLITE_PRIVATE int sqlite3WalOpen(
45139   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
45140   sqlite3_file *pDbFd,            /* The open database file */
45141   const char *zWalName,           /* Name of the WAL file */
45142   int bNoShm,                     /* True to run in heap-memory mode */
45143   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
45144   Wal **ppWal                     /* OUT: Allocated Wal handle */
45145 ){
45146   int rc;                         /* Return Code */
45147   Wal *pRet;                      /* Object to allocate and return */
45148   int flags;                      /* Flags passed to OsOpen() */
45149
45150   assert( zWalName && zWalName[0] );
45151   assert( pDbFd );
45152
45153   /* In the amalgamation, the os_unix.c and os_win.c source files come before
45154   ** this source file.  Verify that the #defines of the locking byte offsets
45155   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45156   */
45157 #ifdef WIN_SHM_BASE
45158   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45159 #endif
45160 #ifdef UNIX_SHM_BASE
45161   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45162 #endif
45163
45164
45165   /* Allocate an instance of struct Wal to return. */
45166   *ppWal = 0;
45167   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45168   if( !pRet ){
45169     return SQLITE_NOMEM;
45170   }
45171
45172   pRet->pVfs = pVfs;
45173   pRet->pWalFd = (sqlite3_file *)&pRet[1];
45174   pRet->pDbFd = pDbFd;
45175   pRet->readLock = -1;
45176   pRet->mxWalSize = mxWalSize;
45177   pRet->zWalName = zWalName;
45178   pRet->syncHeader = 1;
45179   pRet->padToSectorBoundary = 1;
45180   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45181
45182   /* Open file handle on the write-ahead log file. */
45183   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45184   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45185   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45186     pRet->readOnly = WAL_RDONLY;
45187   }
45188
45189   if( rc!=SQLITE_OK ){
45190     walIndexClose(pRet, 0);
45191     sqlite3OsClose(pRet->pWalFd);
45192     sqlite3_free(pRet);
45193   }else{
45194     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
45195     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
45196     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
45197       pRet->padToSectorBoundary = 0;
45198     }
45199     *ppWal = pRet;
45200     WALTRACE(("WAL%d: opened\n", pRet));
45201   }
45202   return rc;
45203 }
45204
45205 /*
45206 ** Change the size to which the WAL file is trucated on each reset.
45207 */
45208 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45209   if( pWal ) pWal->mxWalSize = iLimit;
45210 }
45211
45212 /*
45213 ** Find the smallest page number out of all pages held in the WAL that
45214 ** has not been returned by any prior invocation of this method on the
45215 ** same WalIterator object.   Write into *piFrame the frame index where
45216 ** that page was last written into the WAL.  Write into *piPage the page
45217 ** number.
45218 **
45219 ** Return 0 on success.  If there are no pages in the WAL with a page
45220 ** number larger than *piPage, then return 1.
45221 */
45222 static int walIteratorNext(
45223   WalIterator *p,               /* Iterator */
45224   u32 *piPage,                  /* OUT: The page number of the next page */
45225   u32 *piFrame                  /* OUT: Wal frame index of next page */
45226 ){
45227   u32 iMin;                     /* Result pgno must be greater than iMin */
45228   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
45229   int i;                        /* For looping through segments */
45230
45231   iMin = p->iPrior;
45232   assert( iMin<0xffffffff );
45233   for(i=p->nSegment-1; i>=0; i--){
45234     struct WalSegment *pSegment = &p->aSegment[i];
45235     while( pSegment->iNext<pSegment->nEntry ){
45236       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45237       if( iPg>iMin ){
45238         if( iPg<iRet ){
45239           iRet = iPg;
45240           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45241         }
45242         break;
45243       }
45244       pSegment->iNext++;
45245     }
45246   }
45247
45248   *piPage = p->iPrior = iRet;
45249   return (iRet==0xFFFFFFFF);
45250 }
45251
45252 /*
45253 ** This function merges two sorted lists into a single sorted list.
45254 **
45255 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
45256 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
45257 ** is guaranteed for all J<K:
45258 **
45259 **        aContent[aLeft[J]] < aContent[aLeft[K]]
45260 **        aContent[aRight[J]] < aContent[aRight[K]]
45261 **
45262 ** This routine overwrites aRight[] with a new (probably longer) sequence
45263 ** of indices such that the aRight[] contains every index that appears in
45264 ** either aLeft[] or the old aRight[] and such that the second condition
45265 ** above is still met.
45266 **
45267 ** The aContent[aLeft[X]] values will be unique for all X.  And the
45268 ** aContent[aRight[X]] values will be unique too.  But there might be
45269 ** one or more combinations of X and Y such that
45270 **
45271 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
45272 **
45273 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45274 */
45275 static void walMerge(
45276   const u32 *aContent,            /* Pages in wal - keys for the sort */
45277   ht_slot *aLeft,                 /* IN: Left hand input list */
45278   int nLeft,                      /* IN: Elements in array *paLeft */
45279   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45280   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45281   ht_slot *aTmp                   /* Temporary buffer */
45282 ){
45283   int iLeft = 0;                  /* Current index in aLeft */
45284   int iRight = 0;                 /* Current index in aRight */
45285   int iOut = 0;                   /* Current index in output buffer */
45286   int nRight = *pnRight;
45287   ht_slot *aRight = *paRight;
45288
45289   assert( nLeft>0 && nRight>0 );
45290   while( iRight<nRight || iLeft<nLeft ){
45291     ht_slot logpage;
45292     Pgno dbpage;
45293
45294     if( (iLeft<nLeft) 
45295      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45296     ){
45297       logpage = aLeft[iLeft++];
45298     }else{
45299       logpage = aRight[iRight++];
45300     }
45301     dbpage = aContent[logpage];
45302
45303     aTmp[iOut++] = logpage;
45304     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45305
45306     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45307     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45308   }
45309
45310   *paRight = aLeft;
45311   *pnRight = iOut;
45312   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45313 }
45314
45315 /*
45316 ** Sort the elements in list aList using aContent[] as the sort key.
45317 ** Remove elements with duplicate keys, preferring to keep the
45318 ** larger aList[] values.
45319 **
45320 ** The aList[] entries are indices into aContent[].  The values in
45321 ** aList[] are to be sorted so that for all J<K:
45322 **
45323 **      aContent[aList[J]] < aContent[aList[K]]
45324 **
45325 ** For any X and Y such that
45326 **
45327 **      aContent[aList[X]] == aContent[aList[Y]]
45328 **
45329 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45330 ** the smaller.
45331 */
45332 static void walMergesort(
45333   const u32 *aContent,            /* Pages in wal */
45334   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45335   ht_slot *aList,                 /* IN/OUT: List to sort */
45336   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45337 ){
45338   struct Sublist {
45339     int nList;                    /* Number of elements in aList */
45340     ht_slot *aList;               /* Pointer to sub-list content */
45341   };
45342
45343   const int nList = *pnList;      /* Size of input list */
45344   int nMerge = 0;                 /* Number of elements in list aMerge */
45345   ht_slot *aMerge = 0;            /* List to be merged */
45346   int iList;                      /* Index into input list */
45347   int iSub = 0;                   /* Index into aSub array */
45348   struct Sublist aSub[13];        /* Array of sub-lists */
45349
45350   memset(aSub, 0, sizeof(aSub));
45351   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45352   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45353
45354   for(iList=0; iList<nList; iList++){
45355     nMerge = 1;
45356     aMerge = &aList[iList];
45357     for(iSub=0; iList & (1<<iSub); iSub++){
45358       struct Sublist *p = &aSub[iSub];
45359       assert( p->aList && p->nList<=(1<<iSub) );
45360       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45361       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45362     }
45363     aSub[iSub].aList = aMerge;
45364     aSub[iSub].nList = nMerge;
45365   }
45366
45367   for(iSub++; iSub<ArraySize(aSub); iSub++){
45368     if( nList & (1<<iSub) ){
45369       struct Sublist *p = &aSub[iSub];
45370       assert( p->nList<=(1<<iSub) );
45371       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45372       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45373     }
45374   }
45375   assert( aMerge==aList );
45376   *pnList = nMerge;
45377
45378 #ifdef SQLITE_DEBUG
45379   {
45380     int i;
45381     for(i=1; i<*pnList; i++){
45382       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45383     }
45384   }
45385 #endif
45386 }
45387
45388 /* 
45389 ** Free an iterator allocated by walIteratorInit().
45390 */
45391 static void walIteratorFree(WalIterator *p){
45392   sqlite3ScratchFree(p);
45393 }
45394
45395 /*
45396 ** Construct a WalInterator object that can be used to loop over all 
45397 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45398 ** lock.
45399 **
45400 ** On success, make *pp point to the newly allocated WalInterator object
45401 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45402 ** returns an error, the value of *pp is undefined.
45403 **
45404 ** The calling routine should invoke walIteratorFree() to destroy the
45405 ** WalIterator object when it has finished with it.
45406 */
45407 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45408   WalIterator *p;                 /* Return value */
45409   int nSegment;                   /* Number of segments to merge */
45410   u32 iLast;                      /* Last frame in log */
45411   int nByte;                      /* Number of bytes to allocate */
45412   int i;                          /* Iterator variable */
45413   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45414   int rc = SQLITE_OK;             /* Return Code */
45415
45416   /* This routine only runs while holding the checkpoint lock. And
45417   ** it only runs if there is actually content in the log (mxFrame>0).
45418   */
45419   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45420   iLast = pWal->hdr.mxFrame;
45421
45422   /* Allocate space for the WalIterator object. */
45423   nSegment = walFramePage(iLast) + 1;
45424   nByte = sizeof(WalIterator) 
45425         + (nSegment-1)*sizeof(struct WalSegment)
45426         + iLast*sizeof(ht_slot);
45427   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45428   if( !p ){
45429     return SQLITE_NOMEM;
45430   }
45431   memset(p, 0, nByte);
45432   p->nSegment = nSegment;
45433
45434   /* Allocate temporary space used by the merge-sort routine. This block
45435   ** of memory will be freed before this function returns.
45436   */
45437   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45438       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45439   );
45440   if( !aTmp ){
45441     rc = SQLITE_NOMEM;
45442   }
45443
45444   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45445     volatile ht_slot *aHash;
45446     u32 iZero;
45447     volatile u32 *aPgno;
45448
45449     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45450     if( rc==SQLITE_OK ){
45451       int j;                      /* Counter variable */
45452       int nEntry;                 /* Number of entries in this segment */
45453       ht_slot *aIndex;            /* Sorted index for this segment */
45454
45455       aPgno++;
45456       if( (i+1)==nSegment ){
45457         nEntry = (int)(iLast - iZero);
45458       }else{
45459         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45460       }
45461       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45462       iZero++;
45463   
45464       for(j=0; j<nEntry; j++){
45465         aIndex[j] = (ht_slot)j;
45466       }
45467       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45468       p->aSegment[i].iZero = iZero;
45469       p->aSegment[i].nEntry = nEntry;
45470       p->aSegment[i].aIndex = aIndex;
45471       p->aSegment[i].aPgno = (u32 *)aPgno;
45472     }
45473   }
45474   sqlite3ScratchFree(aTmp);
45475
45476   if( rc!=SQLITE_OK ){
45477     walIteratorFree(p);
45478   }
45479   *pp = p;
45480   return rc;
45481 }
45482
45483 /*
45484 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45485 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45486 ** busy-handler function. Invoke it and retry the lock until either the
45487 ** lock is successfully obtained or the busy-handler returns 0.
45488 */
45489 static int walBusyLock(
45490   Wal *pWal,                      /* WAL connection */
45491   int (*xBusy)(void*),            /* Function to call when busy */
45492   void *pBusyArg,                 /* Context argument for xBusyHandler */
45493   int lockIdx,                    /* Offset of first byte to lock */
45494   int n                           /* Number of bytes to lock */
45495 ){
45496   int rc;
45497   do {
45498     rc = walLockExclusive(pWal, lockIdx, n);
45499   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45500   return rc;
45501 }
45502
45503 /*
45504 ** The cache of the wal-index header must be valid to call this function.
45505 ** Return the page-size in bytes used by the database.
45506 */
45507 static int walPagesize(Wal *pWal){
45508   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45509 }
45510
45511 /*
45512 ** Copy as much content as we can from the WAL back into the database file
45513 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45514 **
45515 ** The amount of information copies from WAL to database might be limited
45516 ** by active readers.  This routine will never overwrite a database page
45517 ** that a concurrent reader might be using.
45518 **
45519 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45520 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
45521 ** checkpoints are always run by a background thread or background 
45522 ** process, foreground threads will never block on a lengthy fsync call.
45523 **
45524 ** Fsync is called on the WAL before writing content out of the WAL and
45525 ** into the database.  This ensures that if the new content is persistent
45526 ** in the WAL and can be recovered following a power-loss or hard reset.
45527 **
45528 ** Fsync is also called on the database file if (and only if) the entire
45529 ** WAL content is copied into the database file.  This second fsync makes
45530 ** it safe to delete the WAL since the new content will persist in the
45531 ** database file.
45532 **
45533 ** This routine uses and updates the nBackfill field of the wal-index header.
45534 ** This is the only routine tha will increase the value of nBackfill.  
45535 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45536 ** its value.)
45537 **
45538 ** The caller must be holding sufficient locks to ensure that no other
45539 ** checkpoint is running (in any other thread or process) at the same
45540 ** time.
45541 */
45542 static int walCheckpoint(
45543   Wal *pWal,                      /* Wal connection */
45544   int eMode,                      /* One of PASSIVE, FULL or RESTART */
45545   int (*xBusyCall)(void*),        /* Function to call when busy */
45546   void *pBusyArg,                 /* Context argument for xBusyHandler */
45547   int sync_flags,                 /* Flags for OsSync() (or 0) */
45548   u8 *zBuf                        /* Temporary buffer to use */
45549 ){
45550   int rc;                         /* Return code */
45551   int szPage;                     /* Database page-size */
45552   WalIterator *pIter = 0;         /* Wal iterator context */
45553   u32 iDbpage = 0;                /* Next database page to write */
45554   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
45555   u32 mxSafeFrame;                /* Max frame that can be backfilled */
45556   u32 mxPage;                     /* Max database page to write */
45557   int i;                          /* Loop counter */
45558   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
45559   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
45560
45561   szPage = walPagesize(pWal);
45562   testcase( szPage<=32768 );
45563   testcase( szPage>=65536 );
45564   pInfo = walCkptInfo(pWal);
45565   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45566
45567   /* Allocate the iterator */
45568   rc = walIteratorInit(pWal, &pIter);
45569   if( rc!=SQLITE_OK ){
45570     return rc;
45571   }
45572   assert( pIter );
45573
45574   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45575
45576   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45577   ** safe to write into the database.  Frames beyond mxSafeFrame might
45578   ** overwrite database pages that are in use by active readers and thus
45579   ** cannot be backfilled from the WAL.
45580   */
45581   mxSafeFrame = pWal->hdr.mxFrame;
45582   mxPage = pWal->hdr.nPage;
45583   for(i=1; i<WAL_NREADER; i++){
45584     u32 y = pInfo->aReadMark[i];
45585     if( mxSafeFrame>y ){
45586       assert( y<=pWal->hdr.mxFrame );
45587       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45588       if( rc==SQLITE_OK ){
45589         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
45590         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45591       }else if( rc==SQLITE_BUSY ){
45592         mxSafeFrame = y;
45593         xBusy = 0;
45594       }else{
45595         goto walcheckpoint_out;
45596       }
45597     }
45598   }
45599
45600   if( pInfo->nBackfill<mxSafeFrame
45601    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45602   ){
45603     i64 nSize;                    /* Current size of database file */
45604     u32 nBackfill = pInfo->nBackfill;
45605
45606     /* Sync the WAL to disk */
45607     if( sync_flags ){
45608       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45609     }
45610
45611     /* If the database file may grow as a result of this checkpoint, hint
45612     ** about the eventual size of the db file to the VFS layer. 
45613     */
45614     if( rc==SQLITE_OK ){
45615       i64 nReq = ((i64)mxPage * szPage);
45616       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
45617       if( rc==SQLITE_OK && nSize<nReq ){
45618         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
45619       }
45620     }
45621
45622     /* Iterate through the contents of the WAL, copying data to the db file. */
45623     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
45624       i64 iOffset;
45625       assert( walFramePgno(pWal, iFrame)==iDbpage );
45626       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
45627       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
45628       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
45629       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
45630       if( rc!=SQLITE_OK ) break;
45631       iOffset = (iDbpage-1)*(i64)szPage;
45632       testcase( IS_BIG_INT(iOffset) );
45633       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
45634       if( rc!=SQLITE_OK ) break;
45635     }
45636
45637     /* If work was actually accomplished... */
45638     if( rc==SQLITE_OK ){
45639       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
45640         i64 szDb = pWal->hdr.nPage*(i64)szPage;
45641         testcase( IS_BIG_INT(szDb) );
45642         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45643         if( rc==SQLITE_OK && sync_flags ){
45644           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45645         }
45646       }
45647       if( rc==SQLITE_OK ){
45648         pInfo->nBackfill = mxSafeFrame;
45649       }
45650     }
45651
45652     /* Release the reader lock held while backfilling */
45653     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45654   }
45655
45656   if( rc==SQLITE_BUSY ){
45657     /* Reset the return code so as not to report a checkpoint failure
45658     ** just because there are active readers.  */
45659     rc = SQLITE_OK;
45660   }
45661
45662   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45663   ** file has been copied into the database file, then block until all
45664   ** readers have finished using the wal file. This ensures that the next
45665   ** process to write to the database restarts the wal file.
45666   */
45667   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45668     assert( pWal->writeLock );
45669     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45670       rc = SQLITE_BUSY;
45671     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45672       assert( mxSafeFrame==pWal->hdr.mxFrame );
45673       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45674       if( rc==SQLITE_OK ){
45675         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45676       }
45677     }
45678   }
45679
45680  walcheckpoint_out:
45681   walIteratorFree(pIter);
45682   return rc;
45683 }
45684
45685 /*
45686 ** If the WAL file is currently larger than nMax bytes in size, truncate
45687 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
45688 */
45689 static void walLimitSize(Wal *pWal, i64 nMax){
45690   i64 sz;
45691   int rx;
45692   sqlite3BeginBenignMalloc();
45693   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
45694   if( rx==SQLITE_OK && (sz > nMax ) ){
45695     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
45696   }
45697   sqlite3EndBenignMalloc();
45698   if( rx ){
45699     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
45700   }
45701 }
45702
45703 /*
45704 ** Close a connection to a log file.
45705 */
45706 SQLITE_PRIVATE int sqlite3WalClose(
45707   Wal *pWal,                      /* Wal to close */
45708   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
45709   int nBuf,
45710   u8 *zBuf                        /* Buffer of at least nBuf bytes */
45711 ){
45712   int rc = SQLITE_OK;
45713   if( pWal ){
45714     int isDelete = 0;             /* True to unlink wal and wal-index files */
45715
45716     /* If an EXCLUSIVE lock can be obtained on the database file (using the
45717     ** ordinary, rollback-mode locking methods, this guarantees that the
45718     ** connection associated with this log file is the only connection to
45719     ** the database. In this case checkpoint the database and unlink both
45720     ** the wal and wal-index files.
45721     **
45722     ** The EXCLUSIVE lock is not released before returning.
45723     */
45724     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45725     if( rc==SQLITE_OK ){
45726       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45727         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45728       }
45729       rc = sqlite3WalCheckpoint(
45730           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
45731       );
45732       if( rc==SQLITE_OK ){
45733         int bPersist = -1;
45734         sqlite3OsFileControlHint(
45735             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
45736         );
45737         if( bPersist!=1 ){
45738           /* Try to delete the WAL file if the checkpoint completed and
45739           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
45740           ** mode (!bPersist) */
45741           isDelete = 1;
45742         }else if( pWal->mxWalSize>=0 ){
45743           /* Try to truncate the WAL file to zero bytes if the checkpoint
45744           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
45745           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
45746           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
45747           ** to zero bytes as truncating to the journal_size_limit might
45748           ** leave a corrupt WAL file on disk. */
45749           walLimitSize(pWal, 0);
45750         }
45751       }
45752     }
45753
45754     walIndexClose(pWal, isDelete);
45755     sqlite3OsClose(pWal->pWalFd);
45756     if( isDelete ){
45757       sqlite3BeginBenignMalloc();
45758       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
45759       sqlite3EndBenignMalloc();
45760     }
45761     WALTRACE(("WAL%p: closed\n", pWal));
45762     sqlite3_free((void *)pWal->apWiData);
45763     sqlite3_free(pWal);
45764   }
45765   return rc;
45766 }
45767
45768 /*
45769 ** Try to read the wal-index header.  Return 0 on success and 1 if
45770 ** there is a problem.
45771 **
45772 ** The wal-index is in shared memory.  Another thread or process might
45773 ** be writing the header at the same time this procedure is trying to
45774 ** read it, which might result in inconsistency.  A dirty read is detected
45775 ** by verifying that both copies of the header are the same and also by
45776 ** a checksum on the header.
45777 **
45778 ** If and only if the read is consistent and the header is different from
45779 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
45780 ** and *pChanged is set to 1.
45781 **
45782 ** If the checksum cannot be verified return non-zero. If the header
45783 ** is read successfully and the checksum verified, return zero.
45784 */
45785 static int walIndexTryHdr(Wal *pWal, int *pChanged){
45786   u32 aCksum[2];                  /* Checksum on the header content */
45787   WalIndexHdr h1, h2;             /* Two copies of the header content */
45788   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
45789
45790   /* The first page of the wal-index must be mapped at this point. */
45791   assert( pWal->nWiData>0 && pWal->apWiData[0] );
45792
45793   /* Read the header. This might happen concurrently with a write to the
45794   ** same area of shared memory on a different CPU in a SMP,
45795   ** meaning it is possible that an inconsistent snapshot is read
45796   ** from the file. If this happens, return non-zero.
45797   **
45798   ** There are two copies of the header at the beginning of the wal-index.
45799   ** When reading, read [0] first then [1].  Writes are in the reverse order.
45800   ** Memory barriers are used to prevent the compiler or the hardware from
45801   ** reordering the reads and writes.
45802   */
45803   aHdr = walIndexHdr(pWal);
45804   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45805   walShmBarrier(pWal);
45806   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45807
45808   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45809     return 1;   /* Dirty read */
45810   }  
45811   if( h1.isInit==0 ){
45812     return 1;   /* Malformed header - probably all zeros */
45813   }
45814   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45815   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45816     return 1;   /* Checksum does not match */
45817   }
45818
45819   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45820     *pChanged = 1;
45821     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45822     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45823     testcase( pWal->szPage<=32768 );
45824     testcase( pWal->szPage>=65536 );
45825   }
45826
45827   /* The header was successfully read. Return zero. */
45828   return 0;
45829 }
45830
45831 /*
45832 ** Read the wal-index header from the wal-index and into pWal->hdr.
45833 ** If the wal-header appears to be corrupt, try to reconstruct the
45834 ** wal-index from the WAL before returning.
45835 **
45836 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45837 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
45838 ** to 0.
45839 **
45840 ** If the wal-index header is successfully read, return SQLITE_OK. 
45841 ** Otherwise an SQLite error code.
45842 */
45843 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45844   int rc;                         /* Return code */
45845   int badHdr;                     /* True if a header read failed */
45846   volatile u32 *page0;            /* Chunk of wal-index containing header */
45847
45848   /* Ensure that page 0 of the wal-index (the page that contains the 
45849   ** wal-index header) is mapped. Return early if an error occurs here.
45850   */
45851   assert( pChanged );
45852   rc = walIndexPage(pWal, 0, &page0);
45853   if( rc!=SQLITE_OK ){
45854     return rc;
45855   };
45856   assert( page0 || pWal->writeLock==0 );
45857
45858   /* If the first page of the wal-index has been mapped, try to read the
45859   ** wal-index header immediately, without holding any lock. This usually
45860   ** works, but may fail if the wal-index header is corrupt or currently 
45861   ** being modified by another thread or process.
45862   */
45863   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45864
45865   /* If the first attempt failed, it might have been due to a race
45866   ** with a writer.  So get a WRITE lock and try again.
45867   */
45868   assert( badHdr==0 || pWal->writeLock==0 );
45869   if( badHdr ){
45870     if( pWal->readOnly & WAL_SHM_RDONLY ){
45871       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
45872         walUnlockShared(pWal, WAL_WRITE_LOCK);
45873         rc = SQLITE_READONLY_RECOVERY;
45874       }
45875     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45876       pWal->writeLock = 1;
45877       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45878         badHdr = walIndexTryHdr(pWal, pChanged);
45879         if( badHdr ){
45880           /* If the wal-index header is still malformed even while holding
45881           ** a WRITE lock, it can only mean that the header is corrupted and
45882           ** needs to be reconstructed.  So run recovery to do exactly that.
45883           */
45884           rc = walIndexRecover(pWal);
45885           *pChanged = 1;
45886         }
45887       }
45888       pWal->writeLock = 0;
45889       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45890     }
45891   }
45892
45893   /* If the header is read successfully, check the version number to make
45894   ** sure the wal-index was not constructed with some future format that
45895   ** this version of SQLite cannot understand.
45896   */
45897   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45898     rc = SQLITE_CANTOPEN_BKPT;
45899   }
45900
45901   return rc;
45902 }
45903
45904 /*
45905 ** This is the value that walTryBeginRead returns when it needs to
45906 ** be retried.
45907 */
45908 #define WAL_RETRY  (-1)
45909
45910 /*
45911 ** Attempt to start a read transaction.  This might fail due to a race or
45912 ** other transient condition.  When that happens, it returns WAL_RETRY to
45913 ** indicate to the caller that it is safe to retry immediately.
45914 **
45915 ** On success return SQLITE_OK.  On a permanent failure (such an
45916 ** I/O error or an SQLITE_BUSY because another process is running
45917 ** recovery) return a positive error code.
45918 **
45919 ** The useWal parameter is true to force the use of the WAL and disable
45920 ** the case where the WAL is bypassed because it has been completely
45921 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
45922 ** to make a copy of the wal-index header into pWal->hdr.  If the 
45923 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
45924 ** to the caller that the local paget cache is obsolete and needs to be 
45925 ** flushed.)  When useWal==1, the wal-index header is assumed to already
45926 ** be loaded and the pChanged parameter is unused.
45927 **
45928 ** The caller must set the cnt parameter to the number of prior calls to
45929 ** this routine during the current read attempt that returned WAL_RETRY.
45930 ** This routine will start taking more aggressive measures to clear the
45931 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45932 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
45933 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45934 ** and is not honoring the locking protocol.  There is a vanishingly small
45935 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45936 ** bad luck when there is lots of contention for the wal-index, but that
45937 ** possibility is so small that it can be safely neglected, we believe.
45938 **
45939 ** On success, this routine obtains a read lock on 
45940 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
45941 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
45942 ** that means the Wal does not hold any read lock.  The reader must not
45943 ** access any database page that is modified by a WAL frame up to and
45944 ** including frame number aReadMark[pWal->readLock].  The reader will
45945 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45946 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45947 ** completely and get all content directly from the database file.
45948 ** If the useWal parameter is 1 then the WAL will never be ignored and
45949 ** this routine will always set pWal->readLock>0 on success.
45950 ** When the read transaction is completed, the caller must release the
45951 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45952 **
45953 ** This routine uses the nBackfill and aReadMark[] fields of the header
45954 ** to select a particular WAL_READ_LOCK() that strives to let the
45955 ** checkpoint process do as much work as possible.  This routine might
45956 ** update values of the aReadMark[] array in the header, but if it does
45957 ** so it takes care to hold an exclusive lock on the corresponding
45958 ** WAL_READ_LOCK() while changing values.
45959 */
45960 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45961   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
45962   u32 mxReadMark;                 /* Largest aReadMark[] value */
45963   int mxI;                        /* Index of largest aReadMark[] value */
45964   int i;                          /* Loop counter */
45965   int rc = SQLITE_OK;             /* Return code  */
45966
45967   assert( pWal->readLock<0 );     /* Not currently locked */
45968
45969   /* Take steps to avoid spinning forever if there is a protocol error.
45970   **
45971   ** Circumstances that cause a RETRY should only last for the briefest
45972   ** instances of time.  No I/O or other system calls are done while the
45973   ** locks are held, so the locks should not be held for very long. But 
45974   ** if we are unlucky, another process that is holding a lock might get
45975   ** paged out or take a page-fault that is time-consuming to resolve, 
45976   ** during the few nanoseconds that it is holding the lock.  In that case,
45977   ** it might take longer than normal for the lock to free.
45978   **
45979   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
45980   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
45981   ** is more of a scheduler yield than an actual delay.  But on the 10th
45982   ** an subsequent retries, the delays start becoming longer and longer, 
45983   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45984   ** The total delay time before giving up is less than 1 second.
45985   */
45986   if( cnt>5 ){
45987     int nDelay = 1;                      /* Pause time in microseconds */
45988     if( cnt>100 ){
45989       VVA_ONLY( pWal->lockError = 1; )
45990       return SQLITE_PROTOCOL;
45991     }
45992     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
45993     sqlite3OsSleep(pWal->pVfs, nDelay);
45994   }
45995
45996   if( !useWal ){
45997     rc = walIndexReadHdr(pWal, pChanged);
45998     if( rc==SQLITE_BUSY ){
45999       /* If there is not a recovery running in another thread or process
46000       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
46001       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
46002       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46003       ** would be technically correct.  But the race is benign since with
46004       ** WAL_RETRY this routine will be called again and will probably be
46005       ** right on the second iteration.
46006       */
46007       if( pWal->apWiData[0]==0 ){
46008         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46009         ** We assume this is a transient condition, so return WAL_RETRY. The
46010         ** xShmMap() implementation used by the default unix and win32 VFS 
46011         ** modules may return SQLITE_BUSY due to a race condition in the 
46012         ** code that determines whether or not the shared-memory region 
46013         ** must be zeroed before the requested page is returned.
46014         */
46015         rc = WAL_RETRY;
46016       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46017         walUnlockShared(pWal, WAL_RECOVER_LOCK);
46018         rc = WAL_RETRY;
46019       }else if( rc==SQLITE_BUSY ){
46020         rc = SQLITE_BUSY_RECOVERY;
46021       }
46022     }
46023     if( rc!=SQLITE_OK ){
46024       return rc;
46025     }
46026   }
46027
46028   pInfo = walCkptInfo(pWal);
46029   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46030     /* The WAL has been completely backfilled (or it is empty).
46031     ** and can be safely ignored.
46032     */
46033     rc = walLockShared(pWal, WAL_READ_LOCK(0));
46034     walShmBarrier(pWal);
46035     if( rc==SQLITE_OK ){
46036       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46037         /* It is not safe to allow the reader to continue here if frames
46038         ** may have been appended to the log before READ_LOCK(0) was obtained.
46039         ** When holding READ_LOCK(0), the reader ignores the entire log file,
46040         ** which implies that the database file contains a trustworthy
46041         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46042         ** happening, this is usually correct.
46043         **
46044         ** However, if frames have been appended to the log (or if the log 
46045         ** is wrapped and written for that matter) before the READ_LOCK(0)
46046         ** is obtained, that is not necessarily true. A checkpointer may
46047         ** have started to backfill the appended frames but crashed before
46048         ** it finished. Leaving a corrupt image in the database file.
46049         */
46050         walUnlockShared(pWal, WAL_READ_LOCK(0));
46051         return WAL_RETRY;
46052       }
46053       pWal->readLock = 0;
46054       return SQLITE_OK;
46055     }else if( rc!=SQLITE_BUSY ){
46056       return rc;
46057     }
46058   }
46059
46060   /* If we get this far, it means that the reader will want to use
46061   ** the WAL to get at content from recent commits.  The job now is
46062   ** to select one of the aReadMark[] entries that is closest to
46063   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46064   */
46065   mxReadMark = 0;
46066   mxI = 0;
46067   for(i=1; i<WAL_NREADER; i++){
46068     u32 thisMark = pInfo->aReadMark[i];
46069     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46070       assert( thisMark!=READMARK_NOT_USED );
46071       mxReadMark = thisMark;
46072       mxI = i;
46073     }
46074   }
46075   /* There was once an "if" here. The extra "{" is to preserve indentation. */
46076   {
46077     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46078      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46079     ){
46080       for(i=1; i<WAL_NREADER; i++){
46081         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46082         if( rc==SQLITE_OK ){
46083           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46084           mxI = i;
46085           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46086           break;
46087         }else if( rc!=SQLITE_BUSY ){
46088           return rc;
46089         }
46090       }
46091     }
46092     if( mxI==0 ){
46093       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46094       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46095     }
46096
46097     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46098     if( rc ){
46099       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46100     }
46101     /* Now that the read-lock has been obtained, check that neither the
46102     ** value in the aReadMark[] array or the contents of the wal-index
46103     ** header have changed.
46104     **
46105     ** It is necessary to check that the wal-index header did not change
46106     ** between the time it was read and when the shared-lock was obtained
46107     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46108     ** that the log file may have been wrapped by a writer, or that frames
46109     ** that occur later in the log than pWal->hdr.mxFrame may have been
46110     ** copied into the database by a checkpointer. If either of these things
46111     ** happened, then reading the database with the current value of
46112     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46113     ** instead.
46114     **
46115     ** This does not guarantee that the copy of the wal-index header is up to
46116     ** date before proceeding. That would not be possible without somehow
46117     ** blocking writers. It only guarantees that a dangerous checkpoint or 
46118     ** log-wrap (either of which would require an exclusive lock on
46119     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46120     */
46121     walShmBarrier(pWal);
46122     if( pInfo->aReadMark[mxI]!=mxReadMark
46123      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46124     ){
46125       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46126       return WAL_RETRY;
46127     }else{
46128       assert( mxReadMark<=pWal->hdr.mxFrame );
46129       pWal->readLock = (i16)mxI;
46130     }
46131   }
46132   return rc;
46133 }
46134
46135 /*
46136 ** Begin a read transaction on the database.
46137 **
46138 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46139 ** it takes a snapshot of the state of the WAL and wal-index for the current
46140 ** instant in time.  The current thread will continue to use this snapshot.
46141 ** Other threads might append new content to the WAL and wal-index but
46142 ** that extra content is ignored by the current thread.
46143 **
46144 ** If the database contents have changes since the previous read
46145 ** transaction, then *pChanged is set to 1 before returning.  The
46146 ** Pager layer will use this to know that is cache is stale and
46147 ** needs to be flushed.
46148 */
46149 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46150   int rc;                         /* Return code */
46151   int cnt = 0;                    /* Number of TryBeginRead attempts */
46152
46153   do{
46154     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46155   }while( rc==WAL_RETRY );
46156   testcase( (rc&0xff)==SQLITE_BUSY );
46157   testcase( (rc&0xff)==SQLITE_IOERR );
46158   testcase( rc==SQLITE_PROTOCOL );
46159   testcase( rc==SQLITE_OK );
46160   return rc;
46161 }
46162
46163 /*
46164 ** Finish with a read transaction.  All this does is release the
46165 ** read-lock.
46166 */
46167 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46168   sqlite3WalEndWriteTransaction(pWal);
46169   if( pWal->readLock>=0 ){
46170     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46171     pWal->readLock = -1;
46172   }
46173 }
46174
46175 /*
46176 ** Read a page from the WAL, if it is present in the WAL and if the 
46177 ** current read transaction is configured to use the WAL.  
46178 **
46179 ** The *pInWal is set to 1 if the requested page is in the WAL and
46180 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
46181 ** the WAL and needs to be read out of the database.
46182 */
46183 SQLITE_PRIVATE int sqlite3WalRead(
46184   Wal *pWal,                      /* WAL handle */
46185   Pgno pgno,                      /* Database page number to read data for */
46186   int *pInWal,                    /* OUT: True if data is read from WAL */
46187   int nOut,                       /* Size of buffer pOut in bytes */
46188   u8 *pOut                        /* Buffer to write page data to */
46189 ){
46190   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
46191   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
46192   int iHash;                      /* Used to loop through N hash tables */
46193
46194   /* This routine is only be called from within a read transaction. */
46195   assert( pWal->readLock>=0 || pWal->lockError );
46196
46197   /* If the "last page" field of the wal-index header snapshot is 0, then
46198   ** no data will be read from the wal under any circumstances. Return early
46199   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
46200   ** then the WAL is ignored by the reader so return early, as if the 
46201   ** WAL were empty.
46202   */
46203   if( iLast==0 || pWal->readLock==0 ){
46204     *pInWal = 0;
46205     return SQLITE_OK;
46206   }
46207
46208   /* Search the hash table or tables for an entry matching page number
46209   ** pgno. Each iteration of the following for() loop searches one
46210   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46211   **
46212   ** This code might run concurrently to the code in walIndexAppend()
46213   ** that adds entries to the wal-index (and possibly to this hash 
46214   ** table). This means the value just read from the hash 
46215   ** slot (aHash[iKey]) may have been added before or after the 
46216   ** current read transaction was opened. Values added after the
46217   ** read transaction was opened may have been written incorrectly -
46218   ** i.e. these slots may contain garbage data. However, we assume
46219   ** that any slots written before the current read transaction was
46220   ** opened remain unmodified.
46221   **
46222   ** For the reasons above, the if(...) condition featured in the inner
46223   ** loop of the following block is more stringent that would be required 
46224   ** if we had exclusive access to the hash-table:
46225   **
46226   **   (aPgno[iFrame]==pgno): 
46227   **     This condition filters out normal hash-table collisions.
46228   **
46229   **   (iFrame<=iLast): 
46230   **     This condition filters out entries that were added to the hash
46231   **     table after the current read-transaction had started.
46232   */
46233   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46234     volatile ht_slot *aHash;      /* Pointer to hash table */
46235     volatile u32 *aPgno;          /* Pointer to array of page numbers */
46236     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
46237     int iKey;                     /* Hash slot index */
46238     int nCollide;                 /* Number of hash collisions remaining */
46239     int rc;                       /* Error code */
46240
46241     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46242     if( rc!=SQLITE_OK ){
46243       return rc;
46244     }
46245     nCollide = HASHTABLE_NSLOT;
46246     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46247       u32 iFrame = aHash[iKey] + iZero;
46248       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46249         /* assert( iFrame>iRead ); -- not true if there is corruption */
46250         iRead = iFrame;
46251       }
46252       if( (nCollide--)==0 ){
46253         return SQLITE_CORRUPT_BKPT;
46254       }
46255     }
46256   }
46257
46258 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46259   /* If expensive assert() statements are available, do a linear search
46260   ** of the wal-index file content. Make sure the results agree with the
46261   ** result obtained using the hash indexes above.  */
46262   {
46263     u32 iRead2 = 0;
46264     u32 iTest;
46265     for(iTest=iLast; iTest>0; iTest--){
46266       if( walFramePgno(pWal, iTest)==pgno ){
46267         iRead2 = iTest;
46268         break;
46269       }
46270     }
46271     assert( iRead==iRead2 );
46272   }
46273 #endif
46274
46275   /* If iRead is non-zero, then it is the log frame number that contains the
46276   ** required page. Read and return data from the log file.
46277   */
46278   if( iRead ){
46279     int sz;
46280     i64 iOffset;
46281     sz = pWal->hdr.szPage;
46282     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
46283     testcase( sz<=32768 );
46284     testcase( sz>=65536 );
46285     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46286     *pInWal = 1;
46287     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46288     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
46289   }
46290
46291   *pInWal = 0;
46292   return SQLITE_OK;
46293 }
46294
46295
46296 /* 
46297 ** Return the size of the database in pages (or zero, if unknown).
46298 */
46299 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46300   if( pWal && ALWAYS(pWal->readLock>=0) ){
46301     return pWal->hdr.nPage;
46302   }
46303   return 0;
46304 }
46305
46306
46307 /* 
46308 ** This function starts a write transaction on the WAL.
46309 **
46310 ** A read transaction must have already been started by a prior call
46311 ** to sqlite3WalBeginReadTransaction().
46312 **
46313 ** If another thread or process has written into the database since
46314 ** the read transaction was started, then it is not possible for this
46315 ** thread to write as doing so would cause a fork.  So this routine
46316 ** returns SQLITE_BUSY in that case and no write transaction is started.
46317 **
46318 ** There can only be a single writer active at a time.
46319 */
46320 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46321   int rc;
46322
46323   /* Cannot start a write transaction without first holding a read
46324   ** transaction. */
46325   assert( pWal->readLock>=0 );
46326
46327   if( pWal->readOnly ){
46328     return SQLITE_READONLY;
46329   }
46330
46331   /* Only one writer allowed at a time.  Get the write lock.  Return
46332   ** SQLITE_BUSY if unable.
46333   */
46334   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46335   if( rc ){
46336     return rc;
46337   }
46338   pWal->writeLock = 1;
46339
46340   /* If another connection has written to the database file since the
46341   ** time the read transaction on this connection was started, then
46342   ** the write is disallowed.
46343   */
46344   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46345     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46346     pWal->writeLock = 0;
46347     rc = SQLITE_BUSY;
46348   }
46349
46350   return rc;
46351 }
46352
46353 /*
46354 ** End a write transaction.  The commit has already been done.  This
46355 ** routine merely releases the lock.
46356 */
46357 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46358   if( pWal->writeLock ){
46359     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46360     pWal->writeLock = 0;
46361     pWal->truncateOnCommit = 0;
46362   }
46363   return SQLITE_OK;
46364 }
46365
46366 /*
46367 ** If any data has been written (but not committed) to the log file, this
46368 ** function moves the write-pointer back to the start of the transaction.
46369 **
46370 ** Additionally, the callback function is invoked for each frame written
46371 ** to the WAL since the start of the transaction. If the callback returns
46372 ** other than SQLITE_OK, it is not invoked again and the error code is
46373 ** returned to the caller.
46374 **
46375 ** Otherwise, if the callback function does not return an error, this
46376 ** function returns SQLITE_OK.
46377 */
46378 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46379   int rc = SQLITE_OK;
46380   if( ALWAYS(pWal->writeLock) ){
46381     Pgno iMax = pWal->hdr.mxFrame;
46382     Pgno iFrame;
46383   
46384     /* Restore the clients cache of the wal-index header to the state it
46385     ** was in before the client began writing to the database. 
46386     */
46387     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46388
46389     for(iFrame=pWal->hdr.mxFrame+1; 
46390         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
46391         iFrame++
46392     ){
46393       /* This call cannot fail. Unless the page for which the page number
46394       ** is passed as the second argument is (a) in the cache and 
46395       ** (b) has an outstanding reference, then xUndo is either a no-op
46396       ** (if (a) is false) or simply expels the page from the cache (if (b)
46397       ** is false).
46398       **
46399       ** If the upper layer is doing a rollback, it is guaranteed that there
46400       ** are no outstanding references to any page other than page 1. And
46401       ** page 1 is never written to the log until the transaction is
46402       ** committed. As a result, the call to xUndo may not fail.
46403       */
46404       assert( walFramePgno(pWal, iFrame)!=1 );
46405       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46406     }
46407     walCleanupHash(pWal);
46408   }
46409   assert( rc==SQLITE_OK );
46410   return rc;
46411 }
46412
46413 /* 
46414 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
46415 ** values. This function populates the array with values required to 
46416 ** "rollback" the write position of the WAL handle back to the current 
46417 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46418 */
46419 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46420   assert( pWal->writeLock );
46421   aWalData[0] = pWal->hdr.mxFrame;
46422   aWalData[1] = pWal->hdr.aFrameCksum[0];
46423   aWalData[2] = pWal->hdr.aFrameCksum[1];
46424   aWalData[3] = pWal->nCkpt;
46425 }
46426
46427 /* 
46428 ** Move the write position of the WAL back to the point identified by
46429 ** the values in the aWalData[] array. aWalData must point to an array
46430 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46431 ** by a call to WalSavepoint().
46432 */
46433 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46434   int rc = SQLITE_OK;
46435
46436   assert( pWal->writeLock );
46437   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46438
46439   if( aWalData[3]!=pWal->nCkpt ){
46440     /* This savepoint was opened immediately after the write-transaction
46441     ** was started. Right after that, the writer decided to wrap around
46442     ** to the start of the log. Update the savepoint values to match.
46443     */
46444     aWalData[0] = 0;
46445     aWalData[3] = pWal->nCkpt;
46446   }
46447
46448   if( aWalData[0]<pWal->hdr.mxFrame ){
46449     pWal->hdr.mxFrame = aWalData[0];
46450     pWal->hdr.aFrameCksum[0] = aWalData[1];
46451     pWal->hdr.aFrameCksum[1] = aWalData[2];
46452     walCleanupHash(pWal);
46453   }
46454
46455   return rc;
46456 }
46457
46458
46459 /*
46460 ** This function is called just before writing a set of frames to the log
46461 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46462 ** to the current log file, it is possible to overwrite the start of the
46463 ** existing log file with the new frames (i.e. "reset" the log). If so,
46464 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46465 ** unchanged.
46466 **
46467 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46468 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46469 ** if an error occurs.
46470 */
46471 static int walRestartLog(Wal *pWal){
46472   int rc = SQLITE_OK;
46473   int cnt;
46474
46475   if( pWal->readLock==0 ){
46476     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46477     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46478     if( pInfo->nBackfill>0 ){
46479       u32 salt1;
46480       sqlite3_randomness(4, &salt1);
46481       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46482       if( rc==SQLITE_OK ){
46483         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46484         ** readers are currently using the WAL), then the transactions
46485         ** frames will overwrite the start of the existing log. Update the
46486         ** wal-index header to reflect this.
46487         **
46488         ** In theory it would be Ok to update the cache of the header only
46489         ** at this point. But updating the actual wal-index header is also
46490         ** safe and means there is no special case for sqlite3WalUndo()
46491         ** to handle if this transaction is rolled back.
46492         */
46493         int i;                    /* Loop counter */
46494         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46495
46496         pWal->nCkpt++;
46497         pWal->hdr.mxFrame = 0;
46498         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46499         aSalt[1] = salt1;
46500         walIndexWriteHdr(pWal);
46501         pInfo->nBackfill = 0;
46502         pInfo->aReadMark[1] = 0;
46503         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46504         assert( pInfo->aReadMark[0]==0 );
46505         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46506       }else if( rc!=SQLITE_BUSY ){
46507         return rc;
46508       }
46509     }
46510     walUnlockShared(pWal, WAL_READ_LOCK(0));
46511     pWal->readLock = -1;
46512     cnt = 0;
46513     do{
46514       int notUsed;
46515       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46516     }while( rc==WAL_RETRY );
46517     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46518     testcase( (rc&0xff)==SQLITE_IOERR );
46519     testcase( rc==SQLITE_PROTOCOL );
46520     testcase( rc==SQLITE_OK );
46521   }
46522   return rc;
46523 }
46524
46525 /*
46526 ** Information about the current state of the WAL file and where
46527 ** the next fsync should occur - passed from sqlite3WalFrames() into
46528 ** walWriteToLog().
46529 */
46530 typedef struct WalWriter {
46531   Wal *pWal;                   /* The complete WAL information */
46532   sqlite3_file *pFd;           /* The WAL file to which we write */
46533   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
46534   int syncFlags;               /* Flags for the fsync */
46535   int szPage;                  /* Size of one page */
46536 } WalWriter;
46537
46538 /*
46539 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
46540 ** Do a sync when crossing the p->iSyncPoint boundary.
46541 **
46542 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
46543 ** first write the part before iSyncPoint, then sync, then write the
46544 ** rest.
46545 */
46546 static int walWriteToLog(
46547   WalWriter *p,              /* WAL to write to */
46548   void *pContent,            /* Content to be written */
46549   int iAmt,                  /* Number of bytes to write */
46550   sqlite3_int64 iOffset      /* Start writing at this offset */
46551 ){
46552   int rc;
46553   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
46554     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
46555     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
46556     if( rc ) return rc;
46557     iOffset += iFirstAmt;
46558     iAmt -= iFirstAmt;
46559     pContent = (void*)(iFirstAmt + (char*)pContent);
46560     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
46561     rc = sqlite3OsSync(p->pFd, p->syncFlags);
46562     if( iAmt==0 || rc ) return rc;
46563   }
46564   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
46565   return rc;
46566 }
46567
46568 /*
46569 ** Write out a single frame of the WAL
46570 */
46571 static int walWriteOneFrame(
46572   WalWriter *p,               /* Where to write the frame */
46573   PgHdr *pPage,               /* The page of the frame to be written */
46574   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
46575   sqlite3_int64 iOffset       /* Byte offset at which to write */
46576 ){
46577   int rc;                         /* Result code from subfunctions */
46578   void *pData;                    /* Data actually written */
46579   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
46580 #if defined(SQLITE_HAS_CODEC)
46581   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
46582 #else
46583   pData = pPage->pData;
46584 #endif
46585   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
46586   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
46587   if( rc ) return rc;
46588   /* Write the page data */
46589   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
46590   return rc;
46591 }
46592
46593 /* 
46594 ** Write a set of frames to the log. The caller must hold the write-lock
46595 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46596 */
46597 SQLITE_PRIVATE int sqlite3WalFrames(
46598   Wal *pWal,                      /* Wal handle to write to */
46599   int szPage,                     /* Database page-size in bytes */
46600   PgHdr *pList,                   /* List of dirty pages to write */
46601   Pgno nTruncate,                 /* Database size after this commit */
46602   int isCommit,                   /* True if this is a commit */
46603   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
46604 ){
46605   int rc;                         /* Used to catch return codes */
46606   u32 iFrame;                     /* Next frame address */
46607   PgHdr *p;                       /* Iterator to run through pList with. */
46608   PgHdr *pLast = 0;               /* Last frame in list */
46609   int nExtra = 0;                 /* Number of extra copies of last page */
46610   int szFrame;                    /* The size of a single frame */
46611   i64 iOffset;                    /* Next byte to write in WAL file */
46612   WalWriter w;                    /* The writer */
46613
46614   assert( pList );
46615   assert( pWal->writeLock );
46616
46617   /* If this frame set completes a transaction, then nTruncate>0.  If
46618   ** nTruncate==0 then this frame set does not complete the transaction. */
46619   assert( (isCommit!=0)==(nTruncate!=0) );
46620
46621 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46622   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
46623     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
46624               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
46625   }
46626 #endif
46627
46628   /* See if it is possible to write these frames into the start of the
46629   ** log file, instead of appending to it at pWal->hdr.mxFrame.
46630   */
46631   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
46632     return rc;
46633   }
46634
46635   /* If this is the first frame written into the log, write the WAL
46636   ** header to the start of the WAL file. See comments at the top of
46637   ** this source file for a description of the WAL header format.
46638   */
46639   iFrame = pWal->hdr.mxFrame;
46640   if( iFrame==0 ){
46641     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
46642     u32 aCksum[2];                /* Checksum for wal-header */
46643
46644     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
46645     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
46646     sqlite3Put4byte(&aWalHdr[8], szPage);
46647     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
46648     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
46649     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
46650     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
46651     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
46652     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
46653     
46654     pWal->szPage = szPage;
46655     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
46656     pWal->hdr.aFrameCksum[0] = aCksum[0];
46657     pWal->hdr.aFrameCksum[1] = aCksum[1];
46658     pWal->truncateOnCommit = 1;
46659
46660     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
46661     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
46662     if( rc!=SQLITE_OK ){
46663       return rc;
46664     }
46665
46666     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
46667     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
46668     ** an out-of-order write following a WAL restart could result in
46669     ** database corruption.  See the ticket:
46670     **
46671     **     http://localhost:591/sqlite/info/ff5be73dee
46672     */
46673     if( pWal->syncHeader && sync_flags ){
46674       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
46675       if( rc ) return rc;
46676     }
46677   }
46678   assert( (int)pWal->szPage==szPage );
46679
46680   /* Setup information needed to write frames into the WAL */
46681   w.pWal = pWal;
46682   w.pFd = pWal->pWalFd;
46683   w.iSyncPoint = 0;
46684   w.syncFlags = sync_flags;
46685   w.szPage = szPage;
46686   iOffset = walFrameOffset(iFrame+1, szPage);
46687   szFrame = szPage + WAL_FRAME_HDRSIZE;
46688
46689   /* Write all frames into the log file exactly once */
46690   for(p=pList; p; p=p->pDirty){
46691     int nDbSize;   /* 0 normally.  Positive == commit flag */
46692     iFrame++;
46693     assert( iOffset==walFrameOffset(iFrame, szPage) );
46694     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
46695     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
46696     if( rc ) return rc;
46697     pLast = p;
46698     iOffset += szFrame;
46699   }
46700
46701   /* If this is the end of a transaction, then we might need to pad
46702   ** the transaction and/or sync the WAL file.
46703   **
46704   ** Padding and syncing only occur if this set of frames complete a
46705   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
46706   ** or synchonous==OFF, then no padding or syncing are needed.
46707   **
46708   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
46709   ** needed and only the sync is done.  If padding is needed, then the
46710   ** final frame is repeated (with its commit mark) until the next sector
46711   ** boundary is crossed.  Only the part of the WAL prior to the last
46712   ** sector boundary is synced; the part of the last frame that extends
46713   ** past the sector boundary is written after the sync.
46714   */
46715   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
46716     if( pWal->padToSectorBoundary ){
46717       int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
46718       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
46719       while( iOffset<w.iSyncPoint ){
46720         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
46721         if( rc ) return rc;
46722         iOffset += szFrame;
46723         nExtra++;
46724       }
46725     }else{
46726       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
46727     }
46728   }
46729
46730   /* If this frame set completes the first transaction in the WAL and
46731   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
46732   ** journal size limit, if possible.
46733   */
46734   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
46735     i64 sz = pWal->mxWalSize;
46736     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
46737       sz = walFrameOffset(iFrame+nExtra+1, szPage);
46738     }
46739     walLimitSize(pWal, sz);
46740     pWal->truncateOnCommit = 0;
46741   }
46742
46743   /* Append data to the wal-index. It is not necessary to lock the 
46744   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
46745   ** guarantees that there are no other writers, and no data that may
46746   ** be in use by existing readers is being overwritten.
46747   */
46748   iFrame = pWal->hdr.mxFrame;
46749   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
46750     iFrame++;
46751     rc = walIndexAppend(pWal, iFrame, p->pgno);
46752   }
46753   while( rc==SQLITE_OK && nExtra>0 ){
46754     iFrame++;
46755     nExtra--;
46756     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
46757   }
46758
46759   if( rc==SQLITE_OK ){
46760     /* Update the private copy of the header. */
46761     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46762     testcase( szPage<=32768 );
46763     testcase( szPage>=65536 );
46764     pWal->hdr.mxFrame = iFrame;
46765     if( isCommit ){
46766       pWal->hdr.iChange++;
46767       pWal->hdr.nPage = nTruncate;
46768     }
46769     /* If this is a commit, update the wal-index header too. */
46770     if( isCommit ){
46771       walIndexWriteHdr(pWal);
46772       pWal->iCallback = iFrame;
46773     }
46774   }
46775
46776   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
46777   return rc;
46778 }
46779
46780 /* 
46781 ** This routine is called to implement sqlite3_wal_checkpoint() and
46782 ** related interfaces.
46783 **
46784 ** Obtain a CHECKPOINT lock and then backfill as much information as
46785 ** we can from WAL into the database.
46786 **
46787 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46788 ** callback. In this case this function runs a blocking checkpoint.
46789 */
46790 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46791   Wal *pWal,                      /* Wal connection */
46792   int eMode,                      /* PASSIVE, FULL or RESTART */
46793   int (*xBusy)(void*),            /* Function to call when busy */
46794   void *pBusyArg,                 /* Context argument for xBusyHandler */
46795   int sync_flags,                 /* Flags to sync db file with (or 0) */
46796   int nBuf,                       /* Size of temporary buffer */
46797   u8 *zBuf,                       /* Temporary buffer to use */
46798   int *pnLog,                     /* OUT: Number of frames in WAL */
46799   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46800 ){
46801   int rc;                         /* Return code */
46802   int isChanged = 0;              /* True if a new wal-index header is loaded */
46803   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
46804
46805   assert( pWal->ckptLock==0 );
46806   assert( pWal->writeLock==0 );
46807
46808   if( pWal->readOnly ) return SQLITE_READONLY;
46809   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46810   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46811   if( rc ){
46812     /* Usually this is SQLITE_BUSY meaning that another thread or process
46813     ** is already running a checkpoint, or maybe a recovery.  But it might
46814     ** also be SQLITE_IOERR. */
46815     return rc;
46816   }
46817   pWal->ckptLock = 1;
46818
46819   /* If this is a blocking-checkpoint, then obtain the write-lock as well
46820   ** to prevent any writers from running while the checkpoint is underway.
46821   ** This has to be done before the call to walIndexReadHdr() below.
46822   **
46823   ** If the writer lock cannot be obtained, then a passive checkpoint is
46824   ** run instead. Since the checkpointer is not holding the writer lock,
46825   ** there is no point in blocking waiting for any readers. Assuming no 
46826   ** other error occurs, this function will return SQLITE_BUSY to the caller.
46827   */
46828   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46829     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
46830     if( rc==SQLITE_OK ){
46831       pWal->writeLock = 1;
46832     }else if( rc==SQLITE_BUSY ){
46833       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
46834       rc = SQLITE_OK;
46835     }
46836   }
46837
46838   /* Read the wal-index header. */
46839   if( rc==SQLITE_OK ){
46840     rc = walIndexReadHdr(pWal, &isChanged);
46841   }
46842
46843   /* Copy data from the log to the database file. */
46844   if( rc==SQLITE_OK ){
46845     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
46846       rc = SQLITE_CORRUPT_BKPT;
46847     }else{
46848       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
46849     }
46850
46851     /* If no error occurred, set the output variables. */
46852     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
46853       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
46854       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
46855     }
46856   }
46857
46858   if( isChanged ){
46859     /* If a new wal-index header was loaded before the checkpoint was 
46860     ** performed, then the pager-cache associated with pWal is now
46861     ** out of date. So zero the cached wal-index header to ensure that
46862     ** next time the pager opens a snapshot on this database it knows that
46863     ** the cache needs to be reset.
46864     */
46865     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46866   }
46867
46868   /* Release the locks. */
46869   sqlite3WalEndWriteTransaction(pWal);
46870   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
46871   pWal->ckptLock = 0;
46872   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
46873   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
46874 }
46875
46876 /* Return the value to pass to a sqlite3_wal_hook callback, the
46877 ** number of frames in the WAL at the point of the last commit since
46878 ** sqlite3WalCallback() was called.  If no commits have occurred since
46879 ** the last call, then return 0.
46880 */
46881 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
46882   u32 ret = 0;
46883   if( pWal ){
46884     ret = pWal->iCallback;
46885     pWal->iCallback = 0;
46886   }
46887   return (int)ret;
46888 }
46889
46890 /*
46891 ** This function is called to change the WAL subsystem into or out
46892 ** of locking_mode=EXCLUSIVE.
46893 **
46894 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
46895 ** into locking_mode=NORMAL.  This means that we must acquire a lock
46896 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
46897 ** or if the acquisition of the lock fails, then return 0.  If the
46898 ** transition out of exclusive-mode is successful, return 1.  This
46899 ** operation must occur while the pager is still holding the exclusive
46900 ** lock on the main database file.
46901 **
46902 ** If op is one, then change from locking_mode=NORMAL into 
46903 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
46904 ** be released.  Return 1 if the transition is made and 0 if the
46905 ** WAL is already in exclusive-locking mode - meaning that this
46906 ** routine is a no-op.  The pager must already hold the exclusive lock
46907 ** on the main database file before invoking this operation.
46908 **
46909 ** If op is negative, then do a dry-run of the op==1 case but do
46910 ** not actually change anything. The pager uses this to see if it
46911 ** should acquire the database exclusive lock prior to invoking
46912 ** the op==1 case.
46913 */
46914 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46915   int rc;
46916   assert( pWal->writeLock==0 );
46917   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46918
46919   /* pWal->readLock is usually set, but might be -1 if there was a 
46920   ** prior error while attempting to acquire are read-lock. This cannot 
46921   ** happen if the connection is actually in exclusive mode (as no xShmLock
46922   ** locks are taken in this case). Nor should the pager attempt to
46923   ** upgrade to exclusive-mode following such an error.
46924   */
46925   assert( pWal->readLock>=0 || pWal->lockError );
46926   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46927
46928   if( op==0 ){
46929     if( pWal->exclusiveMode ){
46930       pWal->exclusiveMode = 0;
46931       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46932         pWal->exclusiveMode = 1;
46933       }
46934       rc = pWal->exclusiveMode==0;
46935     }else{
46936       /* Already in locking_mode=NORMAL */
46937       rc = 0;
46938     }
46939   }else if( op>0 ){
46940     assert( pWal->exclusiveMode==0 );
46941     assert( pWal->readLock>=0 );
46942     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46943     pWal->exclusiveMode = 1;
46944     rc = 1;
46945   }else{
46946     rc = pWal->exclusiveMode==0;
46947   }
46948   return rc;
46949 }
46950
46951 /* 
46952 ** Return true if the argument is non-NULL and the WAL module is using
46953 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46954 ** WAL module is using shared-memory, return false. 
46955 */
46956 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46957   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46958 }
46959
46960 #ifdef SQLITE_ENABLE_ZIPVFS
46961 /*
46962 ** If the argument is not NULL, it points to a Wal object that holds a
46963 ** read-lock. This function returns the database page-size if it is known,
46964 ** or zero if it is not (or if pWal is NULL).
46965 */
46966 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
46967   assert( pWal==0 || pWal->readLock>=0 );
46968   return (pWal ? pWal->szPage : 0);
46969 }
46970 #endif
46971
46972 #endif /* #ifndef SQLITE_OMIT_WAL */
46973
46974 /************** End of wal.c *************************************************/
46975 /************** Begin file btmutex.c *****************************************/
46976 /*
46977 ** 2007 August 27
46978 **
46979 ** The author disclaims copyright to this source code.  In place of
46980 ** a legal notice, here is a blessing:
46981 **
46982 **    May you do good and not evil.
46983 **    May you find forgiveness for yourself and forgive others.
46984 **    May you share freely, never taking more than you give.
46985 **
46986 *************************************************************************
46987 **
46988 ** This file contains code used to implement mutexes on Btree objects.
46989 ** This code really belongs in btree.c.  But btree.c is getting too
46990 ** big and we want to break it down some.  This packaged seemed like
46991 ** a good breakout.
46992 */
46993 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46994 /************** Begin file btreeInt.h ****************************************/
46995 /*
46996 ** 2004 April 6
46997 **
46998 ** The author disclaims copyright to this source code.  In place of
46999 ** a legal notice, here is a blessing:
47000 **
47001 **    May you do good and not evil.
47002 **    May you find forgiveness for yourself and forgive others.
47003 **    May you share freely, never taking more than you give.
47004 **
47005 *************************************************************************
47006 ** This file implements a external (disk-based) database using BTrees.
47007 ** For a detailed discussion of BTrees, refer to
47008 **
47009 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47010 **     "Sorting And Searching", pages 473-480. Addison-Wesley
47011 **     Publishing Company, Reading, Massachusetts.
47012 **
47013 ** The basic idea is that each page of the file contains N database
47014 ** entries and N+1 pointers to subpages.
47015 **
47016 **   ----------------------------------------------------------------
47017 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47018 **   ----------------------------------------------------------------
47019 **
47020 ** All of the keys on the page that Ptr(0) points to have values less
47021 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
47022 ** values greater than Key(0) and less than Key(1).  All of the keys
47023 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
47024 ** so forth.
47025 **
47026 ** Finding a particular key requires reading O(log(M)) pages from the 
47027 ** disk where M is the number of entries in the tree.
47028 **
47029 ** In this implementation, a single file can hold one or more separate 
47030 ** BTrees.  Each BTree is identified by the index of its root page.  The
47031 ** key and data for any entry are combined to form the "payload".  A
47032 ** fixed amount of payload can be carried directly on the database
47033 ** page.  If the payload is larger than the preset amount then surplus
47034 ** bytes are stored on overflow pages.  The payload for an entry
47035 ** and the preceding pointer are combined to form a "Cell".  Each 
47036 ** page has a small header which contains the Ptr(N) pointer and other
47037 ** information such as the size of key and data.
47038 **
47039 ** FORMAT DETAILS
47040 **
47041 ** The file is divided into pages.  The first page is called page 1,
47042 ** the second is page 2, and so forth.  A page number of zero indicates
47043 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
47044 ** Each page can be either a btree page, a freelist page, an overflow
47045 ** page, or a pointer-map page.
47046 **
47047 ** The first page is always a btree page.  The first 100 bytes of the first
47048 ** page contain a special header (the "file header") that describes the file.
47049 ** The format of the file header is as follows:
47050 **
47051 **   OFFSET   SIZE    DESCRIPTION
47052 **      0      16     Header string: "SQLite format 3\000"
47053 **     16       2     Page size in bytes.  
47054 **     18       1     File format write version
47055 **     19       1     File format read version
47056 **     20       1     Bytes of unused space at the end of each page
47057 **     21       1     Max embedded payload fraction
47058 **     22       1     Min embedded payload fraction
47059 **     23       1     Min leaf payload fraction
47060 **     24       4     File change counter
47061 **     28       4     Reserved for future use
47062 **     32       4     First freelist page
47063 **     36       4     Number of freelist pages in the file
47064 **     40      60     15 4-byte meta values passed to higher layers
47065 **
47066 **     40       4     Schema cookie
47067 **     44       4     File format of schema layer
47068 **     48       4     Size of page cache
47069 **     52       4     Largest root-page (auto/incr_vacuum)
47070 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
47071 **     60       4     User version
47072 **     64       4     Incremental vacuum mode
47073 **     68       4     unused
47074 **     72       4     unused
47075 **     76       4     unused
47076 **
47077 ** All of the integer values are big-endian (most significant byte first).
47078 **
47079 ** The file change counter is incremented when the database is changed
47080 ** This counter allows other processes to know when the file has changed
47081 ** and thus when they need to flush their cache.
47082 **
47083 ** The max embedded payload fraction is the amount of the total usable
47084 ** space in a page that can be consumed by a single cell for standard
47085 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
47086 ** is to limit the maximum cell size so that at least 4 cells will fit
47087 ** on one page.  Thus the default max embedded payload fraction is 64.
47088 **
47089 ** If the payload for a cell is larger than the max payload, then extra
47090 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
47091 ** as many bytes as possible are moved into the overflow pages without letting
47092 ** the cell size drop below the min embedded payload fraction.
47093 **
47094 ** The min leaf payload fraction is like the min embedded payload fraction
47095 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
47096 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47097 ** not specified in the header.
47098 **
47099 ** Each btree pages is divided into three sections:  The header, the
47100 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
47101 ** file header that occurs before the page header.
47102 **
47103 **      |----------------|
47104 **      | file header    |   100 bytes.  Page 1 only.
47105 **      |----------------|
47106 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
47107 **      |----------------|
47108 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
47109 **      | array          |   |  Grows downward
47110 **      |                |   v
47111 **      |----------------|
47112 **      | unallocated    |
47113 **      | space          |
47114 **      |----------------|   ^  Grows upwards
47115 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
47116 **      | area           |   |  and free space fragments.
47117 **      |----------------|
47118 **
47119 ** The page headers looks like this:
47120 **
47121 **   OFFSET   SIZE     DESCRIPTION
47122 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47123 **      1       2      byte offset to the first freeblock
47124 **      3       2      number of cells on this page
47125 **      5       2      first byte of the cell content area
47126 **      7       1      number of fragmented free bytes
47127 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
47128 **
47129 ** The flags define the format of this btree page.  The leaf flag means that
47130 ** this page has no children.  The zerodata flag means that this page carries
47131 ** only keys and no data.  The intkey flag means that the key is a integer
47132 ** which is stored in the key size entry of the cell header rather than in
47133 ** the payload area.
47134 **
47135 ** The cell pointer array begins on the first byte after the page header.
47136 ** The cell pointer array contains zero or more 2-byte numbers which are
47137 ** offsets from the beginning of the page to the cell content in the cell
47138 ** content area.  The cell pointers occur in sorted order.  The system strives
47139 ** to keep free space after the last cell pointer so that new cells can
47140 ** be easily added without having to defragment the page.
47141 **
47142 ** Cell content is stored at the very end of the page and grows toward the
47143 ** beginning of the page.
47144 **
47145 ** Unused space within the cell content area is collected into a linked list of
47146 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
47147 ** to the first freeblock is given in the header.  Freeblocks occur in
47148 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
47149 ** any group of 3 or fewer unused bytes in the cell content area cannot
47150 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
47151 ** a fragment.  The total number of bytes in all fragments is recorded.
47152 ** in the page header at offset 7.
47153 **
47154 **    SIZE    DESCRIPTION
47155 **      2     Byte offset of the next freeblock
47156 **      2     Bytes in this freeblock
47157 **
47158 ** Cells are of variable length.  Cells are stored in the cell content area at
47159 ** the end of the page.  Pointers to the cells are in the cell pointer array
47160 ** that immediately follows the page header.  Cells is not necessarily
47161 ** contiguous or in order, but cell pointers are contiguous and in order.
47162 **
47163 ** Cell content makes use of variable length integers.  A variable
47164 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
47165 ** byte are used.  The integer consists of all bytes that have bit 8 set and
47166 ** the first byte with bit 8 clear.  The most significant byte of the integer
47167 ** appears first.  A variable-length integer may not be more than 9 bytes long.
47168 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
47169 ** allows a 64-bit integer to be encoded in 9 bytes.
47170 **
47171 **    0x00                      becomes  0x00000000
47172 **    0x7f                      becomes  0x0000007f
47173 **    0x81 0x00                 becomes  0x00000080
47174 **    0x82 0x00                 becomes  0x00000100
47175 **    0x80 0x7f                 becomes  0x0000007f
47176 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
47177 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
47178 **
47179 ** Variable length integers are used for rowids and to hold the number of
47180 ** bytes of key and data in a btree cell.
47181 **
47182 ** The content of a cell looks like this:
47183 **
47184 **    SIZE    DESCRIPTION
47185 **      4     Page number of the left child. Omitted if leaf flag is set.
47186 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
47187 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
47188 **      *     Payload
47189 **      4     First page of the overflow chain.  Omitted if no overflow
47190 **
47191 ** Overflow pages form a linked list.  Each page except the last is completely
47192 ** filled with data (pagesize - 4 bytes).  The last page can have as little
47193 ** as 1 byte of data.
47194 **
47195 **    SIZE    DESCRIPTION
47196 **      4     Page number of next overflow page
47197 **      *     Data
47198 **
47199 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
47200 ** file header points to the first in a linked list of trunk page.  Each trunk
47201 ** page points to multiple leaf pages.  The content of a leaf page is
47202 ** unspecified.  A trunk page looks like this:
47203 **
47204 **    SIZE    DESCRIPTION
47205 **      4     Page number of next trunk page
47206 **      4     Number of leaf pointers on this page
47207 **      *     zero or more pages numbers of leaves
47208 */
47209
47210
47211 /* The following value is the maximum cell size assuming a maximum page
47212 ** size give above.
47213 */
47214 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
47215
47216 /* The maximum number of cells on a single page of the database.  This
47217 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
47218 ** plus 2 bytes for the index to the cell in the page header).  Such
47219 ** small cells will be rare, but they are possible.
47220 */
47221 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47222
47223 /* Forward declarations */
47224 typedef struct MemPage MemPage;
47225 typedef struct BtLock BtLock;
47226
47227 /*
47228 ** This is a magic string that appears at the beginning of every
47229 ** SQLite database in order to identify the file as a real database.
47230 **
47231 ** You can change this value at compile-time by specifying a
47232 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
47233 ** header must be exactly 16 bytes including the zero-terminator so
47234 ** the string itself should be 15 characters long.  If you change
47235 ** the header, then your custom library will not be able to read 
47236 ** databases generated by the standard tools and the standard tools
47237 ** will not be able to read databases created by your custom library.
47238 */
47239 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47240 #  define SQLITE_FILE_HEADER "SQLite format 3"
47241 #endif
47242
47243 /*
47244 ** Page type flags.  An ORed combination of these flags appear as the
47245 ** first byte of on-disk image of every BTree page.
47246 */
47247 #define PTF_INTKEY    0x01
47248 #define PTF_ZERODATA  0x02
47249 #define PTF_LEAFDATA  0x04
47250 #define PTF_LEAF      0x08
47251
47252 /*
47253 ** As each page of the file is loaded into memory, an instance of the following
47254 ** structure is appended and initialized to zero.  This structure stores
47255 ** information about the page that is decoded from the raw file page.
47256 **
47257 ** The pParent field points back to the parent page.  This allows us to
47258 ** walk up the BTree from any leaf to the root.  Care must be taken to
47259 ** unref() the parent page pointer when this page is no longer referenced.
47260 ** The pageDestructor() routine handles that chore.
47261 **
47262 ** Access to all fields of this structure is controlled by the mutex
47263 ** stored in MemPage.pBt->mutex.
47264 */
47265 struct MemPage {
47266   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
47267   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
47268   u8 intKey;           /* True if intkey flag is set */
47269   u8 leaf;             /* True if leaf flag is set */
47270   u8 hasData;          /* True if this page stores data */
47271   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
47272   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
47273   u8 max1bytePayload;  /* min(maxLocal,127) */
47274   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47275   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
47276   u16 cellOffset;      /* Index in aData of first cell pointer */
47277   u16 nFree;           /* Number of free bytes on the page */
47278   u16 nCell;           /* Number of cells on this page, local and ovfl */
47279   u16 maskPage;        /* Mask for page offset */
47280   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
47281                        ** non-overflow cell */
47282   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
47283   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
47284   u8 *aData;           /* Pointer to disk image of the page data */
47285   u8 *aDataEnd;        /* One byte past the end of usable data */
47286   u8 *aCellIdx;        /* The cell index area */
47287   DbPage *pDbPage;     /* Pager page handle */
47288   Pgno pgno;           /* Page number for this page */
47289 };
47290
47291 /*
47292 ** The in-memory image of a disk page has the auxiliary information appended
47293 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
47294 ** that extra information.
47295 */
47296 #define EXTRA_SIZE sizeof(MemPage)
47297
47298 /*
47299 ** A linked list of the following structures is stored at BtShared.pLock.
47300 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
47301 ** is opened on the table with root page BtShared.iTable. Locks are removed
47302 ** from this list when a transaction is committed or rolled back, or when
47303 ** a btree handle is closed.
47304 */
47305 struct BtLock {
47306   Btree *pBtree;        /* Btree handle holding this lock */
47307   Pgno iTable;          /* Root page of table */
47308   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
47309   BtLock *pNext;        /* Next in BtShared.pLock list */
47310 };
47311
47312 /* Candidate values for BtLock.eLock */
47313 #define READ_LOCK     1
47314 #define WRITE_LOCK    2
47315
47316 /* A Btree handle
47317 **
47318 ** A database connection contains a pointer to an instance of
47319 ** this object for every database file that it has open.  This structure
47320 ** is opaque to the database connection.  The database connection cannot
47321 ** see the internals of this structure and only deals with pointers to
47322 ** this structure.
47323 **
47324 ** For some database files, the same underlying database cache might be 
47325 ** shared between multiple connections.  In that case, each connection
47326 ** has it own instance of this object.  But each instance of this object
47327 ** points to the same BtShared object.  The database cache and the
47328 ** schema associated with the database file are all contained within
47329 ** the BtShared object.
47330 **
47331 ** All fields in this structure are accessed under sqlite3.mutex.
47332 ** The pBt pointer itself may not be changed while there exists cursors 
47333 ** in the referenced BtShared that point back to this Btree since those
47334 ** cursors have to go through this Btree to find their BtShared and
47335 ** they often do so without holding sqlite3.mutex.
47336 */
47337 struct Btree {
47338   sqlite3 *db;       /* The database connection holding this btree */
47339   BtShared *pBt;     /* Sharable content of this btree */
47340   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47341   u8 sharable;       /* True if we can share pBt with another db */
47342   u8 locked;         /* True if db currently has pBt locked */
47343   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
47344   int nBackup;       /* Number of backup operations reading this btree */
47345   Btree *pNext;      /* List of other sharable Btrees from the same db */
47346   Btree *pPrev;      /* Back pointer of the same list */
47347 #ifndef SQLITE_OMIT_SHARED_CACHE
47348   BtLock lock;       /* Object used to lock page 1 */
47349 #endif
47350 };
47351
47352 /*
47353 ** Btree.inTrans may take one of the following values.
47354 **
47355 ** If the shared-data extension is enabled, there may be multiple users
47356 ** of the Btree structure. At most one of these may open a write transaction,
47357 ** but any number may have active read transactions.
47358 */
47359 #define TRANS_NONE  0
47360 #define TRANS_READ  1
47361 #define TRANS_WRITE 2
47362
47363 /*
47364 ** An instance of this object represents a single database file.
47365 ** 
47366 ** A single database file can be in use at the same time by two
47367 ** or more database connections.  When two or more connections are
47368 ** sharing the same database file, each connection has it own
47369 ** private Btree object for the file and each of those Btrees points
47370 ** to this one BtShared object.  BtShared.nRef is the number of
47371 ** connections currently sharing this database file.
47372 **
47373 ** Fields in this structure are accessed under the BtShared.mutex
47374 ** mutex, except for nRef and pNext which are accessed under the
47375 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
47376 ** may not be modified once it is initially set as long as nRef>0.
47377 ** The pSchema field may be set once under BtShared.mutex and
47378 ** thereafter is unchanged as long as nRef>0.
47379 **
47380 ** isPending:
47381 **
47382 **   If a BtShared client fails to obtain a write-lock on a database
47383 **   table (because there exists one or more read-locks on the table),
47384 **   the shared-cache enters 'pending-lock' state and isPending is
47385 **   set to true.
47386 **
47387 **   The shared-cache leaves the 'pending lock' state when either of
47388 **   the following occur:
47389 **
47390 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
47391 **     2) The number of locks held by other connections drops to zero.
47392 **
47393 **   while in the 'pending-lock' state, no connection may start a new
47394 **   transaction.
47395 **
47396 **   This feature is included to help prevent writer-starvation.
47397 */
47398 struct BtShared {
47399   Pager *pPager;        /* The page cache */
47400   sqlite3 *db;          /* Database connection currently using this Btree */
47401   BtCursor *pCursor;    /* A list of all open cursors */
47402   MemPage *pPage1;      /* First page of the database */
47403   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47404 #ifndef SQLITE_OMIT_AUTOVACUUM
47405   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47406   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47407 #endif
47408   u8 inTransaction;     /* Transaction state */
47409   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
47410   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
47411   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47412   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47413   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47414   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47415   u32 pageSize;         /* Total number of bytes on a page */
47416   u32 usableSize;       /* Number of usable bytes on each page */
47417   int nTransaction;     /* Number of open transactions (read + write) */
47418   u32 nPage;            /* Number of pages in the database */
47419   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47420   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47421   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47422   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47423 #ifndef SQLITE_OMIT_SHARED_CACHE
47424   int nRef;             /* Number of references to this structure */
47425   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47426   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47427   Btree *pWriter;       /* Btree with currently open write transaction */
47428 #endif
47429   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47430 };
47431
47432 /*
47433 ** Allowed values for BtShared.btsFlags
47434 */
47435 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
47436 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
47437 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
47438 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
47439 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
47440 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
47441 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
47442
47443 /*
47444 ** An instance of the following structure is used to hold information
47445 ** about a cell.  The parseCellPtr() function fills in this structure
47446 ** based on information extract from the raw disk page.
47447 */
47448 typedef struct CellInfo CellInfo;
47449 struct CellInfo {
47450   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47451   u8 *pCell;     /* Pointer to the start of cell content */
47452   u32 nData;     /* Number of bytes of data */
47453   u32 nPayload;  /* Total amount of payload */
47454   u16 nHeader;   /* Size of the cell content header in bytes */
47455   u16 nLocal;    /* Amount of payload held locally */
47456   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47457   u16 nSize;     /* Size of the cell content on the main b-tree page */
47458 };
47459
47460 /*
47461 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47462 ** this will be declared corrupt. This value is calculated based on a
47463 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47464 ** root-node and 3 for all other internal nodes.
47465 **
47466 ** If a tree that appears to be taller than this is encountered, it is
47467 ** assumed that the database is corrupt.
47468 */
47469 #define BTCURSOR_MAX_DEPTH 20
47470
47471 /*
47472 ** A cursor is a pointer to a particular entry within a particular
47473 ** b-tree within a database file.
47474 **
47475 ** The entry is identified by its MemPage and the index in
47476 ** MemPage.aCell[] of the entry.
47477 **
47478 ** A single database file can be shared by two more database connections,
47479 ** but cursors cannot be shared.  Each cursor is associated with a
47480 ** particular database connection identified BtCursor.pBtree.db.
47481 **
47482 ** Fields in this structure are accessed under the BtShared.mutex
47483 ** found at self->pBt->mutex. 
47484 */
47485 struct BtCursor {
47486   Btree *pBtree;            /* The Btree to which this cursor belongs */
47487   BtShared *pBt;            /* The BtShared this cursor points to */
47488   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47489   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47490 #ifndef SQLITE_OMIT_INCRBLOB
47491   Pgno *aOverflow;          /* Cache of overflow page locations */
47492 #endif
47493   Pgno pgnoRoot;            /* The root page of this tree */
47494   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47495   CellInfo info;            /* A parse of the cell we are pointing at */
47496   i64 nKey;        /* Size of pKey, or last integer key */
47497   void *pKey;      /* Saved key that was cursor's last known position */
47498   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47499   u8 wrFlag;                /* True if writable */
47500   u8 atLast;                /* Cursor pointing to the last entry */
47501   u8 validNKey;             /* True if info.nKey is valid */
47502   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47503 #ifndef SQLITE_OMIT_INCRBLOB
47504   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47505 #endif
47506   u8 hints;                             /* As configured by CursorSetHints() */
47507   i16 iPage;                            /* Index of current page in apPage */
47508   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47509   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47510 };
47511
47512 /*
47513 ** Potential values for BtCursor.eState.
47514 **
47515 ** CURSOR_VALID:
47516 **   Cursor points to a valid entry. getPayload() etc. may be called.
47517 **
47518 ** CURSOR_INVALID:
47519 **   Cursor does not point to a valid entry. This can happen (for example) 
47520 **   because the table is empty or because BtreeCursorFirst() has not been
47521 **   called.
47522 **
47523 ** CURSOR_REQUIRESEEK:
47524 **   The table that this cursor was opened on still exists, but has been 
47525 **   modified since the cursor was last used. The cursor position is saved
47526 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
47527 **   this state, restoreCursorPosition() can be called to attempt to
47528 **   seek the cursor to the saved position.
47529 **
47530 ** CURSOR_FAULT:
47531 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47532 **   on a different connection that shares the BtShared cache with this
47533 **   cursor.  The error has left the cache in an inconsistent state.
47534 **   Do nothing else with this cursor.  Any attempt to use the cursor
47535 **   should return the error code stored in BtCursor.skip
47536 */
47537 #define CURSOR_INVALID           0
47538 #define CURSOR_VALID             1
47539 #define CURSOR_REQUIRESEEK       2
47540 #define CURSOR_FAULT             3
47541
47542 /* 
47543 ** The database page the PENDING_BYTE occupies. This page is never used.
47544 */
47545 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
47546
47547 /*
47548 ** These macros define the location of the pointer-map entry for a 
47549 ** database page. The first argument to each is the number of usable
47550 ** bytes on each page of the database (often 1024). The second is the
47551 ** page number to look up in the pointer map.
47552 **
47553 ** PTRMAP_PAGENO returns the database page number of the pointer-map
47554 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
47555 ** the offset of the requested map entry.
47556 **
47557 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
47558 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
47559 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
47560 ** this test.
47561 */
47562 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
47563 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
47564 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
47565
47566 /*
47567 ** The pointer map is a lookup table that identifies the parent page for
47568 ** each child page in the database file.  The parent page is the page that
47569 ** contains a pointer to the child.  Every page in the database contains
47570 ** 0 or 1 parent pages.  (In this context 'database page' refers
47571 ** to any page that is not part of the pointer map itself.)  Each pointer map
47572 ** entry consists of a single byte 'type' and a 4 byte parent page number.
47573 ** The PTRMAP_XXX identifiers below are the valid types.
47574 **
47575 ** The purpose of the pointer map is to facility moving pages from one
47576 ** position in the file to another as part of autovacuum.  When a page
47577 ** is moved, the pointer in its parent must be updated to point to the
47578 ** new location.  The pointer map is used to locate the parent page quickly.
47579 **
47580 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
47581 **                  used in this case.
47582 **
47583 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
47584 **                  is not used in this case.
47585 **
47586 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
47587 **                   overflow pages. The page number identifies the page that
47588 **                   contains the cell with a pointer to this overflow page.
47589 **
47590 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
47591 **                   overflow pages. The page-number identifies the previous
47592 **                   page in the overflow page list.
47593 **
47594 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
47595 **               identifies the parent page in the btree.
47596 */
47597 #define PTRMAP_ROOTPAGE 1
47598 #define PTRMAP_FREEPAGE 2
47599 #define PTRMAP_OVERFLOW1 3
47600 #define PTRMAP_OVERFLOW2 4
47601 #define PTRMAP_BTREE 5
47602
47603 /* A bunch of assert() statements to check the transaction state variables
47604 ** of handle p (type Btree*) are internally consistent.
47605 */
47606 #define btreeIntegrity(p) \
47607   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
47608   assert( p->pBt->inTransaction>=p->inTrans ); 
47609
47610
47611 /*
47612 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
47613 ** if the database supports auto-vacuum or not. Because it is used
47614 ** within an expression that is an argument to another macro 
47615 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
47616 ** So, this macro is defined instead.
47617 */
47618 #ifndef SQLITE_OMIT_AUTOVACUUM
47619 #define ISAUTOVACUUM (pBt->autoVacuum)
47620 #else
47621 #define ISAUTOVACUUM 0
47622 #endif
47623
47624
47625 /*
47626 ** This structure is passed around through all the sanity checking routines
47627 ** in order to keep track of some global state information.
47628 **
47629 ** The aRef[] array is allocated so that there is 1 bit for each page in
47630 ** the database. As the integrity-check proceeds, for each page used in
47631 ** the database the corresponding bit is set. This allows integrity-check to 
47632 ** detect pages that are used twice and orphaned pages (both of which 
47633 ** indicate corruption).
47634 */
47635 typedef struct IntegrityCk IntegrityCk;
47636 struct IntegrityCk {
47637   BtShared *pBt;    /* The tree being checked out */
47638   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
47639   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
47640   Pgno nPage;       /* Number of pages in the database */
47641   int mxErr;        /* Stop accumulating errors when this reaches zero */
47642   int nErr;         /* Number of messages written to zErrMsg so far */
47643   int mallocFailed; /* A memory allocation error has occurred */
47644   StrAccum errMsg;  /* Accumulate the error message text here */
47645 };
47646
47647 /*
47648 ** Routines to read or write a two- and four-byte big-endian integer values.
47649 */
47650 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
47651 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
47652 #define get4byte sqlite3Get4byte
47653 #define put4byte sqlite3Put4byte
47654
47655 /************** End of btreeInt.h ********************************************/
47656 /************** Continuing where we left off in btmutex.c ********************/
47657 #ifndef SQLITE_OMIT_SHARED_CACHE
47658 #if SQLITE_THREADSAFE
47659
47660 /*
47661 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
47662 ** set BtShared.db to the database handle associated with p and the
47663 ** p->locked boolean to true.
47664 */
47665 static void lockBtreeMutex(Btree *p){
47666   assert( p->locked==0 );
47667   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
47668   assert( sqlite3_mutex_held(p->db->mutex) );
47669
47670   sqlite3_mutex_enter(p->pBt->mutex);
47671   p->pBt->db = p->db;
47672   p->locked = 1;
47673 }
47674
47675 /*
47676 ** Release the BtShared mutex associated with B-Tree handle p and
47677 ** clear the p->locked boolean.
47678 */
47679 static void unlockBtreeMutex(Btree *p){
47680   BtShared *pBt = p->pBt;
47681   assert( p->locked==1 );
47682   assert( sqlite3_mutex_held(pBt->mutex) );
47683   assert( sqlite3_mutex_held(p->db->mutex) );
47684   assert( p->db==pBt->db );
47685
47686   sqlite3_mutex_leave(pBt->mutex);
47687   p->locked = 0;
47688 }
47689
47690 /*
47691 ** Enter a mutex on the given BTree object.
47692 **
47693 ** If the object is not sharable, then no mutex is ever required
47694 ** and this routine is a no-op.  The underlying mutex is non-recursive.
47695 ** But we keep a reference count in Btree.wantToLock so the behavior
47696 ** of this interface is recursive.
47697 **
47698 ** To avoid deadlocks, multiple Btrees are locked in the same order
47699 ** by all database connections.  The p->pNext is a list of other
47700 ** Btrees belonging to the same database connection as the p Btree
47701 ** which need to be locked after p.  If we cannot get a lock on
47702 ** p, then first unlock all of the others on p->pNext, then wait
47703 ** for the lock to become available on p, then relock all of the
47704 ** subsequent Btrees that desire a lock.
47705 */
47706 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47707   Btree *pLater;
47708
47709   /* Some basic sanity checking on the Btree.  The list of Btrees
47710   ** connected by pNext and pPrev should be in sorted order by
47711   ** Btree.pBt value. All elements of the list should belong to
47712   ** the same connection. Only shared Btrees are on the list. */
47713   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
47714   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
47715   assert( p->pNext==0 || p->pNext->db==p->db );
47716   assert( p->pPrev==0 || p->pPrev->db==p->db );
47717   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
47718
47719   /* Check for locking consistency */
47720   assert( !p->locked || p->wantToLock>0 );
47721   assert( p->sharable || p->wantToLock==0 );
47722
47723   /* We should already hold a lock on the database connection */
47724   assert( sqlite3_mutex_held(p->db->mutex) );
47725
47726   /* Unless the database is sharable and unlocked, then BtShared.db
47727   ** should already be set correctly. */
47728   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
47729
47730   if( !p->sharable ) return;
47731   p->wantToLock++;
47732   if( p->locked ) return;
47733
47734   /* In most cases, we should be able to acquire the lock we
47735   ** want without having to go throught the ascending lock
47736   ** procedure that follows.  Just be sure not to block.
47737   */
47738   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
47739     p->pBt->db = p->db;
47740     p->locked = 1;
47741     return;
47742   }
47743
47744   /* To avoid deadlock, first release all locks with a larger
47745   ** BtShared address.  Then acquire our lock.  Then reacquire
47746   ** the other BtShared locks that we used to hold in ascending
47747   ** order.
47748   */
47749   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47750     assert( pLater->sharable );
47751     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
47752     assert( !pLater->locked || pLater->wantToLock>0 );
47753     if( pLater->locked ){
47754       unlockBtreeMutex(pLater);
47755     }
47756   }
47757   lockBtreeMutex(p);
47758   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47759     if( pLater->wantToLock ){
47760       lockBtreeMutex(pLater);
47761     }
47762   }
47763 }
47764
47765 /*
47766 ** Exit the recursive mutex on a Btree.
47767 */
47768 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
47769   if( p->sharable ){
47770     assert( p->wantToLock>0 );
47771     p->wantToLock--;
47772     if( p->wantToLock==0 ){
47773       unlockBtreeMutex(p);
47774     }
47775   }
47776 }
47777
47778 #ifndef NDEBUG
47779 /*
47780 ** Return true if the BtShared mutex is held on the btree, or if the
47781 ** B-Tree is not marked as sharable.
47782 **
47783 ** This routine is used only from within assert() statements.
47784 */
47785 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
47786   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
47787   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
47788   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
47789   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
47790
47791   return (p->sharable==0 || p->locked);
47792 }
47793 #endif
47794
47795
47796 #ifndef SQLITE_OMIT_INCRBLOB
47797 /*
47798 ** Enter and leave a mutex on a Btree given a cursor owned by that
47799 ** Btree.  These entry points are used by incremental I/O and can be
47800 ** omitted if that module is not used.
47801 */
47802 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
47803   sqlite3BtreeEnter(pCur->pBtree);
47804 }
47805 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
47806   sqlite3BtreeLeave(pCur->pBtree);
47807 }
47808 #endif /* SQLITE_OMIT_INCRBLOB */
47809
47810
47811 /*
47812 ** Enter the mutex on every Btree associated with a database
47813 ** connection.  This is needed (for example) prior to parsing
47814 ** a statement since we will be comparing table and column names
47815 ** against all schemas and we do not want those schemas being
47816 ** reset out from under us.
47817 **
47818 ** There is a corresponding leave-all procedures.
47819 **
47820 ** Enter the mutexes in accending order by BtShared pointer address
47821 ** to avoid the possibility of deadlock when two threads with
47822 ** two or more btrees in common both try to lock all their btrees
47823 ** at the same instant.
47824 */
47825 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47826   int i;
47827   Btree *p;
47828   assert( sqlite3_mutex_held(db->mutex) );
47829   for(i=0; i<db->nDb; i++){
47830     p = db->aDb[i].pBt;
47831     if( p ) sqlite3BtreeEnter(p);
47832   }
47833 }
47834 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47835   int i;
47836   Btree *p;
47837   assert( sqlite3_mutex_held(db->mutex) );
47838   for(i=0; i<db->nDb; i++){
47839     p = db->aDb[i].pBt;
47840     if( p ) sqlite3BtreeLeave(p);
47841   }
47842 }
47843
47844 /*
47845 ** Return true if a particular Btree requires a lock.  Return FALSE if
47846 ** no lock is ever required since it is not sharable.
47847 */
47848 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
47849   return p->sharable;
47850 }
47851
47852 #ifndef NDEBUG
47853 /*
47854 ** Return true if the current thread holds the database connection
47855 ** mutex and all required BtShared mutexes.
47856 **
47857 ** This routine is used inside assert() statements only.
47858 */
47859 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
47860   int i;
47861   if( !sqlite3_mutex_held(db->mutex) ){
47862     return 0;
47863   }
47864   for(i=0; i<db->nDb; i++){
47865     Btree *p;
47866     p = db->aDb[i].pBt;
47867     if( p && p->sharable &&
47868          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
47869       return 0;
47870     }
47871   }
47872   return 1;
47873 }
47874 #endif /* NDEBUG */
47875
47876 #ifndef NDEBUG
47877 /*
47878 ** Return true if the correct mutexes are held for accessing the
47879 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
47880 ** access are:
47881 **
47882 **   (1) The mutex on db
47883 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
47884 **
47885 ** If pSchema is not NULL, then iDb is computed from pSchema and
47886 ** db using sqlite3SchemaToIndex().
47887 */
47888 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
47889   Btree *p;
47890   assert( db!=0 );
47891   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
47892   assert( iDb>=0 && iDb<db->nDb );
47893   if( !sqlite3_mutex_held(db->mutex) ) return 0;
47894   if( iDb==1 ) return 1;
47895   p = db->aDb[iDb].pBt;
47896   assert( p!=0 );
47897   return p->sharable==0 || p->locked==1;
47898 }
47899 #endif /* NDEBUG */
47900
47901 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
47902 /*
47903 ** The following are special cases for mutex enter routines for use
47904 ** in single threaded applications that use shared cache.  Except for
47905 ** these two routines, all mutex operations are no-ops in that case and
47906 ** are null #defines in btree.h.
47907 **
47908 ** If shared cache is disabled, then all btree mutex routines, including
47909 ** the ones below, are no-ops and are null #defines in btree.h.
47910 */
47911
47912 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47913   p->pBt->db = p->db;
47914 }
47915 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47916   int i;
47917   for(i=0; i<db->nDb; i++){
47918     Btree *p = db->aDb[i].pBt;
47919     if( p ){
47920       p->pBt->db = p->db;
47921     }
47922   }
47923 }
47924 #endif /* if SQLITE_THREADSAFE */
47925 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
47926
47927 /************** End of btmutex.c *********************************************/
47928 /************** Begin file btree.c *******************************************/
47929 /*
47930 ** 2004 April 6
47931 **
47932 ** The author disclaims copyright to this source code.  In place of
47933 ** a legal notice, here is a blessing:
47934 **
47935 **    May you do good and not evil.
47936 **    May you find forgiveness for yourself and forgive others.
47937 **    May you share freely, never taking more than you give.
47938 **
47939 *************************************************************************
47940 ** This file implements a external (disk-based) database using BTrees.
47941 ** See the header comment on "btreeInt.h" for additional information.
47942 ** Including a description of file format and an overview of operation.
47943 */
47944
47945 /*
47946 ** The header string that appears at the beginning of every
47947 ** SQLite database.
47948 */
47949 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47950
47951 /*
47952 ** Set this global variable to 1 to enable tracing using the TRACE
47953 ** macro.
47954 */
47955 #if 0
47956 int sqlite3BtreeTrace=1;  /* True to enable tracing */
47957 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47958 #else
47959 # define TRACE(X)
47960 #endif
47961
47962 /*
47963 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47964 ** But if the value is zero, make it 65536.
47965 **
47966 ** This routine is used to extract the "offset to cell content area" value
47967 ** from the header of a btree page.  If the page size is 65536 and the page
47968 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47969 ** This routine makes the necessary adjustment to 65536.
47970 */
47971 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
47972
47973 #ifndef SQLITE_OMIT_SHARED_CACHE
47974 /*
47975 ** A list of BtShared objects that are eligible for participation
47976 ** in shared cache.  This variable has file scope during normal builds,
47977 ** but the test harness needs to access it so we make it global for 
47978 ** test builds.
47979 **
47980 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47981 */
47982 #ifdef SQLITE_TEST
47983 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47984 #else
47985 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47986 #endif
47987 #endif /* SQLITE_OMIT_SHARED_CACHE */
47988
47989 #ifndef SQLITE_OMIT_SHARED_CACHE
47990 /*
47991 ** Enable or disable the shared pager and schema features.
47992 **
47993 ** This routine has no effect on existing database connections.
47994 ** The shared cache setting effects only future calls to
47995 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47996 */
47997 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47998   sqlite3GlobalConfig.sharedCacheEnabled = enable;
47999   return SQLITE_OK;
48000 }
48001 #endif
48002
48003
48004
48005 #ifdef SQLITE_OMIT_SHARED_CACHE
48006   /*
48007   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48008   ** and clearAllSharedCacheTableLocks()
48009   ** manipulate entries in the BtShared.pLock linked list used to store
48010   ** shared-cache table level locks. If the library is compiled with the
48011   ** shared-cache feature disabled, then there is only ever one user
48012   ** of each BtShared structure and so this locking is not necessary. 
48013   ** So define the lock related functions as no-ops.
48014   */
48015   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48016   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48017   #define clearAllSharedCacheTableLocks(a)
48018   #define downgradeAllSharedCacheTableLocks(a)
48019   #define hasSharedCacheTableLock(a,b,c,d) 1
48020   #define hasReadConflicts(a, b) 0
48021 #endif
48022
48023 #ifndef SQLITE_OMIT_SHARED_CACHE
48024
48025 #ifdef SQLITE_DEBUG
48026 /*
48027 **** This function is only used as part of an assert() statement. ***
48028 **
48029 ** Check to see if pBtree holds the required locks to read or write to the 
48030 ** table with root page iRoot.   Return 1 if it does and 0 if not.
48031 **
48032 ** For example, when writing to a table with root-page iRoot via 
48033 ** Btree connection pBtree:
48034 **
48035 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48036 **
48037 ** When writing to an index that resides in a sharable database, the 
48038 ** caller should have first obtained a lock specifying the root page of
48039 ** the corresponding table. This makes things a bit more complicated,
48040 ** as this module treats each table as a separate structure. To determine
48041 ** the table corresponding to the index being written, this
48042 ** function has to search through the database schema.
48043 **
48044 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48045 ** hold a write-lock on the schema table (root page 1). This is also
48046 ** acceptable.
48047 */
48048 static int hasSharedCacheTableLock(
48049   Btree *pBtree,         /* Handle that must hold lock */
48050   Pgno iRoot,            /* Root page of b-tree */
48051   int isIndex,           /* True if iRoot is the root of an index b-tree */
48052   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
48053 ){
48054   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48055   Pgno iTab = 0;
48056   BtLock *pLock;
48057
48058   /* If this database is not shareable, or if the client is reading
48059   ** and has the read-uncommitted flag set, then no lock is required. 
48060   ** Return true immediately.
48061   */
48062   if( (pBtree->sharable==0)
48063    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48064   ){
48065     return 1;
48066   }
48067
48068   /* If the client is reading  or writing an index and the schema is
48069   ** not loaded, then it is too difficult to actually check to see if
48070   ** the correct locks are held.  So do not bother - just return true.
48071   ** This case does not come up very often anyhow.
48072   */
48073   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48074     return 1;
48075   }
48076
48077   /* Figure out the root-page that the lock should be held on. For table
48078   ** b-trees, this is just the root page of the b-tree being read or
48079   ** written. For index b-trees, it is the root page of the associated
48080   ** table.  */
48081   if( isIndex ){
48082     HashElem *p;
48083     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48084       Index *pIdx = (Index *)sqliteHashData(p);
48085       if( pIdx->tnum==(int)iRoot ){
48086         iTab = pIdx->pTable->tnum;
48087       }
48088     }
48089   }else{
48090     iTab = iRoot;
48091   }
48092
48093   /* Search for the required lock. Either a write-lock on root-page iTab, a 
48094   ** write-lock on the schema table, or (if the client is reading) a
48095   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
48096   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48097     if( pLock->pBtree==pBtree 
48098      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48099      && pLock->eLock>=eLockType 
48100     ){
48101       return 1;
48102     }
48103   }
48104
48105   /* Failed to find the required lock. */
48106   return 0;
48107 }
48108 #endif /* SQLITE_DEBUG */
48109
48110 #ifdef SQLITE_DEBUG
48111 /*
48112 **** This function may be used as part of assert() statements only. ****
48113 **
48114 ** Return true if it would be illegal for pBtree to write into the
48115 ** table or index rooted at iRoot because other shared connections are
48116 ** simultaneously reading that same table or index.
48117 **
48118 ** It is illegal for pBtree to write if some other Btree object that
48119 ** shares the same BtShared object is currently reading or writing
48120 ** the iRoot table.  Except, if the other Btree object has the
48121 ** read-uncommitted flag set, then it is OK for the other object to
48122 ** have a read cursor.
48123 **
48124 ** For example, before writing to any part of the table or index
48125 ** rooted at page iRoot, one should call:
48126 **
48127 **    assert( !hasReadConflicts(pBtree, iRoot) );
48128 */
48129 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48130   BtCursor *p;
48131   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48132     if( p->pgnoRoot==iRoot 
48133      && p->pBtree!=pBtree
48134      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48135     ){
48136       return 1;
48137     }
48138   }
48139   return 0;
48140 }
48141 #endif    /* #ifdef SQLITE_DEBUG */
48142
48143 /*
48144 ** Query to see if Btree handle p may obtain a lock of type eLock 
48145 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48146 ** SQLITE_OK if the lock may be obtained (by calling
48147 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48148 */
48149 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48150   BtShared *pBt = p->pBt;
48151   BtLock *pIter;
48152
48153   assert( sqlite3BtreeHoldsMutex(p) );
48154   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48155   assert( p->db!=0 );
48156   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48157   
48158   /* If requesting a write-lock, then the Btree must have an open write
48159   ** transaction on this file. And, obviously, for this to be so there 
48160   ** must be an open write transaction on the file itself.
48161   */
48162   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48163   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48164   
48165   /* This routine is a no-op if the shared-cache is not enabled */
48166   if( !p->sharable ){
48167     return SQLITE_OK;
48168   }
48169
48170   /* If some other connection is holding an exclusive lock, the
48171   ** requested lock may not be obtained.
48172   */
48173   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
48174     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48175     return SQLITE_LOCKED_SHAREDCACHE;
48176   }
48177
48178   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48179     /* The condition (pIter->eLock!=eLock) in the following if(...) 
48180     ** statement is a simplification of:
48181     **
48182     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48183     **
48184     ** since we know that if eLock==WRITE_LOCK, then no other connection
48185     ** may hold a WRITE_LOCK on any table in this file (since there can
48186     ** only be a single writer).
48187     */
48188     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48189     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48190     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48191       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48192       if( eLock==WRITE_LOCK ){
48193         assert( p==pBt->pWriter );
48194         pBt->btsFlags |= BTS_PENDING;
48195       }
48196       return SQLITE_LOCKED_SHAREDCACHE;
48197     }
48198   }
48199   return SQLITE_OK;
48200 }
48201 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48202
48203 #ifndef SQLITE_OMIT_SHARED_CACHE
48204 /*
48205 ** Add a lock on the table with root-page iTable to the shared-btree used
48206 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
48207 ** WRITE_LOCK.
48208 **
48209 ** This function assumes the following:
48210 **
48211 **   (a) The specified Btree object p is connected to a sharable
48212 **       database (one with the BtShared.sharable flag set), and
48213 **
48214 **   (b) No other Btree objects hold a lock that conflicts
48215 **       with the requested lock (i.e. querySharedCacheTableLock() has
48216 **       already been called and returned SQLITE_OK).
48217 **
48218 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
48219 ** is returned if a malloc attempt fails.
48220 */
48221 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48222   BtShared *pBt = p->pBt;
48223   BtLock *pLock = 0;
48224   BtLock *pIter;
48225
48226   assert( sqlite3BtreeHoldsMutex(p) );
48227   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48228   assert( p->db!=0 );
48229
48230   /* A connection with the read-uncommitted flag set will never try to
48231   ** obtain a read-lock using this function. The only read-lock obtained
48232   ** by a connection in read-uncommitted mode is on the sqlite_master 
48233   ** table, and that lock is obtained in BtreeBeginTrans().  */
48234   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48235
48236   /* This function should only be called on a sharable b-tree after it 
48237   ** has been determined that no other b-tree holds a conflicting lock.  */
48238   assert( p->sharable );
48239   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48240
48241   /* First search the list for an existing lock on this table. */
48242   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48243     if( pIter->iTable==iTable && pIter->pBtree==p ){
48244       pLock = pIter;
48245       break;
48246     }
48247   }
48248
48249   /* If the above search did not find a BtLock struct associating Btree p
48250   ** with table iTable, allocate one and link it into the list.
48251   */
48252   if( !pLock ){
48253     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48254     if( !pLock ){
48255       return SQLITE_NOMEM;
48256     }
48257     pLock->iTable = iTable;
48258     pLock->pBtree = p;
48259     pLock->pNext = pBt->pLock;
48260     pBt->pLock = pLock;
48261   }
48262
48263   /* Set the BtLock.eLock variable to the maximum of the current lock
48264   ** and the requested lock. This means if a write-lock was already held
48265   ** and a read-lock requested, we don't incorrectly downgrade the lock.
48266   */
48267   assert( WRITE_LOCK>READ_LOCK );
48268   if( eLock>pLock->eLock ){
48269     pLock->eLock = eLock;
48270   }
48271
48272   return SQLITE_OK;
48273 }
48274 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48275
48276 #ifndef SQLITE_OMIT_SHARED_CACHE
48277 /*
48278 ** Release all the table locks (locks obtained via calls to
48279 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48280 **
48281 ** This function assumes that Btree p has an open read or write 
48282 ** transaction. If it does not, then the BTS_PENDING flag
48283 ** may be incorrectly cleared.
48284 */
48285 static void clearAllSharedCacheTableLocks(Btree *p){
48286   BtShared *pBt = p->pBt;
48287   BtLock **ppIter = &pBt->pLock;
48288
48289   assert( sqlite3BtreeHoldsMutex(p) );
48290   assert( p->sharable || 0==*ppIter );
48291   assert( p->inTrans>0 );
48292
48293   while( *ppIter ){
48294     BtLock *pLock = *ppIter;
48295     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
48296     assert( pLock->pBtree->inTrans>=pLock->eLock );
48297     if( pLock->pBtree==p ){
48298       *ppIter = pLock->pNext;
48299       assert( pLock->iTable!=1 || pLock==&p->lock );
48300       if( pLock->iTable!=1 ){
48301         sqlite3_free(pLock);
48302       }
48303     }else{
48304       ppIter = &pLock->pNext;
48305     }
48306   }
48307
48308   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
48309   if( pBt->pWriter==p ){
48310     pBt->pWriter = 0;
48311     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48312   }else if( pBt->nTransaction==2 ){
48313     /* This function is called when Btree p is concluding its 
48314     ** transaction. If there currently exists a writer, and p is not
48315     ** that writer, then the number of locks held by connections other
48316     ** than the writer must be about to drop to zero. In this case
48317     ** set the BTS_PENDING flag to 0.
48318     **
48319     ** If there is not currently a writer, then BTS_PENDING must
48320     ** be zero already. So this next line is harmless in that case.
48321     */
48322     pBt->btsFlags &= ~BTS_PENDING;
48323   }
48324 }
48325
48326 /*
48327 ** This function changes all write-locks held by Btree p into read-locks.
48328 */
48329 static void downgradeAllSharedCacheTableLocks(Btree *p){
48330   BtShared *pBt = p->pBt;
48331   if( pBt->pWriter==p ){
48332     BtLock *pLock;
48333     pBt->pWriter = 0;
48334     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48335     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48336       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48337       pLock->eLock = READ_LOCK;
48338     }
48339   }
48340 }
48341
48342 #endif /* SQLITE_OMIT_SHARED_CACHE */
48343
48344 static void releasePage(MemPage *pPage);  /* Forward reference */
48345
48346 /*
48347 ***** This routine is used inside of assert() only ****
48348 **
48349 ** Verify that the cursor holds the mutex on its BtShared
48350 */
48351 #ifdef SQLITE_DEBUG
48352 static int cursorHoldsMutex(BtCursor *p){
48353   return sqlite3_mutex_held(p->pBt->mutex);
48354 }
48355 #endif
48356
48357
48358 #ifndef SQLITE_OMIT_INCRBLOB
48359 /*
48360 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48361 */
48362 static void invalidateOverflowCache(BtCursor *pCur){
48363   assert( cursorHoldsMutex(pCur) );
48364   sqlite3_free(pCur->aOverflow);
48365   pCur->aOverflow = 0;
48366 }
48367
48368 /*
48369 ** Invalidate the overflow page-list cache for all cursors opened
48370 ** on the shared btree structure pBt.
48371 */
48372 static void invalidateAllOverflowCache(BtShared *pBt){
48373   BtCursor *p;
48374   assert( sqlite3_mutex_held(pBt->mutex) );
48375   for(p=pBt->pCursor; p; p=p->pNext){
48376     invalidateOverflowCache(p);
48377   }
48378 }
48379
48380 /*
48381 ** This function is called before modifying the contents of a table
48382 ** to invalidate any incrblob cursors that are open on the
48383 ** row or one of the rows being modified.
48384 **
48385 ** If argument isClearTable is true, then the entire contents of the
48386 ** table is about to be deleted. In this case invalidate all incrblob
48387 ** cursors open on any row within the table with root-page pgnoRoot.
48388 **
48389 ** Otherwise, if argument isClearTable is false, then the row with
48390 ** rowid iRow is being replaced or deleted. In this case invalidate
48391 ** only those incrblob cursors open on that specific row.
48392 */
48393 static void invalidateIncrblobCursors(
48394   Btree *pBtree,          /* The database file to check */
48395   i64 iRow,               /* The rowid that might be changing */
48396   int isClearTable        /* True if all rows are being deleted */
48397 ){
48398   BtCursor *p;
48399   BtShared *pBt = pBtree->pBt;
48400   assert( sqlite3BtreeHoldsMutex(pBtree) );
48401   for(p=pBt->pCursor; p; p=p->pNext){
48402     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48403       p->eState = CURSOR_INVALID;
48404     }
48405   }
48406 }
48407
48408 #else
48409   /* Stub functions when INCRBLOB is omitted */
48410   #define invalidateOverflowCache(x)
48411   #define invalidateAllOverflowCache(x)
48412   #define invalidateIncrblobCursors(x,y,z)
48413 #endif /* SQLITE_OMIT_INCRBLOB */
48414
48415 /*
48416 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
48417 ** when a page that previously contained data becomes a free-list leaf 
48418 ** page.
48419 **
48420 ** The BtShared.pHasContent bitvec exists to work around an obscure
48421 ** bug caused by the interaction of two useful IO optimizations surrounding
48422 ** free-list leaf pages:
48423 **
48424 **   1) When all data is deleted from a page and the page becomes
48425 **      a free-list leaf page, the page is not written to the database
48426 **      (as free-list leaf pages contain no meaningful data). Sometimes
48427 **      such a page is not even journalled (as it will not be modified,
48428 **      why bother journalling it?).
48429 **
48430 **   2) When a free-list leaf page is reused, its content is not read
48431 **      from the database or written to the journal file (why should it
48432 **      be, if it is not at all meaningful?).
48433 **
48434 ** By themselves, these optimizations work fine and provide a handy
48435 ** performance boost to bulk delete or insert operations. However, if
48436 ** a page is moved to the free-list and then reused within the same
48437 ** transaction, a problem comes up. If the page is not journalled when
48438 ** it is moved to the free-list and it is also not journalled when it
48439 ** is extracted from the free-list and reused, then the original data
48440 ** may be lost. In the event of a rollback, it may not be possible
48441 ** to restore the database to its original configuration.
48442 **
48443 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
48444 ** moved to become a free-list leaf page, the corresponding bit is
48445 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48446 ** optimization 2 above is omitted if the corresponding bit is already
48447 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48448 ** at the end of every transaction.
48449 */
48450 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48451   int rc = SQLITE_OK;
48452   if( !pBt->pHasContent ){
48453     assert( pgno<=pBt->nPage );
48454     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48455     if( !pBt->pHasContent ){
48456       rc = SQLITE_NOMEM;
48457     }
48458   }
48459   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48460     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48461   }
48462   return rc;
48463 }
48464
48465 /*
48466 ** Query the BtShared.pHasContent vector.
48467 **
48468 ** This function is called when a free-list leaf page is removed from the
48469 ** free-list for reuse. It returns false if it is safe to retrieve the
48470 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48471 */
48472 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48473   Bitvec *p = pBt->pHasContent;
48474   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48475 }
48476
48477 /*
48478 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48479 ** invoked at the conclusion of each write-transaction.
48480 */
48481 static void btreeClearHasContent(BtShared *pBt){
48482   sqlite3BitvecDestroy(pBt->pHasContent);
48483   pBt->pHasContent = 0;
48484 }
48485
48486 /*
48487 ** Save the current cursor position in the variables BtCursor.nKey 
48488 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48489 **
48490 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48491 ** prior to calling this routine.  
48492 */
48493 static int saveCursorPosition(BtCursor *pCur){
48494   int rc;
48495
48496   assert( CURSOR_VALID==pCur->eState );
48497   assert( 0==pCur->pKey );
48498   assert( cursorHoldsMutex(pCur) );
48499
48500   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48501   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48502
48503   /* If this is an intKey table, then the above call to BtreeKeySize()
48504   ** stores the integer key in pCur->nKey. In this case this value is
48505   ** all that is required. Otherwise, if pCur is not open on an intKey
48506   ** table, then malloc space for and store the pCur->nKey bytes of key 
48507   ** data.
48508   */
48509   if( 0==pCur->apPage[0]->intKey ){
48510     void *pKey = sqlite3Malloc( (int)pCur->nKey );
48511     if( pKey ){
48512       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48513       if( rc==SQLITE_OK ){
48514         pCur->pKey = pKey;
48515       }else{
48516         sqlite3_free(pKey);
48517       }
48518     }else{
48519       rc = SQLITE_NOMEM;
48520     }
48521   }
48522   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
48523
48524   if( rc==SQLITE_OK ){
48525     int i;
48526     for(i=0; i<=pCur->iPage; i++){
48527       releasePage(pCur->apPage[i]);
48528       pCur->apPage[i] = 0;
48529     }
48530     pCur->iPage = -1;
48531     pCur->eState = CURSOR_REQUIRESEEK;
48532   }
48533
48534   invalidateOverflowCache(pCur);
48535   return rc;
48536 }
48537
48538 /*
48539 ** Save the positions of all cursors (except pExcept) that are open on
48540 ** the table  with root-page iRoot. Usually, this is called just before cursor
48541 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
48542 */
48543 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
48544   BtCursor *p;
48545   assert( sqlite3_mutex_held(pBt->mutex) );
48546   assert( pExcept==0 || pExcept->pBt==pBt );
48547   for(p=pBt->pCursor; p; p=p->pNext){
48548     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
48549         p->eState==CURSOR_VALID ){
48550       int rc = saveCursorPosition(p);
48551       if( SQLITE_OK!=rc ){
48552         return rc;
48553       }
48554     }
48555   }
48556   return SQLITE_OK;
48557 }
48558
48559 /*
48560 ** Clear the current cursor position.
48561 */
48562 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
48563   assert( cursorHoldsMutex(pCur) );
48564   sqlite3_free(pCur->pKey);
48565   pCur->pKey = 0;
48566   pCur->eState = CURSOR_INVALID;
48567 }
48568
48569 /*
48570 ** In this version of BtreeMoveto, pKey is a packed index record
48571 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
48572 ** record and then call BtreeMovetoUnpacked() to do the work.
48573 */
48574 static int btreeMoveto(
48575   BtCursor *pCur,     /* Cursor open on the btree to be searched */
48576   const void *pKey,   /* Packed key if the btree is an index */
48577   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
48578   int bias,           /* Bias search to the high end */
48579   int *pRes           /* Write search results here */
48580 ){
48581   int rc;                    /* Status code */
48582   UnpackedRecord *pIdxKey;   /* Unpacked index key */
48583   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
48584   char *pFree = 0;
48585
48586   if( pKey ){
48587     assert( nKey==(i64)(int)nKey );
48588     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
48589         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
48590     );
48591     if( pIdxKey==0 ) return SQLITE_NOMEM;
48592     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
48593   }else{
48594     pIdxKey = 0;
48595   }
48596   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
48597   if( pFree ){
48598     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
48599   }
48600   return rc;
48601 }
48602
48603 /*
48604 ** Restore the cursor to the position it was in (or as close to as possible)
48605 ** when saveCursorPosition() was called. Note that this call deletes the 
48606 ** saved position info stored by saveCursorPosition(), so there can be
48607 ** at most one effective restoreCursorPosition() call after each 
48608 ** saveCursorPosition().
48609 */
48610 static int btreeRestoreCursorPosition(BtCursor *pCur){
48611   int rc;
48612   assert( cursorHoldsMutex(pCur) );
48613   assert( pCur->eState>=CURSOR_REQUIRESEEK );
48614   if( pCur->eState==CURSOR_FAULT ){
48615     return pCur->skipNext;
48616   }
48617   pCur->eState = CURSOR_INVALID;
48618   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
48619   if( rc==SQLITE_OK ){
48620     sqlite3_free(pCur->pKey);
48621     pCur->pKey = 0;
48622     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
48623   }
48624   return rc;
48625 }
48626
48627 #define restoreCursorPosition(p) \
48628   (p->eState>=CURSOR_REQUIRESEEK ? \
48629          btreeRestoreCursorPosition(p) : \
48630          SQLITE_OK)
48631
48632 /*
48633 ** Determine whether or not a cursor has moved from the position it
48634 ** was last placed at.  Cursors can move when the row they are pointing
48635 ** at is deleted out from under them.
48636 **
48637 ** This routine returns an error code if something goes wrong.  The
48638 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
48639 */
48640 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
48641   int rc;
48642
48643   rc = restoreCursorPosition(pCur);
48644   if( rc ){
48645     *pHasMoved = 1;
48646     return rc;
48647   }
48648   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
48649     *pHasMoved = 1;
48650   }else{
48651     *pHasMoved = 0;
48652   }
48653   return SQLITE_OK;
48654 }
48655
48656 #ifndef SQLITE_OMIT_AUTOVACUUM
48657 /*
48658 ** Given a page number of a regular database page, return the page
48659 ** number for the pointer-map page that contains the entry for the
48660 ** input page number.
48661 **
48662 ** Return 0 (not a valid page) for pgno==1 since there is
48663 ** no pointer map associated with page 1.  The integrity_check logic
48664 ** requires that ptrmapPageno(*,1)!=1.
48665 */
48666 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
48667   int nPagesPerMapPage;
48668   Pgno iPtrMap, ret;
48669   assert( sqlite3_mutex_held(pBt->mutex) );
48670   if( pgno<2 ) return 0;
48671   nPagesPerMapPage = (pBt->usableSize/5)+1;
48672   iPtrMap = (pgno-2)/nPagesPerMapPage;
48673   ret = (iPtrMap*nPagesPerMapPage) + 2; 
48674   if( ret==PENDING_BYTE_PAGE(pBt) ){
48675     ret++;
48676   }
48677   return ret;
48678 }
48679
48680 /*
48681 ** Write an entry into the pointer map.
48682 **
48683 ** This routine updates the pointer map entry for page number 'key'
48684 ** so that it maps to type 'eType' and parent page number 'pgno'.
48685 **
48686 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
48687 ** a no-op.  If an error occurs, the appropriate error code is written
48688 ** into *pRC.
48689 */
48690 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
48691   DbPage *pDbPage;  /* The pointer map page */
48692   u8 *pPtrmap;      /* The pointer map data */
48693   Pgno iPtrmap;     /* The pointer map page number */
48694   int offset;       /* Offset in pointer map page */
48695   int rc;           /* Return code from subfunctions */
48696
48697   if( *pRC ) return;
48698
48699   assert( sqlite3_mutex_held(pBt->mutex) );
48700   /* The master-journal page number must never be used as a pointer map page */
48701   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
48702
48703   assert( pBt->autoVacuum );
48704   if( key==0 ){
48705     *pRC = SQLITE_CORRUPT_BKPT;
48706     return;
48707   }
48708   iPtrmap = PTRMAP_PAGENO(pBt, key);
48709   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48710   if( rc!=SQLITE_OK ){
48711     *pRC = rc;
48712     return;
48713   }
48714   offset = PTRMAP_PTROFFSET(iPtrmap, key);
48715   if( offset<0 ){
48716     *pRC = SQLITE_CORRUPT_BKPT;
48717     goto ptrmap_exit;
48718   }
48719   assert( offset <= (int)pBt->usableSize-5 );
48720   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48721
48722   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
48723     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
48724     *pRC= rc = sqlite3PagerWrite(pDbPage);
48725     if( rc==SQLITE_OK ){
48726       pPtrmap[offset] = eType;
48727       put4byte(&pPtrmap[offset+1], parent);
48728     }
48729   }
48730
48731 ptrmap_exit:
48732   sqlite3PagerUnref(pDbPage);
48733 }
48734
48735 /*
48736 ** Read an entry from the pointer map.
48737 **
48738 ** This routine retrieves the pointer map entry for page 'key', writing
48739 ** the type and parent page number to *pEType and *pPgno respectively.
48740 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
48741 */
48742 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
48743   DbPage *pDbPage;   /* The pointer map page */
48744   int iPtrmap;       /* Pointer map page index */
48745   u8 *pPtrmap;       /* Pointer map page data */
48746   int offset;        /* Offset of entry in pointer map */
48747   int rc;
48748
48749   assert( sqlite3_mutex_held(pBt->mutex) );
48750
48751   iPtrmap = PTRMAP_PAGENO(pBt, key);
48752   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48753   if( rc!=0 ){
48754     return rc;
48755   }
48756   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48757
48758   offset = PTRMAP_PTROFFSET(iPtrmap, key);
48759   if( offset<0 ){
48760     sqlite3PagerUnref(pDbPage);
48761     return SQLITE_CORRUPT_BKPT;
48762   }
48763   assert( offset <= (int)pBt->usableSize-5 );
48764   assert( pEType!=0 );
48765   *pEType = pPtrmap[offset];
48766   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
48767
48768   sqlite3PagerUnref(pDbPage);
48769   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
48770   return SQLITE_OK;
48771 }
48772
48773 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
48774   #define ptrmapPut(w,x,y,z,rc)
48775   #define ptrmapGet(w,x,y,z) SQLITE_OK
48776   #define ptrmapPutOvflPtr(x, y, rc)
48777 #endif
48778
48779 /*
48780 ** Given a btree page and a cell index (0 means the first cell on
48781 ** the page, 1 means the second cell, and so forth) return a pointer
48782 ** to the cell content.
48783 **
48784 ** This routine works only for pages that do not contain overflow cells.
48785 */
48786 #define findCell(P,I) \
48787   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
48788 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
48789
48790
48791 /*
48792 ** This a more complex version of findCell() that works for
48793 ** pages that do contain overflow cells.
48794 */
48795 static u8 *findOverflowCell(MemPage *pPage, int iCell){
48796   int i;
48797   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48798   for(i=pPage->nOverflow-1; i>=0; i--){
48799     int k;
48800     k = pPage->aiOvfl[i];
48801     if( k<=iCell ){
48802       if( k==iCell ){
48803         return pPage->apOvfl[i];
48804       }
48805       iCell--;
48806     }
48807   }
48808   return findCell(pPage, iCell);
48809 }
48810
48811 /*
48812 ** Parse a cell content block and fill in the CellInfo structure.  There
48813 ** are two versions of this function.  btreeParseCell() takes a 
48814 ** cell index as the second argument and btreeParseCellPtr() 
48815 ** takes a pointer to the body of the cell as its second argument.
48816 **
48817 ** Within this file, the parseCell() macro can be called instead of
48818 ** btreeParseCellPtr(). Using some compilers, this will be faster.
48819 */
48820 static void btreeParseCellPtr(
48821   MemPage *pPage,         /* Page containing the cell */
48822   u8 *pCell,              /* Pointer to the cell text. */
48823   CellInfo *pInfo         /* Fill in this structure */
48824 ){
48825   u16 n;                  /* Number bytes in cell content header */
48826   u32 nPayload;           /* Number of bytes of cell payload */
48827
48828   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48829
48830   pInfo->pCell = pCell;
48831   assert( pPage->leaf==0 || pPage->leaf==1 );
48832   n = pPage->childPtrSize;
48833   assert( n==4-4*pPage->leaf );
48834   if( pPage->intKey ){
48835     if( pPage->hasData ){
48836       n += getVarint32(&pCell[n], nPayload);
48837     }else{
48838       nPayload = 0;
48839     }
48840     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48841     pInfo->nData = nPayload;
48842   }else{
48843     pInfo->nData = 0;
48844     n += getVarint32(&pCell[n], nPayload);
48845     pInfo->nKey = nPayload;
48846   }
48847   pInfo->nPayload = nPayload;
48848   pInfo->nHeader = n;
48849   testcase( nPayload==pPage->maxLocal );
48850   testcase( nPayload==pPage->maxLocal+1 );
48851   if( likely(nPayload<=pPage->maxLocal) ){
48852     /* This is the (easy) common case where the entire payload fits
48853     ** on the local page.  No overflow is required.
48854     */
48855     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
48856     pInfo->nLocal = (u16)nPayload;
48857     pInfo->iOverflow = 0;
48858   }else{
48859     /* If the payload will not fit completely on the local page, we have
48860     ** to decide how much to store locally and how much to spill onto
48861     ** overflow pages.  The strategy is to minimize the amount of unused
48862     ** space on overflow pages while keeping the amount of local storage
48863     ** in between minLocal and maxLocal.
48864     **
48865     ** Warning:  changing the way overflow payload is distributed in any
48866     ** way will result in an incompatible file format.
48867     */
48868     int minLocal;  /* Minimum amount of payload held locally */
48869     int maxLocal;  /* Maximum amount of payload held locally */
48870     int surplus;   /* Overflow payload available for local storage */
48871
48872     minLocal = pPage->minLocal;
48873     maxLocal = pPage->maxLocal;
48874     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
48875     testcase( surplus==maxLocal );
48876     testcase( surplus==maxLocal+1 );
48877     if( surplus <= maxLocal ){
48878       pInfo->nLocal = (u16)surplus;
48879     }else{
48880       pInfo->nLocal = (u16)minLocal;
48881     }
48882     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
48883     pInfo->nSize = pInfo->iOverflow + 4;
48884   }
48885 }
48886 #define parseCell(pPage, iCell, pInfo) \
48887   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
48888 static void btreeParseCell(
48889   MemPage *pPage,         /* Page containing the cell */
48890   int iCell,              /* The cell index.  First cell is 0 */
48891   CellInfo *pInfo         /* Fill in this structure */
48892 ){
48893   parseCell(pPage, iCell, pInfo);
48894 }
48895
48896 /*
48897 ** Compute the total number of bytes that a Cell needs in the cell
48898 ** data area of the btree-page.  The return number includes the cell
48899 ** data header and the local payload, but not any overflow page or
48900 ** the space used by the cell pointer.
48901 */
48902 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
48903   u8 *pIter = &pCell[pPage->childPtrSize];
48904   u32 nSize;
48905
48906 #ifdef SQLITE_DEBUG
48907   /* The value returned by this function should always be the same as
48908   ** the (CellInfo.nSize) value found by doing a full parse of the
48909   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
48910   ** this function verifies that this invariant is not violated. */
48911   CellInfo debuginfo;
48912   btreeParseCellPtr(pPage, pCell, &debuginfo);
48913 #endif
48914
48915   if( pPage->intKey ){
48916     u8 *pEnd;
48917     if( pPage->hasData ){
48918       pIter += getVarint32(pIter, nSize);
48919     }else{
48920       nSize = 0;
48921     }
48922
48923     /* pIter now points at the 64-bit integer key value, a variable length 
48924     ** integer. The following block moves pIter to point at the first byte
48925     ** past the end of the key value. */
48926     pEnd = &pIter[9];
48927     while( (*pIter++)&0x80 && pIter<pEnd );
48928   }else{
48929     pIter += getVarint32(pIter, nSize);
48930   }
48931
48932   testcase( nSize==pPage->maxLocal );
48933   testcase( nSize==pPage->maxLocal+1 );
48934   if( nSize>pPage->maxLocal ){
48935     int minLocal = pPage->minLocal;
48936     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
48937     testcase( nSize==pPage->maxLocal );
48938     testcase( nSize==pPage->maxLocal+1 );
48939     if( nSize>pPage->maxLocal ){
48940       nSize = minLocal;
48941     }
48942     nSize += 4;
48943   }
48944   nSize += (u32)(pIter - pCell);
48945
48946   /* The minimum size of any cell is 4 bytes. */
48947   if( nSize<4 ){
48948     nSize = 4;
48949   }
48950
48951   assert( nSize==debuginfo.nSize );
48952   return (u16)nSize;
48953 }
48954
48955 #ifdef SQLITE_DEBUG
48956 /* This variation on cellSizePtr() is used inside of assert() statements
48957 ** only. */
48958 static u16 cellSize(MemPage *pPage, int iCell){
48959   return cellSizePtr(pPage, findCell(pPage, iCell));
48960 }
48961 #endif
48962
48963 #ifndef SQLITE_OMIT_AUTOVACUUM
48964 /*
48965 ** If the cell pCell, part of page pPage contains a pointer
48966 ** to an overflow page, insert an entry into the pointer-map
48967 ** for the overflow page.
48968 */
48969 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48970   CellInfo info;
48971   if( *pRC ) return;
48972   assert( pCell!=0 );
48973   btreeParseCellPtr(pPage, pCell, &info);
48974   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48975   if( info.iOverflow ){
48976     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48977     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48978   }
48979 }
48980 #endif
48981
48982
48983 /*
48984 ** Defragment the page given.  All Cells are moved to the
48985 ** end of the page and all free space is collected into one
48986 ** big FreeBlk that occurs in between the header and cell
48987 ** pointer array and the cell content area.
48988 */
48989 static int defragmentPage(MemPage *pPage){
48990   int i;                     /* Loop counter */
48991   int pc;                    /* Address of a i-th cell */
48992   int hdr;                   /* Offset to the page header */
48993   int size;                  /* Size of a cell */
48994   int usableSize;            /* Number of usable bytes on a page */
48995   int cellOffset;            /* Offset to the cell pointer array */
48996   int cbrk;                  /* Offset to the cell content area */
48997   int nCell;                 /* Number of cells on the page */
48998   unsigned char *data;       /* The page data */
48999   unsigned char *temp;       /* Temp area for cell content */
49000   int iCellFirst;            /* First allowable cell index */
49001   int iCellLast;             /* Last possible cell index */
49002
49003
49004   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49005   assert( pPage->pBt!=0 );
49006   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49007   assert( pPage->nOverflow==0 );
49008   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49009   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49010   data = pPage->aData;
49011   hdr = pPage->hdrOffset;
49012   cellOffset = pPage->cellOffset;
49013   nCell = pPage->nCell;
49014   assert( nCell==get2byte(&data[hdr+3]) );
49015   usableSize = pPage->pBt->usableSize;
49016   cbrk = get2byte(&data[hdr+5]);
49017   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49018   cbrk = usableSize;
49019   iCellFirst = cellOffset + 2*nCell;
49020   iCellLast = usableSize - 4;
49021   for(i=0; i<nCell; i++){
49022     u8 *pAddr;     /* The i-th cell pointer */
49023     pAddr = &data[cellOffset + i*2];
49024     pc = get2byte(pAddr);
49025     testcase( pc==iCellFirst );
49026     testcase( pc==iCellLast );
49027 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49028     /* These conditions have already been verified in btreeInitPage()
49029     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
49030     */
49031     if( pc<iCellFirst || pc>iCellLast ){
49032       return SQLITE_CORRUPT_BKPT;
49033     }
49034 #endif
49035     assert( pc>=iCellFirst && pc<=iCellLast );
49036     size = cellSizePtr(pPage, &temp[pc]);
49037     cbrk -= size;
49038 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49039     if( cbrk<iCellFirst ){
49040       return SQLITE_CORRUPT_BKPT;
49041     }
49042 #else
49043     if( cbrk<iCellFirst || pc+size>usableSize ){
49044       return SQLITE_CORRUPT_BKPT;
49045     }
49046 #endif
49047     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49048     testcase( cbrk+size==usableSize );
49049     testcase( pc+size==usableSize );
49050     memcpy(&data[cbrk], &temp[pc], size);
49051     put2byte(pAddr, cbrk);
49052   }
49053   assert( cbrk>=iCellFirst );
49054   put2byte(&data[hdr+5], cbrk);
49055   data[hdr+1] = 0;
49056   data[hdr+2] = 0;
49057   data[hdr+7] = 0;
49058   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49059   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49060   if( cbrk-iCellFirst!=pPage->nFree ){
49061     return SQLITE_CORRUPT_BKPT;
49062   }
49063   return SQLITE_OK;
49064 }
49065
49066 /*
49067 ** Allocate nByte bytes of space from within the B-Tree page passed
49068 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49069 ** of the first byte of allocated space. Return either SQLITE_OK or
49070 ** an error code (usually SQLITE_CORRUPT).
49071 **
49072 ** The caller guarantees that there is sufficient space to make the
49073 ** allocation.  This routine might need to defragment in order to bring
49074 ** all the space together, however.  This routine will avoid using
49075 ** the first two bytes past the cell pointer area since presumably this
49076 ** allocation is being made in order to insert a new cell, so we will
49077 ** also end up needing a new cell pointer.
49078 */
49079 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49080   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
49081   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
49082   int nFrag;                           /* Number of fragmented bytes on pPage */
49083   int top;                             /* First byte of cell content area */
49084   int gap;        /* First byte of gap between cell pointers and cell content */
49085   int rc;         /* Integer return code */
49086   int usableSize; /* Usable size of the page */
49087   
49088   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49089   assert( pPage->pBt );
49090   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49091   assert( nByte>=0 );  /* Minimum cell size is 4 */
49092   assert( pPage->nFree>=nByte );
49093   assert( pPage->nOverflow==0 );
49094   usableSize = pPage->pBt->usableSize;
49095   assert( nByte < usableSize-8 );
49096
49097   nFrag = data[hdr+7];
49098   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49099   gap = pPage->cellOffset + 2*pPage->nCell;
49100   top = get2byteNotZero(&data[hdr+5]);
49101   if( gap>top ) return SQLITE_CORRUPT_BKPT;
49102   testcase( gap+2==top );
49103   testcase( gap+1==top );
49104   testcase( gap==top );
49105
49106   if( nFrag>=60 ){
49107     /* Always defragment highly fragmented pages */
49108     rc = defragmentPage(pPage);
49109     if( rc ) return rc;
49110     top = get2byteNotZero(&data[hdr+5]);
49111   }else if( gap+2<=top ){
49112     /* Search the freelist looking for a free slot big enough to satisfy 
49113     ** the request. The allocation is made from the first free slot in 
49114     ** the list that is large enough to accomadate it.
49115     */
49116     int pc, addr;
49117     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49118       int size;            /* Size of the free slot */
49119       if( pc>usableSize-4 || pc<addr+4 ){
49120         return SQLITE_CORRUPT_BKPT;
49121       }
49122       size = get2byte(&data[pc+2]);
49123       if( size>=nByte ){
49124         int x = size - nByte;
49125         testcase( x==4 );
49126         testcase( x==3 );
49127         if( x<4 ){
49128           /* Remove the slot from the free-list. Update the number of
49129           ** fragmented bytes within the page. */
49130           memcpy(&data[addr], &data[pc], 2);
49131           data[hdr+7] = (u8)(nFrag + x);
49132         }else if( size+pc > usableSize ){
49133           return SQLITE_CORRUPT_BKPT;
49134         }else{
49135           /* The slot remains on the free-list. Reduce its size to account
49136           ** for the portion used by the new allocation. */
49137           put2byte(&data[pc+2], x);
49138         }
49139         *pIdx = pc + x;
49140         return SQLITE_OK;
49141       }
49142     }
49143   }
49144
49145   /* Check to make sure there is enough space in the gap to satisfy
49146   ** the allocation.  If not, defragment.
49147   */
49148   testcase( gap+2+nByte==top );
49149   if( gap+2+nByte>top ){
49150     rc = defragmentPage(pPage);
49151     if( rc ) return rc;
49152     top = get2byteNotZero(&data[hdr+5]);
49153     assert( gap+nByte<=top );
49154   }
49155
49156
49157   /* Allocate memory from the gap in between the cell pointer array
49158   ** and the cell content area.  The btreeInitPage() call has already
49159   ** validated the freelist.  Given that the freelist is valid, there
49160   ** is no way that the allocation can extend off the end of the page.
49161   ** The assert() below verifies the previous sentence.
49162   */
49163   top -= nByte;
49164   put2byte(&data[hdr+5], top);
49165   assert( top+nByte <= (int)pPage->pBt->usableSize );
49166   *pIdx = top;
49167   return SQLITE_OK;
49168 }
49169
49170 /*
49171 ** Return a section of the pPage->aData to the freelist.
49172 ** The first byte of the new free block is pPage->aDisk[start]
49173 ** and the size of the block is "size" bytes.
49174 **
49175 ** Most of the effort here is involved in coalesing adjacent
49176 ** free blocks into a single big free block.
49177 */
49178 static int freeSpace(MemPage *pPage, int start, int size){
49179   int addr, pbegin, hdr;
49180   int iLast;                        /* Largest possible freeblock offset */
49181   unsigned char *data = pPage->aData;
49182
49183   assert( pPage->pBt!=0 );
49184   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49185   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49186   assert( (start + size) <= (int)pPage->pBt->usableSize );
49187   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49188   assert( size>=0 );   /* Minimum cell size is 4 */
49189
49190   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
49191     /* Overwrite deleted information with zeros when the secure_delete
49192     ** option is enabled */
49193     memset(&data[start], 0, size);
49194   }
49195
49196   /* Add the space back into the linked list of freeblocks.  Note that
49197   ** even though the freeblock list was checked by btreeInitPage(),
49198   ** btreeInitPage() did not detect overlapping cells or
49199   ** freeblocks that overlapped cells.   Nor does it detect when the
49200   ** cell content area exceeds the value in the page header.  If these
49201   ** situations arise, then subsequent insert operations might corrupt
49202   ** the freelist.  So we do need to check for corruption while scanning
49203   ** the freelist.
49204   */
49205   hdr = pPage->hdrOffset;
49206   addr = hdr + 1;
49207   iLast = pPage->pBt->usableSize - 4;
49208   assert( start<=iLast );
49209   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49210     if( pbegin<addr+4 ){
49211       return SQLITE_CORRUPT_BKPT;
49212     }
49213     addr = pbegin;
49214   }
49215   if( pbegin>iLast ){
49216     return SQLITE_CORRUPT_BKPT;
49217   }
49218   assert( pbegin>addr || pbegin==0 );
49219   put2byte(&data[addr], start);
49220   put2byte(&data[start], pbegin);
49221   put2byte(&data[start+2], size);
49222   pPage->nFree = pPage->nFree + (u16)size;
49223
49224   /* Coalesce adjacent free blocks */
49225   addr = hdr + 1;
49226   while( (pbegin = get2byte(&data[addr]))>0 ){
49227     int pnext, psize, x;
49228     assert( pbegin>addr );
49229     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49230     pnext = get2byte(&data[pbegin]);
49231     psize = get2byte(&data[pbegin+2]);
49232     if( pbegin + psize + 3 >= pnext && pnext>0 ){
49233       int frag = pnext - (pbegin+psize);
49234       if( (frag<0) || (frag>(int)data[hdr+7]) ){
49235         return SQLITE_CORRUPT_BKPT;
49236       }
49237       data[hdr+7] -= (u8)frag;
49238       x = get2byte(&data[pnext]);
49239       put2byte(&data[pbegin], x);
49240       x = pnext + get2byte(&data[pnext+2]) - pbegin;
49241       put2byte(&data[pbegin+2], x);
49242     }else{
49243       addr = pbegin;
49244     }
49245   }
49246
49247   /* If the cell content area begins with a freeblock, remove it. */
49248   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49249     int top;
49250     pbegin = get2byte(&data[hdr+1]);
49251     memcpy(&data[hdr+1], &data[pbegin], 2);
49252     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49253     put2byte(&data[hdr+5], top);
49254   }
49255   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49256   return SQLITE_OK;
49257 }
49258
49259 /*
49260 ** Decode the flags byte (the first byte of the header) for a page
49261 ** and initialize fields of the MemPage structure accordingly.
49262 **
49263 ** Only the following combinations are supported.  Anything different
49264 ** indicates a corrupt database files:
49265 **
49266 **         PTF_ZERODATA
49267 **         PTF_ZERODATA | PTF_LEAF
49268 **         PTF_LEAFDATA | PTF_INTKEY
49269 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49270 */
49271 static int decodeFlags(MemPage *pPage, int flagByte){
49272   BtShared *pBt;     /* A copy of pPage->pBt */
49273
49274   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49275   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49276   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
49277   flagByte &= ~PTF_LEAF;
49278   pPage->childPtrSize = 4-4*pPage->leaf;
49279   pBt = pPage->pBt;
49280   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49281     pPage->intKey = 1;
49282     pPage->hasData = pPage->leaf;
49283     pPage->maxLocal = pBt->maxLeaf;
49284     pPage->minLocal = pBt->minLeaf;
49285   }else if( flagByte==PTF_ZERODATA ){
49286     pPage->intKey = 0;
49287     pPage->hasData = 0;
49288     pPage->maxLocal = pBt->maxLocal;
49289     pPage->minLocal = pBt->minLocal;
49290   }else{
49291     return SQLITE_CORRUPT_BKPT;
49292   }
49293   pPage->max1bytePayload = pBt->max1bytePayload;
49294   return SQLITE_OK;
49295 }
49296
49297 /*
49298 ** Initialize the auxiliary information for a disk block.
49299 **
49300 ** Return SQLITE_OK on success.  If we see that the page does
49301 ** not contain a well-formed database page, then return 
49302 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
49303 ** guarantee that the page is well-formed.  It only shows that
49304 ** we failed to detect any corruption.
49305 */
49306 static int btreeInitPage(MemPage *pPage){
49307
49308   assert( pPage->pBt!=0 );
49309   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49310   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49311   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49312   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49313
49314   if( !pPage->isInit ){
49315     u16 pc;            /* Address of a freeblock within pPage->aData[] */
49316     u8 hdr;            /* Offset to beginning of page header */
49317     u8 *data;          /* Equal to pPage->aData */
49318     BtShared *pBt;        /* The main btree structure */
49319     int usableSize;    /* Amount of usable space on each page */
49320     u16 cellOffset;    /* Offset from start of page to first cell pointer */
49321     int nFree;         /* Number of unused bytes on the page */
49322     int top;           /* First byte of the cell content area */
49323     int iCellFirst;    /* First allowable cell or freeblock offset */
49324     int iCellLast;     /* Last possible cell or freeblock offset */
49325
49326     pBt = pPage->pBt;
49327
49328     hdr = pPage->hdrOffset;
49329     data = pPage->aData;
49330     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49331     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49332     pPage->maskPage = (u16)(pBt->pageSize - 1);
49333     pPage->nOverflow = 0;
49334     usableSize = pBt->usableSize;
49335     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49336     pPage->aDataEnd = &data[usableSize];
49337     pPage->aCellIdx = &data[cellOffset];
49338     top = get2byteNotZero(&data[hdr+5]);
49339     pPage->nCell = get2byte(&data[hdr+3]);
49340     if( pPage->nCell>MX_CELL(pBt) ){
49341       /* To many cells for a single page.  The page must be corrupt */
49342       return SQLITE_CORRUPT_BKPT;
49343     }
49344     testcase( pPage->nCell==MX_CELL(pBt) );
49345
49346     /* A malformed database page might cause us to read past the end
49347     ** of page when parsing a cell.  
49348     **
49349     ** The following block of code checks early to see if a cell extends
49350     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
49351     ** returned if it does.
49352     */
49353     iCellFirst = cellOffset + 2*pPage->nCell;
49354     iCellLast = usableSize - 4;
49355 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49356     {
49357       int i;            /* Index into the cell pointer array */
49358       int sz;           /* Size of a cell */
49359
49360       if( !pPage->leaf ) iCellLast--;
49361       for(i=0; i<pPage->nCell; i++){
49362         pc = get2byte(&data[cellOffset+i*2]);
49363         testcase( pc==iCellFirst );
49364         testcase( pc==iCellLast );
49365         if( pc<iCellFirst || pc>iCellLast ){
49366           return SQLITE_CORRUPT_BKPT;
49367         }
49368         sz = cellSizePtr(pPage, &data[pc]);
49369         testcase( pc+sz==usableSize );
49370         if( pc+sz>usableSize ){
49371           return SQLITE_CORRUPT_BKPT;
49372         }
49373       }
49374       if( !pPage->leaf ) iCellLast++;
49375     }  
49376 #endif
49377
49378     /* Compute the total free space on the page */
49379     pc = get2byte(&data[hdr+1]);
49380     nFree = data[hdr+7] + top;
49381     while( pc>0 ){
49382       u16 next, size;
49383       if( pc<iCellFirst || pc>iCellLast ){
49384         /* Start of free block is off the page */
49385         return SQLITE_CORRUPT_BKPT; 
49386       }
49387       next = get2byte(&data[pc]);
49388       size = get2byte(&data[pc+2]);
49389       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49390         /* Free blocks must be in ascending order. And the last byte of
49391         ** the free-block must lie on the database page.  */
49392         return SQLITE_CORRUPT_BKPT; 
49393       }
49394       nFree = nFree + size;
49395       pc = next;
49396     }
49397
49398     /* At this point, nFree contains the sum of the offset to the start
49399     ** of the cell-content area plus the number of free bytes within
49400     ** the cell-content area. If this is greater than the usable-size
49401     ** of the page, then the page must be corrupted. This check also
49402     ** serves to verify that the offset to the start of the cell-content
49403     ** area, according to the page header, lies within the page.
49404     */
49405     if( nFree>usableSize ){
49406       return SQLITE_CORRUPT_BKPT; 
49407     }
49408     pPage->nFree = (u16)(nFree - iCellFirst);
49409     pPage->isInit = 1;
49410   }
49411   return SQLITE_OK;
49412 }
49413
49414 /*
49415 ** Set up a raw page so that it looks like a database page holding
49416 ** no entries.
49417 */
49418 static void zeroPage(MemPage *pPage, int flags){
49419   unsigned char *data = pPage->aData;
49420   BtShared *pBt = pPage->pBt;
49421   u8 hdr = pPage->hdrOffset;
49422   u16 first;
49423
49424   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49425   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49426   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49427   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49428   assert( sqlite3_mutex_held(pBt->mutex) );
49429   if( pBt->btsFlags & BTS_SECURE_DELETE ){
49430     memset(&data[hdr], 0, pBt->usableSize - hdr);
49431   }
49432   data[hdr] = (char)flags;
49433   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49434   memset(&data[hdr+1], 0, 4);
49435   data[hdr+7] = 0;
49436   put2byte(&data[hdr+5], pBt->usableSize);
49437   pPage->nFree = (u16)(pBt->usableSize - first);
49438   decodeFlags(pPage, flags);
49439   pPage->hdrOffset = hdr;
49440   pPage->cellOffset = first;
49441   pPage->aDataEnd = &data[pBt->usableSize];
49442   pPage->aCellIdx = &data[first];
49443   pPage->nOverflow = 0;
49444   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49445   pPage->maskPage = (u16)(pBt->pageSize - 1);
49446   pPage->nCell = 0;
49447   pPage->isInit = 1;
49448 }
49449
49450
49451 /*
49452 ** Convert a DbPage obtained from the pager into a MemPage used by
49453 ** the btree layer.
49454 */
49455 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49456   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49457   pPage->aData = sqlite3PagerGetData(pDbPage);
49458   pPage->pDbPage = pDbPage;
49459   pPage->pBt = pBt;
49460   pPage->pgno = pgno;
49461   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49462   return pPage; 
49463 }
49464
49465 /*
49466 ** Get a page from the pager.  Initialize the MemPage.pBt and
49467 ** MemPage.aData elements if needed.
49468 **
49469 ** If the noContent flag is set, it means that we do not care about
49470 ** the content of the page at this time.  So do not go to the disk
49471 ** to fetch the content.  Just fill in the content with zeros for now.
49472 ** If in the future we call sqlite3PagerWrite() on this page, that
49473 ** means we have started to be concerned about content and the disk
49474 ** read should occur at that point.
49475 */
49476 static int btreeGetPage(
49477   BtShared *pBt,       /* The btree */
49478   Pgno pgno,           /* Number of the page to fetch */
49479   MemPage **ppPage,    /* Return the page in this parameter */
49480   int noContent        /* Do not load page content if true */
49481 ){
49482   int rc;
49483   DbPage *pDbPage;
49484
49485   assert( sqlite3_mutex_held(pBt->mutex) );
49486   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49487   if( rc ) return rc;
49488   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49489   return SQLITE_OK;
49490 }
49491
49492 /*
49493 ** Retrieve a page from the pager cache. If the requested page is not
49494 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49495 ** MemPage.aData elements if needed.
49496 */
49497 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49498   DbPage *pDbPage;
49499   assert( sqlite3_mutex_held(pBt->mutex) );
49500   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49501   if( pDbPage ){
49502     return btreePageFromDbPage(pDbPage, pgno, pBt);
49503   }
49504   return 0;
49505 }
49506
49507 /*
49508 ** Return the size of the database file in pages. If there is any kind of
49509 ** error, return ((unsigned int)-1).
49510 */
49511 static Pgno btreePagecount(BtShared *pBt){
49512   return pBt->nPage;
49513 }
49514 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
49515   assert( sqlite3BtreeHoldsMutex(p) );
49516   assert( ((p->pBt->nPage)&0x8000000)==0 );
49517   return (int)btreePagecount(p->pBt);
49518 }
49519
49520 /*
49521 ** Get a page from the pager and initialize it.  This routine is just a
49522 ** convenience wrapper around separate calls to btreeGetPage() and 
49523 ** btreeInitPage().
49524 **
49525 ** If an error occurs, then the value *ppPage is set to is undefined. It
49526 ** may remain unchanged, or it may be set to an invalid value.
49527 */
49528 static int getAndInitPage(
49529   BtShared *pBt,          /* The database file */
49530   Pgno pgno,           /* Number of the page to get */
49531   MemPage **ppPage     /* Write the page pointer here */
49532 ){
49533   int rc;
49534   assert( sqlite3_mutex_held(pBt->mutex) );
49535
49536   if( pgno>btreePagecount(pBt) ){
49537     rc = SQLITE_CORRUPT_BKPT;
49538   }else{
49539     rc = btreeGetPage(pBt, pgno, ppPage, 0);
49540     if( rc==SQLITE_OK ){
49541       rc = btreeInitPage(*ppPage);
49542       if( rc!=SQLITE_OK ){
49543         releasePage(*ppPage);
49544       }
49545     }
49546   }
49547
49548   testcase( pgno==0 );
49549   assert( pgno!=0 || rc==SQLITE_CORRUPT );
49550   return rc;
49551 }
49552
49553 /*
49554 ** Release a MemPage.  This should be called once for each prior
49555 ** call to btreeGetPage.
49556 */
49557 static void releasePage(MemPage *pPage){
49558   if( pPage ){
49559     assert( pPage->aData );
49560     assert( pPage->pBt );
49561     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49562     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
49563     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49564     sqlite3PagerUnref(pPage->pDbPage);
49565   }
49566 }
49567
49568 /*
49569 ** During a rollback, when the pager reloads information into the cache
49570 ** so that the cache is restored to its original state at the start of
49571 ** the transaction, for each page restored this routine is called.
49572 **
49573 ** This routine needs to reset the extra data section at the end of the
49574 ** page to agree with the restored data.
49575 */
49576 static void pageReinit(DbPage *pData){
49577   MemPage *pPage;
49578   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
49579   assert( sqlite3PagerPageRefcount(pData)>0 );
49580   if( pPage->isInit ){
49581     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49582     pPage->isInit = 0;
49583     if( sqlite3PagerPageRefcount(pData)>1 ){
49584       /* pPage might not be a btree page;  it might be an overflow page
49585       ** or ptrmap page or a free page.  In those cases, the following
49586       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
49587       ** But no harm is done by this.  And it is very important that
49588       ** btreeInitPage() be called on every btree page so we make
49589       ** the call for every page that comes in for re-initing. */
49590       btreeInitPage(pPage);
49591     }
49592   }
49593 }
49594
49595 /*
49596 ** Invoke the busy handler for a btree.
49597 */
49598 static int btreeInvokeBusyHandler(void *pArg){
49599   BtShared *pBt = (BtShared*)pArg;
49600   assert( pBt->db );
49601   assert( sqlite3_mutex_held(pBt->db->mutex) );
49602   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
49603 }
49604
49605 /*
49606 ** Open a database file.
49607 ** 
49608 ** zFilename is the name of the database file.  If zFilename is NULL
49609 ** then an ephemeral database is created.  The ephemeral database might
49610 ** be exclusively in memory, or it might use a disk-based memory cache.
49611 ** Either way, the ephemeral database will be automatically deleted 
49612 ** when sqlite3BtreeClose() is called.
49613 **
49614 ** If zFilename is ":memory:" then an in-memory database is created
49615 ** that is automatically destroyed when it is closed.
49616 **
49617 ** The "flags" parameter is a bitmask that might contain bits like
49618 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
49619 **
49620 ** If the database is already opened in the same database connection
49621 ** and we are in shared cache mode, then the open will fail with an
49622 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
49623 ** objects in the same database connection since doing so will lead
49624 ** to problems with locking.
49625 */
49626 SQLITE_PRIVATE int sqlite3BtreeOpen(
49627   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
49628   const char *zFilename,  /* Name of the file containing the BTree database */
49629   sqlite3 *db,            /* Associated database handle */
49630   Btree **ppBtree,        /* Pointer to new Btree object written here */
49631   int flags,              /* Options */
49632   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
49633 ){
49634   BtShared *pBt = 0;             /* Shared part of btree structure */
49635   Btree *p;                      /* Handle to return */
49636   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
49637   int rc = SQLITE_OK;            /* Result code from this function */
49638   u8 nReserve;                   /* Byte of unused space on each page */
49639   unsigned char zDbHeader[100];  /* Database header content */
49640
49641   /* True if opening an ephemeral, temporary database */
49642   const int isTempDb = zFilename==0 || zFilename[0]==0;
49643
49644   /* Set the variable isMemdb to true for an in-memory database, or 
49645   ** false for a file-based database.
49646   */
49647 #ifdef SQLITE_OMIT_MEMORYDB
49648   const int isMemdb = 0;
49649 #else
49650   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
49651                        || (isTempDb && sqlite3TempInMemory(db))
49652                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
49653 #endif
49654
49655   assert( db!=0 );
49656   assert( pVfs!=0 );
49657   assert( sqlite3_mutex_held(db->mutex) );
49658   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
49659
49660   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
49661   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
49662
49663   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
49664   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
49665
49666   if( isMemdb ){
49667     flags |= BTREE_MEMORY;
49668   }
49669   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
49670     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
49671   }
49672   p = sqlite3MallocZero(sizeof(Btree));
49673   if( !p ){
49674     return SQLITE_NOMEM;
49675   }
49676   p->inTrans = TRANS_NONE;
49677   p->db = db;
49678 #ifndef SQLITE_OMIT_SHARED_CACHE
49679   p->lock.pBtree = p;
49680   p->lock.iTable = 1;
49681 #endif
49682
49683 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49684   /*
49685   ** If this Btree is a candidate for shared cache, try to find an
49686   ** existing BtShared object that we can share with
49687   */
49688   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
49689     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
49690       int nFullPathname = pVfs->mxPathname+1;
49691       char *zFullPathname = sqlite3Malloc(nFullPathname);
49692       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
49693       p->sharable = 1;
49694       if( !zFullPathname ){
49695         sqlite3_free(p);
49696         return SQLITE_NOMEM;
49697       }
49698       if( isMemdb ){
49699         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
49700       }else{
49701         rc = sqlite3OsFullPathname(pVfs, zFilename,
49702                                    nFullPathname, zFullPathname);
49703         if( rc ){
49704           sqlite3_free(zFullPathname);
49705           sqlite3_free(p);
49706           return rc;
49707         }
49708       }
49709 #if SQLITE_THREADSAFE
49710       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
49711       sqlite3_mutex_enter(mutexOpen);
49712       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49713       sqlite3_mutex_enter(mutexShared);
49714 #endif
49715       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
49716         assert( pBt->nRef>0 );
49717         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
49718                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
49719           int iDb;
49720           for(iDb=db->nDb-1; iDb>=0; iDb--){
49721             Btree *pExisting = db->aDb[iDb].pBt;
49722             if( pExisting && pExisting->pBt==pBt ){
49723               sqlite3_mutex_leave(mutexShared);
49724               sqlite3_mutex_leave(mutexOpen);
49725               sqlite3_free(zFullPathname);
49726               sqlite3_free(p);
49727               return SQLITE_CONSTRAINT;
49728             }
49729           }
49730           p->pBt = pBt;
49731           pBt->nRef++;
49732           break;
49733         }
49734       }
49735       sqlite3_mutex_leave(mutexShared);
49736       sqlite3_free(zFullPathname);
49737     }
49738 #ifdef SQLITE_DEBUG
49739     else{
49740       /* In debug mode, we mark all persistent databases as sharable
49741       ** even when they are not.  This exercises the locking code and
49742       ** gives more opportunity for asserts(sqlite3_mutex_held())
49743       ** statements to find locking problems.
49744       */
49745       p->sharable = 1;
49746     }
49747 #endif
49748   }
49749 #endif
49750   if( pBt==0 ){
49751     /*
49752     ** The following asserts make sure that structures used by the btree are
49753     ** the right size.  This is to guard against size changes that result
49754     ** when compiling on a different architecture.
49755     */
49756     assert( sizeof(i64)==8 || sizeof(i64)==4 );
49757     assert( sizeof(u64)==8 || sizeof(u64)==4 );
49758     assert( sizeof(u32)==4 );
49759     assert( sizeof(u16)==2 );
49760     assert( sizeof(Pgno)==4 );
49761   
49762     pBt = sqlite3MallocZero( sizeof(*pBt) );
49763     if( pBt==0 ){
49764       rc = SQLITE_NOMEM;
49765       goto btree_open_out;
49766     }
49767     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
49768                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
49769     if( rc==SQLITE_OK ){
49770       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
49771     }
49772     if( rc!=SQLITE_OK ){
49773       goto btree_open_out;
49774     }
49775     pBt->openFlags = (u8)flags;
49776     pBt->db = db;
49777     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
49778     p->pBt = pBt;
49779   
49780     pBt->pCursor = 0;
49781     pBt->pPage1 = 0;
49782     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
49783 #ifdef SQLITE_SECURE_DELETE
49784     pBt->btsFlags |= BTS_SECURE_DELETE;
49785 #endif
49786     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
49787     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
49788          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
49789       pBt->pageSize = 0;
49790 #ifndef SQLITE_OMIT_AUTOVACUUM
49791       /* If the magic name ":memory:" will create an in-memory database, then
49792       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
49793       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
49794       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
49795       ** regular file-name. In this case the auto-vacuum applies as per normal.
49796       */
49797       if( zFilename && !isMemdb ){
49798         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
49799         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
49800       }
49801 #endif
49802       nReserve = 0;
49803     }else{
49804       nReserve = zDbHeader[20];
49805       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
49806 #ifndef SQLITE_OMIT_AUTOVACUUM
49807       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
49808       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
49809 #endif
49810     }
49811     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49812     if( rc ) goto btree_open_out;
49813     pBt->usableSize = pBt->pageSize - nReserve;
49814     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
49815    
49816 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49817     /* Add the new BtShared object to the linked list sharable BtShareds.
49818     */
49819     if( p->sharable ){
49820       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
49821       pBt->nRef = 1;
49822       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
49823       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
49824         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
49825         if( pBt->mutex==0 ){
49826           rc = SQLITE_NOMEM;
49827           db->mallocFailed = 0;
49828           goto btree_open_out;
49829         }
49830       }
49831       sqlite3_mutex_enter(mutexShared);
49832       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49833       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49834       sqlite3_mutex_leave(mutexShared);
49835     }
49836 #endif
49837   }
49838
49839 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49840   /* If the new Btree uses a sharable pBtShared, then link the new
49841   ** Btree into the list of all sharable Btrees for the same connection.
49842   ** The list is kept in ascending order by pBt address.
49843   */
49844   if( p->sharable ){
49845     int i;
49846     Btree *pSib;
49847     for(i=0; i<db->nDb; i++){
49848       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49849         while( pSib->pPrev ){ pSib = pSib->pPrev; }
49850         if( p->pBt<pSib->pBt ){
49851           p->pNext = pSib;
49852           p->pPrev = 0;
49853           pSib->pPrev = p;
49854         }else{
49855           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
49856             pSib = pSib->pNext;
49857           }
49858           p->pNext = pSib->pNext;
49859           p->pPrev = pSib;
49860           if( p->pNext ){
49861             p->pNext->pPrev = p;
49862           }
49863           pSib->pNext = p;
49864         }
49865         break;
49866       }
49867     }
49868   }
49869 #endif
49870   *ppBtree = p;
49871
49872 btree_open_out:
49873   if( rc!=SQLITE_OK ){
49874     if( pBt && pBt->pPager ){
49875       sqlite3PagerClose(pBt->pPager);
49876     }
49877     sqlite3_free(pBt);
49878     sqlite3_free(p);
49879     *ppBtree = 0;
49880   }else{
49881     /* If the B-Tree was successfully opened, set the pager-cache size to the
49882     ** default value. Except, when opening on an existing shared pager-cache,
49883     ** do not change the pager-cache size.
49884     */
49885     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
49886       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
49887     }
49888   }
49889   if( mutexOpen ){
49890     assert( sqlite3_mutex_held(mutexOpen) );
49891     sqlite3_mutex_leave(mutexOpen);
49892   }
49893   return rc;
49894 }
49895
49896 /*
49897 ** Decrement the BtShared.nRef counter.  When it reaches zero,
49898 ** remove the BtShared structure from the sharing list.  Return
49899 ** true if the BtShared.nRef counter reaches zero and return
49900 ** false if it is still positive.
49901 */
49902 static int removeFromSharingList(BtShared *pBt){
49903 #ifndef SQLITE_OMIT_SHARED_CACHE
49904   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
49905   BtShared *pList;
49906   int removed = 0;
49907
49908   assert( sqlite3_mutex_notheld(pBt->mutex) );
49909   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
49910   sqlite3_mutex_enter(pMaster);
49911   pBt->nRef--;
49912   if( pBt->nRef<=0 ){
49913     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
49914       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
49915     }else{
49916       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
49917       while( ALWAYS(pList) && pList->pNext!=pBt ){
49918         pList=pList->pNext;
49919       }
49920       if( ALWAYS(pList) ){
49921         pList->pNext = pBt->pNext;
49922       }
49923     }
49924     if( SQLITE_THREADSAFE ){
49925       sqlite3_mutex_free(pBt->mutex);
49926     }
49927     removed = 1;
49928   }
49929   sqlite3_mutex_leave(pMaster);
49930   return removed;
49931 #else
49932   return 1;
49933 #endif
49934 }
49935
49936 /*
49937 ** Make sure pBt->pTmpSpace points to an allocation of 
49938 ** MX_CELL_SIZE(pBt) bytes.
49939 */
49940 static void allocateTempSpace(BtShared *pBt){
49941   if( !pBt->pTmpSpace ){
49942     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
49943   }
49944 }
49945
49946 /*
49947 ** Free the pBt->pTmpSpace allocation
49948 */
49949 static void freeTempSpace(BtShared *pBt){
49950   sqlite3PageFree( pBt->pTmpSpace);
49951   pBt->pTmpSpace = 0;
49952 }
49953
49954 /*
49955 ** Close an open database and invalidate all cursors.
49956 */
49957 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49958   BtShared *pBt = p->pBt;
49959   BtCursor *pCur;
49960
49961   /* Close all cursors opened via this handle.  */
49962   assert( sqlite3_mutex_held(p->db->mutex) );
49963   sqlite3BtreeEnter(p);
49964   pCur = pBt->pCursor;
49965   while( pCur ){
49966     BtCursor *pTmp = pCur;
49967     pCur = pCur->pNext;
49968     if( pTmp->pBtree==p ){
49969       sqlite3BtreeCloseCursor(pTmp);
49970     }
49971   }
49972
49973   /* Rollback any active transaction and free the handle structure.
49974   ** The call to sqlite3BtreeRollback() drops any table-locks held by
49975   ** this handle.
49976   */
49977   sqlite3BtreeRollback(p, SQLITE_OK);
49978   sqlite3BtreeLeave(p);
49979
49980   /* If there are still other outstanding references to the shared-btree
49981   ** structure, return now. The remainder of this procedure cleans 
49982   ** up the shared-btree.
49983   */
49984   assert( p->wantToLock==0 && p->locked==0 );
49985   if( !p->sharable || removeFromSharingList(pBt) ){
49986     /* The pBt is no longer on the sharing list, so we can access
49987     ** it without having to hold the mutex.
49988     **
49989     ** Clean out and delete the BtShared object.
49990     */
49991     assert( !pBt->pCursor );
49992     sqlite3PagerClose(pBt->pPager);
49993     if( pBt->xFreeSchema && pBt->pSchema ){
49994       pBt->xFreeSchema(pBt->pSchema);
49995     }
49996     sqlite3DbFree(0, pBt->pSchema);
49997     freeTempSpace(pBt);
49998     sqlite3_free(pBt);
49999   }
50000
50001 #ifndef SQLITE_OMIT_SHARED_CACHE
50002   assert( p->wantToLock==0 );
50003   assert( p->locked==0 );
50004   if( p->pPrev ) p->pPrev->pNext = p->pNext;
50005   if( p->pNext ) p->pNext->pPrev = p->pPrev;
50006 #endif
50007
50008   sqlite3_free(p);
50009   return SQLITE_OK;
50010 }
50011
50012 /*
50013 ** Change the limit on the number of pages allowed in the cache.
50014 **
50015 ** The maximum number of cache pages is set to the absolute
50016 ** value of mxPage.  If mxPage is negative, the pager will
50017 ** operate asynchronously - it will not stop to do fsync()s
50018 ** to insure data is written to the disk surface before
50019 ** continuing.  Transactions still work if synchronous is off,
50020 ** and the database cannot be corrupted if this program
50021 ** crashes.  But if the operating system crashes or there is
50022 ** an abrupt power failure when synchronous is off, the database
50023 ** could be left in an inconsistent and unrecoverable state.
50024 ** Synchronous is on by default so database corruption is not
50025 ** normally a worry.
50026 */
50027 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50028   BtShared *pBt = p->pBt;
50029   assert( sqlite3_mutex_held(p->db->mutex) );
50030   sqlite3BtreeEnter(p);
50031   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50032   sqlite3BtreeLeave(p);
50033   return SQLITE_OK;
50034 }
50035
50036 /*
50037 ** Change the way data is synced to disk in order to increase or decrease
50038 ** how well the database resists damage due to OS crashes and power
50039 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
50040 ** there is a high probability of damage)  Level 2 is the default.  There
50041 ** is a very low but non-zero probability of damage.  Level 3 reduces the
50042 ** probability of damage to near zero but with a write performance reduction.
50043 */
50044 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50045 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50046   Btree *p,              /* The btree to set the safety level on */
50047   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
50048   int fullSync,          /* PRAGMA fullfsync. */
50049   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
50050 ){
50051   BtShared *pBt = p->pBt;
50052   assert( sqlite3_mutex_held(p->db->mutex) );
50053   assert( level>=1 && level<=3 );
50054   sqlite3BtreeEnter(p);
50055   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50056   sqlite3BtreeLeave(p);
50057   return SQLITE_OK;
50058 }
50059 #endif
50060
50061 /*
50062 ** Return TRUE if the given btree is set to safety level 1.  In other
50063 ** words, return TRUE if no sync() occurs on the disk files.
50064 */
50065 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50066   BtShared *pBt = p->pBt;
50067   int rc;
50068   assert( sqlite3_mutex_held(p->db->mutex) );  
50069   sqlite3BtreeEnter(p);
50070   assert( pBt && pBt->pPager );
50071   rc = sqlite3PagerNosync(pBt->pPager);
50072   sqlite3BtreeLeave(p);
50073   return rc;
50074 }
50075
50076 /*
50077 ** Change the default pages size and the number of reserved bytes per page.
50078 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
50079 ** without changing anything.
50080 **
50081 ** The page size must be a power of 2 between 512 and 65536.  If the page
50082 ** size supplied does not meet this constraint then the page size is not
50083 ** changed.
50084 **
50085 ** Page sizes are constrained to be a power of two so that the region
50086 ** of the database file used for locking (beginning at PENDING_BYTE,
50087 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50088 ** at the beginning of a page.
50089 **
50090 ** If parameter nReserve is less than zero, then the number of reserved
50091 ** bytes per page is left unchanged.
50092 **
50093 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
50094 ** and autovacuum mode can no longer be changed.
50095 */
50096 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50097   int rc = SQLITE_OK;
50098   BtShared *pBt = p->pBt;
50099   assert( nReserve>=-1 && nReserve<=255 );
50100   sqlite3BtreeEnter(p);
50101   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
50102     sqlite3BtreeLeave(p);
50103     return SQLITE_READONLY;
50104   }
50105   if( nReserve<0 ){
50106     nReserve = pBt->pageSize - pBt->usableSize;
50107   }
50108   assert( nReserve>=0 && nReserve<=255 );
50109   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50110         ((pageSize-1)&pageSize)==0 ){
50111     assert( (pageSize & 7)==0 );
50112     assert( !pBt->pPage1 && !pBt->pCursor );
50113     pBt->pageSize = (u32)pageSize;
50114     freeTempSpace(pBt);
50115   }
50116   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50117   pBt->usableSize = pBt->pageSize - (u16)nReserve;
50118   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50119   sqlite3BtreeLeave(p);
50120   return rc;
50121 }
50122
50123 /*
50124 ** Return the currently defined page size
50125 */
50126 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50127   return p->pBt->pageSize;
50128 }
50129
50130 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50131 /*
50132 ** Return the number of bytes of space at the end of every page that
50133 ** are intentually left unused.  This is the "reserved" space that is
50134 ** sometimes used by extensions.
50135 */
50136 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50137   int n;
50138   sqlite3BtreeEnter(p);
50139   n = p->pBt->pageSize - p->pBt->usableSize;
50140   sqlite3BtreeLeave(p);
50141   return n;
50142 }
50143
50144 /*
50145 ** Set the maximum page count for a database if mxPage is positive.
50146 ** No changes are made if mxPage is 0 or negative.
50147 ** Regardless of the value of mxPage, return the maximum page count.
50148 */
50149 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50150   int n;
50151   sqlite3BtreeEnter(p);
50152   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50153   sqlite3BtreeLeave(p);
50154   return n;
50155 }
50156
50157 /*
50158 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
50159 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
50160 ** setting after the change.
50161 */
50162 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50163   int b;
50164   if( p==0 ) return 0;
50165   sqlite3BtreeEnter(p);
50166   if( newFlag>=0 ){
50167     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
50168     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
50169   } 
50170   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
50171   sqlite3BtreeLeave(p);
50172   return b;
50173 }
50174 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50175
50176 /*
50177 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50178 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50179 ** is disabled. The default value for the auto-vacuum property is 
50180 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50181 */
50182 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50183 #ifdef SQLITE_OMIT_AUTOVACUUM
50184   return SQLITE_READONLY;
50185 #else
50186   BtShared *pBt = p->pBt;
50187   int rc = SQLITE_OK;
50188   u8 av = (u8)autoVacuum;
50189
50190   sqlite3BtreeEnter(p);
50191   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
50192     rc = SQLITE_READONLY;
50193   }else{
50194     pBt->autoVacuum = av ?1:0;
50195     pBt->incrVacuum = av==2 ?1:0;
50196   }
50197   sqlite3BtreeLeave(p);
50198   return rc;
50199 #endif
50200 }
50201
50202 /*
50203 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
50204 ** enabled 1 is returned. Otherwise 0.
50205 */
50206 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50207 #ifdef SQLITE_OMIT_AUTOVACUUM
50208   return BTREE_AUTOVACUUM_NONE;
50209 #else
50210   int rc;
50211   sqlite3BtreeEnter(p);
50212   rc = (
50213     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50214     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50215     BTREE_AUTOVACUUM_INCR
50216   );
50217   sqlite3BtreeLeave(p);
50218   return rc;
50219 #endif
50220 }
50221
50222
50223 /*
50224 ** Get a reference to pPage1 of the database file.  This will
50225 ** also acquire a readlock on that file.
50226 **
50227 ** SQLITE_OK is returned on success.  If the file is not a
50228 ** well-formed database file, then SQLITE_CORRUPT is returned.
50229 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
50230 ** is returned if we run out of memory. 
50231 */
50232 static int lockBtree(BtShared *pBt){
50233   int rc;              /* Result code from subfunctions */
50234   MemPage *pPage1;     /* Page 1 of the database file */
50235   int nPage;           /* Number of pages in the database */
50236   int nPageFile = 0;   /* Number of pages in the database file */
50237   int nPageHeader;     /* Number of pages in the database according to hdr */
50238
50239   assert( sqlite3_mutex_held(pBt->mutex) );
50240   assert( pBt->pPage1==0 );
50241   rc = sqlite3PagerSharedLock(pBt->pPager);
50242   if( rc!=SQLITE_OK ) return rc;
50243   rc = btreeGetPage(pBt, 1, &pPage1, 0);
50244   if( rc!=SQLITE_OK ) return rc;
50245
50246   /* Do some checking to help insure the file we opened really is
50247   ** a valid database file. 
50248   */
50249   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50250   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50251   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50252     nPage = nPageFile;
50253   }
50254   if( nPage>0 ){
50255     u32 pageSize;
50256     u32 usableSize;
50257     u8 *page1 = pPage1->aData;
50258     rc = SQLITE_NOTADB;
50259     if( memcmp(page1, zMagicHeader, 16)!=0 ){
50260       goto page1_init_failed;
50261     }
50262
50263 #ifdef SQLITE_OMIT_WAL
50264     if( page1[18]>1 ){
50265       pBt->btsFlags |= BTS_READ_ONLY;
50266     }
50267     if( page1[19]>1 ){
50268       goto page1_init_failed;
50269     }
50270 #else
50271     if( page1[18]>2 ){
50272       pBt->btsFlags |= BTS_READ_ONLY;
50273     }
50274     if( page1[19]>2 ){
50275       goto page1_init_failed;
50276     }
50277
50278     /* If the write version is set to 2, this database should be accessed
50279     ** in WAL mode. If the log is not already open, open it now. Then 
50280     ** return SQLITE_OK and return without populating BtShared.pPage1.
50281     ** The caller detects this and calls this function again. This is
50282     ** required as the version of page 1 currently in the page1 buffer
50283     ** may not be the latest version - there may be a newer one in the log
50284     ** file.
50285     */
50286     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
50287       int isOpen = 0;
50288       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50289       if( rc!=SQLITE_OK ){
50290         goto page1_init_failed;
50291       }else if( isOpen==0 ){
50292         releasePage(pPage1);
50293         return SQLITE_OK;
50294       }
50295       rc = SQLITE_NOTADB;
50296     }
50297 #endif
50298
50299     /* The maximum embedded fraction must be exactly 25%.  And the minimum
50300     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50301     ** The original design allowed these amounts to vary, but as of
50302     ** version 3.6.0, we require them to be fixed.
50303     */
50304     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50305       goto page1_init_failed;
50306     }
50307     pageSize = (page1[16]<<8) | (page1[17]<<16);
50308     if( ((pageSize-1)&pageSize)!=0
50309      || pageSize>SQLITE_MAX_PAGE_SIZE 
50310      || pageSize<=256 
50311     ){
50312       goto page1_init_failed;
50313     }
50314     assert( (pageSize & 7)==0 );
50315     usableSize = pageSize - page1[20];
50316     if( (u32)pageSize!=pBt->pageSize ){
50317       /* After reading the first page of the database assuming a page size
50318       ** of BtShared.pageSize, we have discovered that the page-size is
50319       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50320       ** zero and return SQLITE_OK. The caller will call this function
50321       ** again with the correct page-size.
50322       */
50323       releasePage(pPage1);
50324       pBt->usableSize = usableSize;
50325       pBt->pageSize = pageSize;
50326       freeTempSpace(pBt);
50327       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50328                                    pageSize-usableSize);
50329       return rc;
50330     }
50331     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50332       rc = SQLITE_CORRUPT_BKPT;
50333       goto page1_init_failed;
50334     }
50335     if( usableSize<480 ){
50336       goto page1_init_failed;
50337     }
50338     pBt->pageSize = pageSize;
50339     pBt->usableSize = usableSize;
50340 #ifndef SQLITE_OMIT_AUTOVACUUM
50341     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50342     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50343 #endif
50344   }
50345
50346   /* maxLocal is the maximum amount of payload to store locally for
50347   ** a cell.  Make sure it is small enough so that at least minFanout
50348   ** cells can will fit on one page.  We assume a 10-byte page header.
50349   ** Besides the payload, the cell must store:
50350   **     2-byte pointer to the cell
50351   **     4-byte child pointer
50352   **     9-byte nKey value
50353   **     4-byte nData value
50354   **     4-byte overflow page pointer
50355   ** So a cell consists of a 2-byte pointer, a header which is as much as
50356   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50357   ** page pointer.
50358   */
50359   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50360   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50361   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50362   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50363   if( pBt->maxLocal>127 ){
50364     pBt->max1bytePayload = 127;
50365   }else{
50366     pBt->max1bytePayload = (u8)pBt->maxLocal;
50367   }
50368   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50369   pBt->pPage1 = pPage1;
50370   pBt->nPage = nPage;
50371   return SQLITE_OK;
50372
50373 page1_init_failed:
50374   releasePage(pPage1);
50375   pBt->pPage1 = 0;
50376   return rc;
50377 }
50378
50379 /*
50380 ** If there are no outstanding cursors and we are not in the middle
50381 ** of a transaction but there is a read lock on the database, then
50382 ** this routine unrefs the first page of the database file which 
50383 ** has the effect of releasing the read lock.
50384 **
50385 ** If there is a transaction in progress, this routine is a no-op.
50386 */
50387 static void unlockBtreeIfUnused(BtShared *pBt){
50388   assert( sqlite3_mutex_held(pBt->mutex) );
50389   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50390   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50391     assert( pBt->pPage1->aData );
50392     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50393     assert( pBt->pPage1->aData );
50394     releasePage(pBt->pPage1);
50395     pBt->pPage1 = 0;
50396   }
50397 }
50398
50399 /*
50400 ** If pBt points to an empty file then convert that empty file
50401 ** into a new empty database by initializing the first page of
50402 ** the database.
50403 */
50404 static int newDatabase(BtShared *pBt){
50405   MemPage *pP1;
50406   unsigned char *data;
50407   int rc;
50408
50409   assert( sqlite3_mutex_held(pBt->mutex) );
50410   if( pBt->nPage>0 ){
50411     return SQLITE_OK;
50412   }
50413   pP1 = pBt->pPage1;
50414   assert( pP1!=0 );
50415   data = pP1->aData;
50416   rc = sqlite3PagerWrite(pP1->pDbPage);
50417   if( rc ) return rc;
50418   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50419   assert( sizeof(zMagicHeader)==16 );
50420   data[16] = (u8)((pBt->pageSize>>8)&0xff);
50421   data[17] = (u8)((pBt->pageSize>>16)&0xff);
50422   data[18] = 1;
50423   data[19] = 1;
50424   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50425   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50426   data[21] = 64;
50427   data[22] = 32;
50428   data[23] = 32;
50429   memset(&data[24], 0, 100-24);
50430   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50431   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50432 #ifndef SQLITE_OMIT_AUTOVACUUM
50433   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50434   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50435   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50436   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50437 #endif
50438   pBt->nPage = 1;
50439   data[31] = 1;
50440   return SQLITE_OK;
50441 }
50442
50443 /*
50444 ** Attempt to start a new transaction. A write-transaction
50445 ** is started if the second argument is nonzero, otherwise a read-
50446 ** transaction.  If the second argument is 2 or more and exclusive
50447 ** transaction is started, meaning that no other process is allowed
50448 ** to access the database.  A preexisting transaction may not be
50449 ** upgraded to exclusive by calling this routine a second time - the
50450 ** exclusivity flag only works for a new transaction.
50451 **
50452 ** A write-transaction must be started before attempting any 
50453 ** changes to the database.  None of the following routines 
50454 ** will work unless a transaction is started first:
50455 **
50456 **      sqlite3BtreeCreateTable()
50457 **      sqlite3BtreeCreateIndex()
50458 **      sqlite3BtreeClearTable()
50459 **      sqlite3BtreeDropTable()
50460 **      sqlite3BtreeInsert()
50461 **      sqlite3BtreeDelete()
50462 **      sqlite3BtreeUpdateMeta()
50463 **
50464 ** If an initial attempt to acquire the lock fails because of lock contention
50465 ** and the database was previously unlocked, then invoke the busy handler
50466 ** if there is one.  But if there was previously a read-lock, do not
50467 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
50468 ** returned when there is already a read-lock in order to avoid a deadlock.
50469 **
50470 ** Suppose there are two processes A and B.  A has a read lock and B has
50471 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50472 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50473 ** One or the other of the two processes must give way or there can be
50474 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50475 ** when A already has a read lock, we encourage A to give up and let B
50476 ** proceed.
50477 */
50478 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50479   sqlite3 *pBlock = 0;
50480   BtShared *pBt = p->pBt;
50481   int rc = SQLITE_OK;
50482
50483   sqlite3BtreeEnter(p);
50484   btreeIntegrity(p);
50485
50486   /* If the btree is already in a write-transaction, or it
50487   ** is already in a read-transaction and a read-transaction
50488   ** is requested, this is a no-op.
50489   */
50490   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
50491     goto trans_begun;
50492   }
50493
50494   /* Write transactions are not possible on a read-only database */
50495   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
50496     rc = SQLITE_READONLY;
50497     goto trans_begun;
50498   }
50499
50500 #ifndef SQLITE_OMIT_SHARED_CACHE
50501   /* If another database handle has already opened a write transaction 
50502   ** on this shared-btree structure and a second write transaction is
50503   ** requested, return SQLITE_LOCKED.
50504   */
50505   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
50506    || (pBt->btsFlags & BTS_PENDING)!=0
50507   ){
50508     pBlock = pBt->pWriter->db;
50509   }else if( wrflag>1 ){
50510     BtLock *pIter;
50511     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50512       if( pIter->pBtree!=p ){
50513         pBlock = pIter->pBtree->db;
50514         break;
50515       }
50516     }
50517   }
50518   if( pBlock ){
50519     sqlite3ConnectionBlocked(p->db, pBlock);
50520     rc = SQLITE_LOCKED_SHAREDCACHE;
50521     goto trans_begun;
50522   }
50523 #endif
50524
50525   /* Any read-only or read-write transaction implies a read-lock on 
50526   ** page 1. So if some other shared-cache client already has a write-lock 
50527   ** on page 1, the transaction cannot be opened. */
50528   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
50529   if( SQLITE_OK!=rc ) goto trans_begun;
50530
50531   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
50532   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
50533   do {
50534     /* Call lockBtree() until either pBt->pPage1 is populated or
50535     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
50536     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
50537     ** reading page 1 it discovers that the page-size of the database 
50538     ** file is not pBt->pageSize. In this case lockBtree() will update
50539     ** pBt->pageSize to the page-size of the file on disk.
50540     */
50541     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
50542
50543     if( rc==SQLITE_OK && wrflag ){
50544       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
50545         rc = SQLITE_READONLY;
50546       }else{
50547         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
50548         if( rc==SQLITE_OK ){
50549           rc = newDatabase(pBt);
50550         }
50551       }
50552     }
50553   
50554     if( rc!=SQLITE_OK ){
50555       unlockBtreeIfUnused(pBt);
50556     }
50557   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
50558           btreeInvokeBusyHandler(pBt) );
50559
50560   if( rc==SQLITE_OK ){
50561     if( p->inTrans==TRANS_NONE ){
50562       pBt->nTransaction++;
50563 #ifndef SQLITE_OMIT_SHARED_CACHE
50564       if( p->sharable ){
50565         assert( p->lock.pBtree==p && p->lock.iTable==1 );
50566         p->lock.eLock = READ_LOCK;
50567         p->lock.pNext = pBt->pLock;
50568         pBt->pLock = &p->lock;
50569       }
50570 #endif
50571     }
50572     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
50573     if( p->inTrans>pBt->inTransaction ){
50574       pBt->inTransaction = p->inTrans;
50575     }
50576     if( wrflag ){
50577       MemPage *pPage1 = pBt->pPage1;
50578 #ifndef SQLITE_OMIT_SHARED_CACHE
50579       assert( !pBt->pWriter );
50580       pBt->pWriter = p;
50581       pBt->btsFlags &= ~BTS_EXCLUSIVE;
50582       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
50583 #endif
50584
50585       /* If the db-size header field is incorrect (as it may be if an old
50586       ** client has been writing the database file), update it now. Doing
50587       ** this sooner rather than later means the database size can safely 
50588       ** re-read the database size from page 1 if a savepoint or transaction
50589       ** rollback occurs within the transaction.
50590       */
50591       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
50592         rc = sqlite3PagerWrite(pPage1->pDbPage);
50593         if( rc==SQLITE_OK ){
50594           put4byte(&pPage1->aData[28], pBt->nPage);
50595         }
50596       }
50597     }
50598   }
50599
50600
50601 trans_begun:
50602   if( rc==SQLITE_OK && wrflag ){
50603     /* This call makes sure that the pager has the correct number of
50604     ** open savepoints. If the second parameter is greater than 0 and
50605     ** the sub-journal is not already open, then it will be opened here.
50606     */
50607     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
50608   }
50609
50610   btreeIntegrity(p);
50611   sqlite3BtreeLeave(p);
50612   return rc;
50613 }
50614
50615 #ifndef SQLITE_OMIT_AUTOVACUUM
50616
50617 /*
50618 ** Set the pointer-map entries for all children of page pPage. Also, if
50619 ** pPage contains cells that point to overflow pages, set the pointer
50620 ** map entries for the overflow pages as well.
50621 */
50622 static int setChildPtrmaps(MemPage *pPage){
50623   int i;                             /* Counter variable */
50624   int nCell;                         /* Number of cells in page pPage */
50625   int rc;                            /* Return code */
50626   BtShared *pBt = pPage->pBt;
50627   u8 isInitOrig = pPage->isInit;
50628   Pgno pgno = pPage->pgno;
50629
50630   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50631   rc = btreeInitPage(pPage);
50632   if( rc!=SQLITE_OK ){
50633     goto set_child_ptrmaps_out;
50634   }
50635   nCell = pPage->nCell;
50636
50637   for(i=0; i<nCell; i++){
50638     u8 *pCell = findCell(pPage, i);
50639
50640     ptrmapPutOvflPtr(pPage, pCell, &rc);
50641
50642     if( !pPage->leaf ){
50643       Pgno childPgno = get4byte(pCell);
50644       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50645     }
50646   }
50647
50648   if( !pPage->leaf ){
50649     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50650     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50651   }
50652
50653 set_child_ptrmaps_out:
50654   pPage->isInit = isInitOrig;
50655   return rc;
50656 }
50657
50658 /*
50659 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
50660 ** that it points to iTo. Parameter eType describes the type of pointer to
50661 ** be modified, as  follows:
50662 **
50663 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
50664 **                   page of pPage.
50665 **
50666 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
50667 **                   page pointed to by one of the cells on pPage.
50668 **
50669 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
50670 **                   overflow page in the list.
50671 */
50672 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
50673   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50674   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50675   if( eType==PTRMAP_OVERFLOW2 ){
50676     /* The pointer is always the first 4 bytes of the page in this case.  */
50677     if( get4byte(pPage->aData)!=iFrom ){
50678       return SQLITE_CORRUPT_BKPT;
50679     }
50680     put4byte(pPage->aData, iTo);
50681   }else{
50682     u8 isInitOrig = pPage->isInit;
50683     int i;
50684     int nCell;
50685
50686     btreeInitPage(pPage);
50687     nCell = pPage->nCell;
50688
50689     for(i=0; i<nCell; i++){
50690       u8 *pCell = findCell(pPage, i);
50691       if( eType==PTRMAP_OVERFLOW1 ){
50692         CellInfo info;
50693         btreeParseCellPtr(pPage, pCell, &info);
50694         if( info.iOverflow
50695          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
50696          && iFrom==get4byte(&pCell[info.iOverflow])
50697         ){
50698           put4byte(&pCell[info.iOverflow], iTo);
50699           break;
50700         }
50701       }else{
50702         if( get4byte(pCell)==iFrom ){
50703           put4byte(pCell, iTo);
50704           break;
50705         }
50706       }
50707     }
50708   
50709     if( i==nCell ){
50710       if( eType!=PTRMAP_BTREE || 
50711           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
50712         return SQLITE_CORRUPT_BKPT;
50713       }
50714       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
50715     }
50716
50717     pPage->isInit = isInitOrig;
50718   }
50719   return SQLITE_OK;
50720 }
50721
50722
50723 /*
50724 ** Move the open database page pDbPage to location iFreePage in the 
50725 ** database. The pDbPage reference remains valid.
50726 **
50727 ** The isCommit flag indicates that there is no need to remember that
50728 ** the journal needs to be sync()ed before database page pDbPage->pgno 
50729 ** can be written to. The caller has already promised not to write to that
50730 ** page.
50731 */
50732 static int relocatePage(
50733   BtShared *pBt,           /* Btree */
50734   MemPage *pDbPage,        /* Open page to move */
50735   u8 eType,                /* Pointer map 'type' entry for pDbPage */
50736   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
50737   Pgno iFreePage,          /* The location to move pDbPage to */
50738   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
50739 ){
50740   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
50741   Pgno iDbPage = pDbPage->pgno;
50742   Pager *pPager = pBt->pPager;
50743   int rc;
50744
50745   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
50746       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
50747   assert( sqlite3_mutex_held(pBt->mutex) );
50748   assert( pDbPage->pBt==pBt );
50749
50750   /* Move page iDbPage from its current location to page number iFreePage */
50751   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
50752       iDbPage, iFreePage, iPtrPage, eType));
50753   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
50754   if( rc!=SQLITE_OK ){
50755     return rc;
50756   }
50757   pDbPage->pgno = iFreePage;
50758
50759   /* If pDbPage was a btree-page, then it may have child pages and/or cells
50760   ** that point to overflow pages. The pointer map entries for all these
50761   ** pages need to be changed.
50762   **
50763   ** If pDbPage is an overflow page, then the first 4 bytes may store a
50764   ** pointer to a subsequent overflow page. If this is the case, then
50765   ** the pointer map needs to be updated for the subsequent overflow page.
50766   */
50767   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
50768     rc = setChildPtrmaps(pDbPage);
50769     if( rc!=SQLITE_OK ){
50770       return rc;
50771     }
50772   }else{
50773     Pgno nextOvfl = get4byte(pDbPage->aData);
50774     if( nextOvfl!=0 ){
50775       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
50776       if( rc!=SQLITE_OK ){
50777         return rc;
50778       }
50779     }
50780   }
50781
50782   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
50783   ** that it points at iFreePage. Also fix the pointer map entry for
50784   ** iPtrPage.
50785   */
50786   if( eType!=PTRMAP_ROOTPAGE ){
50787     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
50788     if( rc!=SQLITE_OK ){
50789       return rc;
50790     }
50791     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
50792     if( rc!=SQLITE_OK ){
50793       releasePage(pPtrPage);
50794       return rc;
50795     }
50796     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
50797     releasePage(pPtrPage);
50798     if( rc==SQLITE_OK ){
50799       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
50800     }
50801   }
50802   return rc;
50803 }
50804
50805 /* Forward declaration required by incrVacuumStep(). */
50806 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
50807
50808 /*
50809 ** Perform a single step of an incremental-vacuum. If successful,
50810 ** return SQLITE_OK. If there is no work to do (and therefore no
50811 ** point in calling this function again), return SQLITE_DONE.
50812 **
50813 ** More specificly, this function attempts to re-organize the 
50814 ** database so that the last page of the file currently in use
50815 ** is no longer in use.
50816 **
50817 ** If the nFin parameter is non-zero, this function assumes
50818 ** that the caller will keep calling incrVacuumStep() until
50819 ** it returns SQLITE_DONE or an error, and that nFin is the
50820 ** number of pages the database file will contain after this 
50821 ** process is complete.  If nFin is zero, it is assumed that
50822 ** incrVacuumStep() will be called a finite amount of times
50823 ** which may or may not empty the freelist.  A full autovacuum
50824 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
50825 */
50826 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
50827   Pgno nFreeList;           /* Number of pages still on the free-list */
50828   int rc;
50829
50830   assert( sqlite3_mutex_held(pBt->mutex) );
50831   assert( iLastPg>nFin );
50832
50833   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
50834     u8 eType;
50835     Pgno iPtrPage;
50836
50837     nFreeList = get4byte(&pBt->pPage1->aData[36]);
50838     if( nFreeList==0 ){
50839       return SQLITE_DONE;
50840     }
50841
50842     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50843     if( rc!=SQLITE_OK ){
50844       return rc;
50845     }
50846     if( eType==PTRMAP_ROOTPAGE ){
50847       return SQLITE_CORRUPT_BKPT;
50848     }
50849
50850     if( eType==PTRMAP_FREEPAGE ){
50851       if( nFin==0 ){
50852         /* Remove the page from the files free-list. This is not required
50853         ** if nFin is non-zero. In that case, the free-list will be
50854         ** truncated to zero after this function returns, so it doesn't 
50855         ** matter if it still contains some garbage entries.
50856         */
50857         Pgno iFreePg;
50858         MemPage *pFreePg;
50859         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50860         if( rc!=SQLITE_OK ){
50861           return rc;
50862         }
50863         assert( iFreePg==iLastPg );
50864         releasePage(pFreePg);
50865       }
50866     } else {
50867       Pgno iFreePg;             /* Index of free page to move pLastPg to */
50868       MemPage *pLastPg;
50869
50870       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
50871       if( rc!=SQLITE_OK ){
50872         return rc;
50873       }
50874
50875       /* If nFin is zero, this loop runs exactly once and page pLastPg
50876       ** is swapped with the first free page pulled off the free list.
50877       **
50878       ** On the other hand, if nFin is greater than zero, then keep
50879       ** looping until a free-page located within the first nFin pages
50880       ** of the file is found.
50881       */
50882       do {
50883         MemPage *pFreePg;
50884         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
50885         if( rc!=SQLITE_OK ){
50886           releasePage(pLastPg);
50887           return rc;
50888         }
50889         releasePage(pFreePg);
50890       }while( nFin!=0 && iFreePg>nFin );
50891       assert( iFreePg<iLastPg );
50892       
50893       rc = sqlite3PagerWrite(pLastPg->pDbPage);
50894       if( rc==SQLITE_OK ){
50895         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
50896       }
50897       releasePage(pLastPg);
50898       if( rc!=SQLITE_OK ){
50899         return rc;
50900       }
50901     }
50902   }
50903
50904   if( nFin==0 ){
50905     iLastPg--;
50906     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
50907       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
50908         MemPage *pPg;
50909         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
50910         if( rc!=SQLITE_OK ){
50911           return rc;
50912         }
50913         rc = sqlite3PagerWrite(pPg->pDbPage);
50914         releasePage(pPg);
50915         if( rc!=SQLITE_OK ){
50916           return rc;
50917         }
50918       }
50919       iLastPg--;
50920     }
50921     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
50922     pBt->nPage = iLastPg;
50923   }
50924   return SQLITE_OK;
50925 }
50926
50927 /*
50928 ** A write-transaction must be opened before calling this function.
50929 ** It performs a single unit of work towards an incremental vacuum.
50930 **
50931 ** If the incremental vacuum is finished after this function has run,
50932 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
50933 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
50934 */
50935 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
50936   int rc;
50937   BtShared *pBt = p->pBt;
50938
50939   sqlite3BtreeEnter(p);
50940   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
50941   if( !pBt->autoVacuum ){
50942     rc = SQLITE_DONE;
50943   }else{
50944     invalidateAllOverflowCache(pBt);
50945     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
50946     if( rc==SQLITE_OK ){
50947       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50948       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
50949     }
50950   }
50951   sqlite3BtreeLeave(p);
50952   return rc;
50953 }
50954
50955 /*
50956 ** This routine is called prior to sqlite3PagerCommit when a transaction
50957 ** is commited for an auto-vacuum database.
50958 **
50959 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
50960 ** the database file should be truncated to during the commit process. 
50961 ** i.e. the database has been reorganized so that only the first *pnTrunc
50962 ** pages are in use.
50963 */
50964 static int autoVacuumCommit(BtShared *pBt){
50965   int rc = SQLITE_OK;
50966   Pager *pPager = pBt->pPager;
50967   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50968
50969   assert( sqlite3_mutex_held(pBt->mutex) );
50970   invalidateAllOverflowCache(pBt);
50971   assert(pBt->autoVacuum);
50972   if( !pBt->incrVacuum ){
50973     Pgno nFin;         /* Number of pages in database after autovacuuming */
50974     Pgno nFree;        /* Number of pages on the freelist initially */
50975     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
50976     Pgno iFree;        /* The next page to be freed */
50977     int nEntry;        /* Number of entries on one ptrmap page */
50978     Pgno nOrig;        /* Database size before freeing */
50979
50980     nOrig = btreePagecount(pBt);
50981     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50982       /* It is not possible to create a database for which the final page
50983       ** is either a pointer-map page or the pending-byte page. If one
50984       ** is encountered, this indicates corruption.
50985       */
50986       return SQLITE_CORRUPT_BKPT;
50987     }
50988
50989     nFree = get4byte(&pBt->pPage1->aData[36]);
50990     nEntry = pBt->usableSize/5;
50991     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50992     nFin = nOrig - nFree - nPtrmap;
50993     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50994       nFin--;
50995     }
50996     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50997       nFin--;
50998     }
50999     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51000
51001     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51002       rc = incrVacuumStep(pBt, nFin, iFree);
51003     }
51004     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51005       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51006       put4byte(&pBt->pPage1->aData[32], 0);
51007       put4byte(&pBt->pPage1->aData[36], 0);
51008       put4byte(&pBt->pPage1->aData[28], nFin);
51009       sqlite3PagerTruncateImage(pBt->pPager, nFin);
51010       pBt->nPage = nFin;
51011     }
51012     if( rc!=SQLITE_OK ){
51013       sqlite3PagerRollback(pPager);
51014     }
51015   }
51016
51017   assert( nRef==sqlite3PagerRefcount(pPager) );
51018   return rc;
51019 }
51020
51021 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51022 # define setChildPtrmaps(x) SQLITE_OK
51023 #endif
51024
51025 /*
51026 ** This routine does the first phase of a two-phase commit.  This routine
51027 ** causes a rollback journal to be created (if it does not already exist)
51028 ** and populated with enough information so that if a power loss occurs
51029 ** the database can be restored to its original state by playing back
51030 ** the journal.  Then the contents of the journal are flushed out to
51031 ** the disk.  After the journal is safely on oxide, the changes to the
51032 ** database are written into the database file and flushed to oxide.
51033 ** At the end of this call, the rollback journal still exists on the
51034 ** disk and we are still holding all locks, so the transaction has not
51035 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51036 ** commit process.
51037 **
51038 ** This call is a no-op if no write-transaction is currently active on pBt.
51039 **
51040 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51041 ** the name of a master journal file that should be written into the
51042 ** individual journal file, or is NULL, indicating no master journal file 
51043 ** (single database transaction).
51044 **
51045 ** When this is called, the master journal should already have been
51046 ** created, populated with this journal pointer and synced to disk.
51047 **
51048 ** Once this is routine has returned, the only thing required to commit
51049 ** the write-transaction for this database file is to delete the journal.
51050 */
51051 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51052   int rc = SQLITE_OK;
51053   if( p->inTrans==TRANS_WRITE ){
51054     BtShared *pBt = p->pBt;
51055     sqlite3BtreeEnter(p);
51056 #ifndef SQLITE_OMIT_AUTOVACUUM
51057     if( pBt->autoVacuum ){
51058       rc = autoVacuumCommit(pBt);
51059       if( rc!=SQLITE_OK ){
51060         sqlite3BtreeLeave(p);
51061         return rc;
51062       }
51063     }
51064 #endif
51065     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51066     sqlite3BtreeLeave(p);
51067   }
51068   return rc;
51069 }
51070
51071 /*
51072 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51073 ** at the conclusion of a transaction.
51074 */
51075 static void btreeEndTransaction(Btree *p){
51076   BtShared *pBt = p->pBt;
51077   assert( sqlite3BtreeHoldsMutex(p) );
51078
51079   btreeClearHasContent(pBt);
51080   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51081     /* If there are other active statements that belong to this database
51082     ** handle, downgrade to a read-only transaction. The other statements
51083     ** may still be reading from the database.  */
51084     downgradeAllSharedCacheTableLocks(p);
51085     p->inTrans = TRANS_READ;
51086   }else{
51087     /* If the handle had any kind of transaction open, decrement the 
51088     ** transaction count of the shared btree. If the transaction count 
51089     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51090     ** call below will unlock the pager.  */
51091     if( p->inTrans!=TRANS_NONE ){
51092       clearAllSharedCacheTableLocks(p);
51093       pBt->nTransaction--;
51094       if( 0==pBt->nTransaction ){
51095         pBt->inTransaction = TRANS_NONE;
51096       }
51097     }
51098
51099     /* Set the current transaction state to TRANS_NONE and unlock the 
51100     ** pager if this call closed the only read or write transaction.  */
51101     p->inTrans = TRANS_NONE;
51102     unlockBtreeIfUnused(pBt);
51103   }
51104
51105   btreeIntegrity(p);
51106 }
51107
51108 /*
51109 ** Commit the transaction currently in progress.
51110 **
51111 ** This routine implements the second phase of a 2-phase commit.  The
51112 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51113 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
51114 ** routine did all the work of writing information out to disk and flushing the
51115 ** contents so that they are written onto the disk platter.  All this
51116 ** routine has to do is delete or truncate or zero the header in the
51117 ** the rollback journal (which causes the transaction to commit) and
51118 ** drop locks.
51119 **
51120 ** Normally, if an error occurs while the pager layer is attempting to 
51121 ** finalize the underlying journal file, this function returns an error and
51122 ** the upper layer will attempt a rollback. However, if the second argument
51123 ** is non-zero then this b-tree transaction is part of a multi-file 
51124 ** transaction. In this case, the transaction has already been committed 
51125 ** (by deleting a master journal file) and the caller will ignore this 
51126 ** functions return code. So, even if an error occurs in the pager layer,
51127 ** reset the b-tree objects internal state to indicate that the write
51128 ** transaction has been closed. This is quite safe, as the pager will have
51129 ** transitioned to the error state.
51130 **
51131 ** This will release the write lock on the database file.  If there
51132 ** are no active cursors, it also releases the read lock.
51133 */
51134 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51135
51136   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51137   sqlite3BtreeEnter(p);
51138   btreeIntegrity(p);
51139
51140   /* If the handle has a write-transaction open, commit the shared-btrees 
51141   ** transaction and set the shared state to TRANS_READ.
51142   */
51143   if( p->inTrans==TRANS_WRITE ){
51144     int rc;
51145     BtShared *pBt = p->pBt;
51146     assert( pBt->inTransaction==TRANS_WRITE );
51147     assert( pBt->nTransaction>0 );
51148     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51149     if( rc!=SQLITE_OK && bCleanup==0 ){
51150       sqlite3BtreeLeave(p);
51151       return rc;
51152     }
51153     pBt->inTransaction = TRANS_READ;
51154   }
51155
51156   btreeEndTransaction(p);
51157   sqlite3BtreeLeave(p);
51158   return SQLITE_OK;
51159 }
51160
51161 /*
51162 ** Do both phases of a commit.
51163 */
51164 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51165   int rc;
51166   sqlite3BtreeEnter(p);
51167   rc = sqlite3BtreeCommitPhaseOne(p, 0);
51168   if( rc==SQLITE_OK ){
51169     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51170   }
51171   sqlite3BtreeLeave(p);
51172   return rc;
51173 }
51174
51175 #ifndef NDEBUG
51176 /*
51177 ** Return the number of write-cursors open on this handle. This is for use
51178 ** in assert() expressions, so it is only compiled if NDEBUG is not
51179 ** defined.
51180 **
51181 ** For the purposes of this routine, a write-cursor is any cursor that
51182 ** is capable of writing to the databse.  That means the cursor was
51183 ** originally opened for writing and the cursor has not be disabled
51184 ** by having its state changed to CURSOR_FAULT.
51185 */
51186 static int countWriteCursors(BtShared *pBt){
51187   BtCursor *pCur;
51188   int r = 0;
51189   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51190     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
51191   }
51192   return r;
51193 }
51194 #endif
51195
51196 /*
51197 ** This routine sets the state to CURSOR_FAULT and the error
51198 ** code to errCode for every cursor on BtShared that pBtree
51199 ** references.
51200 **
51201 ** Every cursor is tripped, including cursors that belong
51202 ** to other database connections that happen to be sharing
51203 ** the cache with pBtree.
51204 **
51205 ** This routine gets called when a rollback occurs.
51206 ** All cursors using the same cache must be tripped
51207 ** to prevent them from trying to use the btree after
51208 ** the rollback.  The rollback may have deleted tables
51209 ** or moved root pages, so it is not sufficient to
51210 ** save the state of the cursor.  The cursor must be
51211 ** invalidated.
51212 */
51213 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51214   BtCursor *p;
51215   if( pBtree==0 ) return;
51216   sqlite3BtreeEnter(pBtree);
51217   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51218     int i;
51219     sqlite3BtreeClearCursor(p);
51220     p->eState = CURSOR_FAULT;
51221     p->skipNext = errCode;
51222     for(i=0; i<=p->iPage; i++){
51223       releasePage(p->apPage[i]);
51224       p->apPage[i] = 0;
51225     }
51226   }
51227   sqlite3BtreeLeave(pBtree);
51228 }
51229
51230 /*
51231 ** Rollback the transaction in progress.  All cursors will be
51232 ** invalided by this operation.  Any attempt to use a cursor
51233 ** that was open at the beginning of this operation will result
51234 ** in an error.
51235 **
51236 ** This will release the write lock on the database file.  If there
51237 ** are no active cursors, it also releases the read lock.
51238 */
51239 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
51240   int rc;
51241   BtShared *pBt = p->pBt;
51242   MemPage *pPage1;
51243
51244   sqlite3BtreeEnter(p);
51245   if( tripCode==SQLITE_OK ){
51246     rc = tripCode = saveAllCursors(pBt, 0, 0);
51247   }else{
51248     rc = SQLITE_OK;
51249   }
51250   if( tripCode ){
51251     sqlite3BtreeTripAllCursors(p, tripCode);
51252   }
51253   btreeIntegrity(p);
51254
51255   if( p->inTrans==TRANS_WRITE ){
51256     int rc2;
51257
51258     assert( TRANS_WRITE==pBt->inTransaction );
51259     rc2 = sqlite3PagerRollback(pBt->pPager);
51260     if( rc2!=SQLITE_OK ){
51261       rc = rc2;
51262     }
51263
51264     /* The rollback may have destroyed the pPage1->aData value.  So
51265     ** call btreeGetPage() on page 1 again to make
51266     ** sure pPage1->aData is set correctly. */
51267     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51268       int nPage = get4byte(28+(u8*)pPage1->aData);
51269       testcase( nPage==0 );
51270       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51271       testcase( pBt->nPage!=nPage );
51272       pBt->nPage = nPage;
51273       releasePage(pPage1);
51274     }
51275     assert( countWriteCursors(pBt)==0 );
51276     pBt->inTransaction = TRANS_READ;
51277   }
51278
51279   btreeEndTransaction(p);
51280   sqlite3BtreeLeave(p);
51281   return rc;
51282 }
51283
51284 /*
51285 ** Start a statement subtransaction. The subtransaction can can be rolled
51286 ** back independently of the main transaction. You must start a transaction 
51287 ** before starting a subtransaction. The subtransaction is ended automatically 
51288 ** if the main transaction commits or rolls back.
51289 **
51290 ** Statement subtransactions are used around individual SQL statements
51291 ** that are contained within a BEGIN...COMMIT block.  If a constraint
51292 ** error occurs within the statement, the effect of that one statement
51293 ** can be rolled back without having to rollback the entire transaction.
51294 **
51295 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51296 ** value passed as the second parameter is the total number of savepoints,
51297 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51298 ** are no active savepoints and no other statement-transactions open,
51299 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51300 ** using the sqlite3BtreeSavepoint() function.
51301 */
51302 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51303   int rc;
51304   BtShared *pBt = p->pBt;
51305   sqlite3BtreeEnter(p);
51306   assert( p->inTrans==TRANS_WRITE );
51307   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
51308   assert( iStatement>0 );
51309   assert( iStatement>p->db->nSavepoint );
51310   assert( pBt->inTransaction==TRANS_WRITE );
51311   /* At the pager level, a statement transaction is a savepoint with
51312   ** an index greater than all savepoints created explicitly using
51313   ** SQL statements. It is illegal to open, release or rollback any
51314   ** such savepoints while the statement transaction savepoint is active.
51315   */
51316   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51317   sqlite3BtreeLeave(p);
51318   return rc;
51319 }
51320
51321 /*
51322 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51323 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51324 ** savepoint identified by parameter iSavepoint, depending on the value 
51325 ** of op.
51326 **
51327 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51328 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
51329 ** contents of the entire transaction are rolled back. This is different
51330 ** from a normal transaction rollback, as no locks are released and the
51331 ** transaction remains open.
51332 */
51333 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51334   int rc = SQLITE_OK;
51335   if( p && p->inTrans==TRANS_WRITE ){
51336     BtShared *pBt = p->pBt;
51337     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51338     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51339     sqlite3BtreeEnter(p);
51340     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51341     if( rc==SQLITE_OK ){
51342       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
51343         pBt->nPage = 0;
51344       }
51345       rc = newDatabase(pBt);
51346       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51347
51348       /* The database size was written into the offset 28 of the header
51349       ** when the transaction started, so we know that the value at offset
51350       ** 28 is nonzero. */
51351       assert( pBt->nPage>0 );
51352     }
51353     sqlite3BtreeLeave(p);
51354   }
51355   return rc;
51356 }
51357
51358 /*
51359 ** Create a new cursor for the BTree whose root is on the page
51360 ** iTable. If a read-only cursor is requested, it is assumed that
51361 ** the caller already has at least a read-only transaction open
51362 ** on the database already. If a write-cursor is requested, then
51363 ** the caller is assumed to have an open write transaction.
51364 **
51365 ** If wrFlag==0, then the cursor can only be used for reading.
51366 ** If wrFlag==1, then the cursor can be used for reading or for
51367 ** writing if other conditions for writing are also met.  These
51368 ** are the conditions that must be met in order for writing to
51369 ** be allowed:
51370 **
51371 ** 1:  The cursor must have been opened with wrFlag==1
51372 **
51373 ** 2:  Other database connections that share the same pager cache
51374 **     but which are not in the READ_UNCOMMITTED state may not have
51375 **     cursors open with wrFlag==0 on the same table.  Otherwise
51376 **     the changes made by this write cursor would be visible to
51377 **     the read cursors in the other database connection.
51378 **
51379 ** 3:  The database must be writable (not on read-only media)
51380 **
51381 ** 4:  There must be an active transaction.
51382 **
51383 ** No checking is done to make sure that page iTable really is the
51384 ** root page of a b-tree.  If it is not, then the cursor acquired
51385 ** will not work correctly.
51386 **
51387 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51388 ** on pCur to initialize the memory space prior to invoking this routine.
51389 */
51390 static int btreeCursor(
51391   Btree *p,                              /* The btree */
51392   int iTable,                            /* Root page of table to open */
51393   int wrFlag,                            /* 1 to write. 0 read-only */
51394   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
51395   BtCursor *pCur                         /* Space for new cursor */
51396 ){
51397   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
51398
51399   assert( sqlite3BtreeHoldsMutex(p) );
51400   assert( wrFlag==0 || wrFlag==1 );
51401
51402   /* The following assert statements verify that if this is a sharable 
51403   ** b-tree database, the connection is holding the required table locks, 
51404   ** and that no other connection has any open cursor that conflicts with 
51405   ** this lock.  */
51406   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51407   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51408
51409   /* Assert that the caller has opened the required transaction. */
51410   assert( p->inTrans>TRANS_NONE );
51411   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51412   assert( pBt->pPage1 && pBt->pPage1->aData );
51413
51414   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
51415     return SQLITE_READONLY;
51416   }
51417   if( iTable==1 && btreePagecount(pBt)==0 ){
51418     assert( wrFlag==0 );
51419     iTable = 0;
51420   }
51421
51422   /* Now that no other errors can occur, finish filling in the BtCursor
51423   ** variables and link the cursor into the BtShared list.  */
51424   pCur->pgnoRoot = (Pgno)iTable;
51425   pCur->iPage = -1;
51426   pCur->pKeyInfo = pKeyInfo;
51427   pCur->pBtree = p;
51428   pCur->pBt = pBt;
51429   pCur->wrFlag = (u8)wrFlag;
51430   pCur->pNext = pBt->pCursor;
51431   if( pCur->pNext ){
51432     pCur->pNext->pPrev = pCur;
51433   }
51434   pBt->pCursor = pCur;
51435   pCur->eState = CURSOR_INVALID;
51436   pCur->cachedRowid = 0;
51437   return SQLITE_OK;
51438 }
51439 SQLITE_PRIVATE int sqlite3BtreeCursor(
51440   Btree *p,                                   /* The btree */
51441   int iTable,                                 /* Root page of table to open */
51442   int wrFlag,                                 /* 1 to write. 0 read-only */
51443   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51444   BtCursor *pCur                              /* Write new cursor here */
51445 ){
51446   int rc;
51447   sqlite3BtreeEnter(p);
51448   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51449   sqlite3BtreeLeave(p);
51450   return rc;
51451 }
51452
51453 /*
51454 ** Return the size of a BtCursor object in bytes.
51455 **
51456 ** This interfaces is needed so that users of cursors can preallocate
51457 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51458 ** to users so they cannot do the sizeof() themselves - they must call
51459 ** this routine.
51460 */
51461 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51462   return ROUND8(sizeof(BtCursor));
51463 }
51464
51465 /*
51466 ** Initialize memory that will be converted into a BtCursor object.
51467 **
51468 ** The simple approach here would be to memset() the entire object
51469 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
51470 ** do not need to be zeroed and they are large, so we can save a lot
51471 ** of run-time by skipping the initialization of those elements.
51472 */
51473 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
51474   memset(p, 0, offsetof(BtCursor, iPage));
51475 }
51476
51477 /*
51478 ** Set the cached rowid value of every cursor in the same database file
51479 ** as pCur and having the same root page number as pCur.  The value is
51480 ** set to iRowid.
51481 **
51482 ** Only positive rowid values are considered valid for this cache.
51483 ** The cache is initialized to zero, indicating an invalid cache.
51484 ** A btree will work fine with zero or negative rowids.  We just cannot
51485 ** cache zero or negative rowids, which means tables that use zero or
51486 ** negative rowids might run a little slower.  But in practice, zero
51487 ** or negative rowids are very uncommon so this should not be a problem.
51488 */
51489 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
51490   BtCursor *p;
51491   for(p=pCur->pBt->pCursor; p; p=p->pNext){
51492     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
51493   }
51494   assert( pCur->cachedRowid==iRowid );
51495 }
51496
51497 /*
51498 ** Return the cached rowid for the given cursor.  A negative or zero
51499 ** return value indicates that the rowid cache is invalid and should be
51500 ** ignored.  If the rowid cache has never before been set, then a
51501 ** zero is returned.
51502 */
51503 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
51504   return pCur->cachedRowid;
51505 }
51506
51507 /*
51508 ** Close a cursor.  The read lock on the database file is released
51509 ** when the last cursor is closed.
51510 */
51511 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
51512   Btree *pBtree = pCur->pBtree;
51513   if( pBtree ){
51514     int i;
51515     BtShared *pBt = pCur->pBt;
51516     sqlite3BtreeEnter(pBtree);
51517     sqlite3BtreeClearCursor(pCur);
51518     if( pCur->pPrev ){
51519       pCur->pPrev->pNext = pCur->pNext;
51520     }else{
51521       pBt->pCursor = pCur->pNext;
51522     }
51523     if( pCur->pNext ){
51524       pCur->pNext->pPrev = pCur->pPrev;
51525     }
51526     for(i=0; i<=pCur->iPage; i++){
51527       releasePage(pCur->apPage[i]);
51528     }
51529     unlockBtreeIfUnused(pBt);
51530     invalidateOverflowCache(pCur);
51531     /* sqlite3_free(pCur); */
51532     sqlite3BtreeLeave(pBtree);
51533   }
51534   return SQLITE_OK;
51535 }
51536
51537 /*
51538 ** Make sure the BtCursor* given in the argument has a valid
51539 ** BtCursor.info structure.  If it is not already valid, call
51540 ** btreeParseCell() to fill it in.
51541 **
51542 ** BtCursor.info is a cache of the information in the current cell.
51543 ** Using this cache reduces the number of calls to btreeParseCell().
51544 **
51545 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
51546 ** compiler to crash when getCellInfo() is implemented as a macro.
51547 ** But there is a measureable speed advantage to using the macro on gcc
51548 ** (when less compiler optimizations like -Os or -O0 are used and the
51549 ** compiler is not doing agressive inlining.)  So we use a real function
51550 ** for MSVC and a macro for everything else.  Ticket #2457.
51551 */
51552 #ifndef NDEBUG
51553   static void assertCellInfo(BtCursor *pCur){
51554     CellInfo info;
51555     int iPage = pCur->iPage;
51556     memset(&info, 0, sizeof(info));
51557     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
51558     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
51559   }
51560 #else
51561   #define assertCellInfo(x)
51562 #endif
51563 #ifdef _MSC_VER
51564   /* Use a real function in MSVC to work around bugs in that compiler. */
51565   static void getCellInfo(BtCursor *pCur){
51566     if( pCur->info.nSize==0 ){
51567       int iPage = pCur->iPage;
51568       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
51569       pCur->validNKey = 1;
51570     }else{
51571       assertCellInfo(pCur);
51572     }
51573   }
51574 #else /* if not _MSC_VER */
51575   /* Use a macro in all other compilers so that the function is inlined */
51576 #define getCellInfo(pCur)                                                      \
51577   if( pCur->info.nSize==0 ){                                                   \
51578     int iPage = pCur->iPage;                                                   \
51579     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
51580     pCur->validNKey = 1;                                                       \
51581   }else{                                                                       \
51582     assertCellInfo(pCur);                                                      \
51583   }
51584 #endif /* _MSC_VER */
51585
51586 #ifndef NDEBUG  /* The next routine used only within assert() statements */
51587 /*
51588 ** Return true if the given BtCursor is valid.  A valid cursor is one
51589 ** that is currently pointing to a row in a (non-empty) table.
51590 ** This is a verification routine is used only within assert() statements.
51591 */
51592 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
51593   return pCur && pCur->eState==CURSOR_VALID;
51594 }
51595 #endif /* NDEBUG */
51596
51597 /*
51598 ** Set *pSize to the size of the buffer needed to hold the value of
51599 ** the key for the current entry.  If the cursor is not pointing
51600 ** to a valid entry, *pSize is set to 0. 
51601 **
51602 ** For a table with the INTKEY flag set, this routine returns the key
51603 ** itself, not the number of bytes in the key.
51604 **
51605 ** The caller must position the cursor prior to invoking this routine.
51606 ** 
51607 ** This routine cannot fail.  It always returns SQLITE_OK.  
51608 */
51609 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
51610   assert( cursorHoldsMutex(pCur) );
51611   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
51612   if( pCur->eState!=CURSOR_VALID ){
51613     *pSize = 0;
51614   }else{
51615     getCellInfo(pCur);
51616     *pSize = pCur->info.nKey;
51617   }
51618   return SQLITE_OK;
51619 }
51620
51621 /*
51622 ** Set *pSize to the number of bytes of data in the entry the
51623 ** cursor currently points to.
51624 **
51625 ** The caller must guarantee that the cursor is pointing to a non-NULL
51626 ** valid entry.  In other words, the calling procedure must guarantee
51627 ** that the cursor has Cursor.eState==CURSOR_VALID.
51628 **
51629 ** Failure is not possible.  This function always returns SQLITE_OK.
51630 ** It might just as well be a procedure (returning void) but we continue
51631 ** to return an integer result code for historical reasons.
51632 */
51633 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
51634   assert( cursorHoldsMutex(pCur) );
51635   assert( pCur->eState==CURSOR_VALID );
51636   getCellInfo(pCur);
51637   *pSize = pCur->info.nData;
51638   return SQLITE_OK;
51639 }
51640
51641 /*
51642 ** Given the page number of an overflow page in the database (parameter
51643 ** ovfl), this function finds the page number of the next page in the 
51644 ** linked list of overflow pages. If possible, it uses the auto-vacuum
51645 ** pointer-map data instead of reading the content of page ovfl to do so. 
51646 **
51647 ** If an error occurs an SQLite error code is returned. Otherwise:
51648 **
51649 ** The page number of the next overflow page in the linked list is 
51650 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
51651 ** list, *pPgnoNext is set to zero. 
51652 **
51653 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
51654 ** to page number pOvfl was obtained, then *ppPage is set to point to that
51655 ** reference. It is the responsibility of the caller to call releasePage()
51656 ** on *ppPage to free the reference. In no reference was obtained (because
51657 ** the pointer-map was used to obtain the value for *pPgnoNext), then
51658 ** *ppPage is set to zero.
51659 */
51660 static int getOverflowPage(
51661   BtShared *pBt,               /* The database file */
51662   Pgno ovfl,                   /* Current overflow page number */
51663   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
51664   Pgno *pPgnoNext              /* OUT: Next overflow page number */
51665 ){
51666   Pgno next = 0;
51667   MemPage *pPage = 0;
51668   int rc = SQLITE_OK;
51669
51670   assert( sqlite3_mutex_held(pBt->mutex) );
51671   assert(pPgnoNext);
51672
51673 #ifndef SQLITE_OMIT_AUTOVACUUM
51674   /* Try to find the next page in the overflow list using the
51675   ** autovacuum pointer-map pages. Guess that the next page in 
51676   ** the overflow list is page number (ovfl+1). If that guess turns 
51677   ** out to be wrong, fall back to loading the data of page 
51678   ** number ovfl to determine the next page number.
51679   */
51680   if( pBt->autoVacuum ){
51681     Pgno pgno;
51682     Pgno iGuess = ovfl+1;
51683     u8 eType;
51684
51685     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
51686       iGuess++;
51687     }
51688
51689     if( iGuess<=btreePagecount(pBt) ){
51690       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
51691       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
51692         next = iGuess;
51693         rc = SQLITE_DONE;
51694       }
51695     }
51696   }
51697 #endif
51698
51699   assert( next==0 || rc==SQLITE_DONE );
51700   if( rc==SQLITE_OK ){
51701     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
51702     assert( rc==SQLITE_OK || pPage==0 );
51703     if( rc==SQLITE_OK ){
51704       next = get4byte(pPage->aData);
51705     }
51706   }
51707
51708   *pPgnoNext = next;
51709   if( ppPage ){
51710     *ppPage = pPage;
51711   }else{
51712     releasePage(pPage);
51713   }
51714   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
51715 }
51716
51717 /*
51718 ** Copy data from a buffer to a page, or from a page to a buffer.
51719 **
51720 ** pPayload is a pointer to data stored on database page pDbPage.
51721 ** If argument eOp is false, then nByte bytes of data are copied
51722 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
51723 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
51724 ** of data are copied from the buffer pBuf to pPayload.
51725 **
51726 ** SQLITE_OK is returned on success, otherwise an error code.
51727 */
51728 static int copyPayload(
51729   void *pPayload,           /* Pointer to page data */
51730   void *pBuf,               /* Pointer to buffer */
51731   int nByte,                /* Number of bytes to copy */
51732   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
51733   DbPage *pDbPage           /* Page containing pPayload */
51734 ){
51735   if( eOp ){
51736     /* Copy data from buffer to page (a write operation) */
51737     int rc = sqlite3PagerWrite(pDbPage);
51738     if( rc!=SQLITE_OK ){
51739       return rc;
51740     }
51741     memcpy(pPayload, pBuf, nByte);
51742   }else{
51743     /* Copy data from page to buffer (a read operation) */
51744     memcpy(pBuf, pPayload, nByte);
51745   }
51746   return SQLITE_OK;
51747 }
51748
51749 /*
51750 ** This function is used to read or overwrite payload information
51751 ** for the entry that the pCur cursor is pointing to. If the eOp
51752 ** parameter is 0, this is a read operation (data copied into
51753 ** buffer pBuf). If it is non-zero, a write (data copied from
51754 ** buffer pBuf).
51755 **
51756 ** A total of "amt" bytes are read or written beginning at "offset".
51757 ** Data is read to or from the buffer pBuf.
51758 **
51759 ** The content being read or written might appear on the main page
51760 ** or be scattered out on multiple overflow pages.
51761 **
51762 ** If the BtCursor.isIncrblobHandle flag is set, and the current
51763 ** cursor entry uses one or more overflow pages, this function
51764 ** allocates space for and lazily popluates the overflow page-list 
51765 ** cache array (BtCursor.aOverflow). Subsequent calls use this
51766 ** cache to make seeking to the supplied offset more efficient.
51767 **
51768 ** Once an overflow page-list cache has been allocated, it may be
51769 ** invalidated if some other cursor writes to the same table, or if
51770 ** the cursor is moved to a different row. Additionally, in auto-vacuum
51771 ** mode, the following events may invalidate an overflow page-list cache.
51772 **
51773 **   * An incremental vacuum,
51774 **   * A commit in auto_vacuum="full" mode,
51775 **   * Creating a table (may require moving an overflow page).
51776 */
51777 static int accessPayload(
51778   BtCursor *pCur,      /* Cursor pointing to entry to read from */
51779   u32 offset,          /* Begin reading this far into payload */
51780   u32 amt,             /* Read this many bytes */
51781   unsigned char *pBuf, /* Write the bytes into this buffer */ 
51782   int eOp              /* zero to read. non-zero to write. */
51783 ){
51784   unsigned char *aPayload;
51785   int rc = SQLITE_OK;
51786   u32 nKey;
51787   int iIdx = 0;
51788   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
51789   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
51790
51791   assert( pPage );
51792   assert( pCur->eState==CURSOR_VALID );
51793   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51794   assert( cursorHoldsMutex(pCur) );
51795
51796   getCellInfo(pCur);
51797   aPayload = pCur->info.pCell + pCur->info.nHeader;
51798   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
51799
51800   if( NEVER(offset+amt > nKey+pCur->info.nData) 
51801    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
51802   ){
51803     /* Trying to read or write past the end of the data is an error */
51804     return SQLITE_CORRUPT_BKPT;
51805   }
51806
51807   /* Check if data must be read/written to/from the btree page itself. */
51808   if( offset<pCur->info.nLocal ){
51809     int a = amt;
51810     if( a+offset>pCur->info.nLocal ){
51811       a = pCur->info.nLocal - offset;
51812     }
51813     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
51814     offset = 0;
51815     pBuf += a;
51816     amt -= a;
51817   }else{
51818     offset -= pCur->info.nLocal;
51819   }
51820
51821   if( rc==SQLITE_OK && amt>0 ){
51822     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
51823     Pgno nextPage;
51824
51825     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
51826
51827 #ifndef SQLITE_OMIT_INCRBLOB
51828     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
51829     ** has not been allocated, allocate it now. The array is sized at
51830     ** one entry for each overflow page in the overflow chain. The
51831     ** page number of the first overflow page is stored in aOverflow[0],
51832     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
51833     ** (the cache is lazily populated).
51834     */
51835     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
51836       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51837       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51838       /* nOvfl is always positive.  If it were zero, fetchPayload would have
51839       ** been used instead of this routine. */
51840       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51841         rc = SQLITE_NOMEM;
51842       }
51843     }
51844
51845     /* If the overflow page-list cache has been allocated and the
51846     ** entry for the first required overflow page is valid, skip
51847     ** directly to it.
51848     */
51849     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51850       iIdx = (offset/ovflSize);
51851       nextPage = pCur->aOverflow[iIdx];
51852       offset = (offset%ovflSize);
51853     }
51854 #endif
51855
51856     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51857
51858 #ifndef SQLITE_OMIT_INCRBLOB
51859       /* If required, populate the overflow page-list cache. */
51860       if( pCur->aOverflow ){
51861         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51862         pCur->aOverflow[iIdx] = nextPage;
51863       }
51864 #endif
51865
51866       if( offset>=ovflSize ){
51867         /* The only reason to read this page is to obtain the page
51868         ** number for the next page in the overflow chain. The page
51869         ** data is not required. So first try to lookup the overflow
51870         ** page-list cache, if any, then fall back to the getOverflowPage()
51871         ** function.
51872         */
51873 #ifndef SQLITE_OMIT_INCRBLOB
51874         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
51875           nextPage = pCur->aOverflow[iIdx+1];
51876         } else 
51877 #endif
51878           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
51879         offset -= ovflSize;
51880       }else{
51881         /* Need to read this page properly. It contains some of the
51882         ** range of data that is being read (eOp==0) or written (eOp!=0).
51883         */
51884 #ifdef SQLITE_DIRECT_OVERFLOW_READ
51885         sqlite3_file *fd;
51886 #endif
51887         int a = amt;
51888         if( a + offset > ovflSize ){
51889           a = ovflSize - offset;
51890         }
51891
51892 #ifdef SQLITE_DIRECT_OVERFLOW_READ
51893         /* If all the following are true:
51894         **
51895         **   1) this is a read operation, and 
51896         **   2) data is required from the start of this overflow page, and
51897         **   3) the database is file-backed, and
51898         **   4) there is no open write-transaction, and
51899         **   5) the database is not a WAL database,
51900         **
51901         ** then data can be read directly from the database file into the
51902         ** output buffer, bypassing the page-cache altogether. This speeds
51903         ** up loading large records that span many overflow pages.
51904         */
51905         if( eOp==0                                             /* (1) */
51906          && offset==0                                          /* (2) */
51907          && pBt->inTransaction==TRANS_READ                     /* (4) */
51908          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
51909          && pBt->pPage1->aData[19]==0x01                       /* (5) */
51910         ){
51911           u8 aSave[4];
51912           u8 *aWrite = &pBuf[-4];
51913           memcpy(aSave, aWrite, 4);
51914           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
51915           nextPage = get4byte(aWrite);
51916           memcpy(aWrite, aSave, 4);
51917         }else
51918 #endif
51919
51920         {
51921           DbPage *pDbPage;
51922           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
51923           if( rc==SQLITE_OK ){
51924             aPayload = sqlite3PagerGetData(pDbPage);
51925             nextPage = get4byte(aPayload);
51926             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
51927             sqlite3PagerUnref(pDbPage);
51928             offset = 0;
51929           }
51930         }
51931         amt -= a;
51932         pBuf += a;
51933       }
51934     }
51935   }
51936
51937   if( rc==SQLITE_OK && amt>0 ){
51938     return SQLITE_CORRUPT_BKPT;
51939   }
51940   return rc;
51941 }
51942
51943 /*
51944 ** Read part of the key associated with cursor pCur.  Exactly
51945 ** "amt" bytes will be transfered into pBuf[].  The transfer
51946 ** begins at "offset".
51947 **
51948 ** The caller must ensure that pCur is pointing to a valid row
51949 ** in the table.
51950 **
51951 ** Return SQLITE_OK on success or an error code if anything goes
51952 ** wrong.  An error is returned if "offset+amt" is larger than
51953 ** the available payload.
51954 */
51955 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51956   assert( cursorHoldsMutex(pCur) );
51957   assert( pCur->eState==CURSOR_VALID );
51958   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51959   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51960   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
51961 }
51962
51963 /*
51964 ** Read part of the data associated with cursor pCur.  Exactly
51965 ** "amt" bytes will be transfered into pBuf[].  The transfer
51966 ** begins at "offset".
51967 **
51968 ** Return SQLITE_OK on success or an error code if anything goes
51969 ** wrong.  An error is returned if "offset+amt" is larger than
51970 ** the available payload.
51971 */
51972 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51973   int rc;
51974
51975 #ifndef SQLITE_OMIT_INCRBLOB
51976   if ( pCur->eState==CURSOR_INVALID ){
51977     return SQLITE_ABORT;
51978   }
51979 #endif
51980
51981   assert( cursorHoldsMutex(pCur) );
51982   rc = restoreCursorPosition(pCur);
51983   if( rc==SQLITE_OK ){
51984     assert( pCur->eState==CURSOR_VALID );
51985     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51986     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51987     rc = accessPayload(pCur, offset, amt, pBuf, 0);
51988   }
51989   return rc;
51990 }
51991
51992 /*
51993 ** Return a pointer to payload information from the entry that the 
51994 ** pCur cursor is pointing to.  The pointer is to the beginning of
51995 ** the key if skipKey==0 and it points to the beginning of data if
51996 ** skipKey==1.  The number of bytes of available key/data is written
51997 ** into *pAmt.  If *pAmt==0, then the value returned will not be
51998 ** a valid pointer.
51999 **
52000 ** This routine is an optimization.  It is common for the entire key
52001 ** and data to fit on the local page and for there to be no overflow
52002 ** pages.  When that is so, this routine can be used to access the
52003 ** key and data without making a copy.  If the key and/or data spills
52004 ** onto overflow pages, then accessPayload() must be used to reassemble
52005 ** the key/data and copy it into a preallocated buffer.
52006 **
52007 ** The pointer returned by this routine looks directly into the cached
52008 ** page of the database.  The data might change or move the next time
52009 ** any btree routine is called.
52010 */
52011 static const unsigned char *fetchPayload(
52012   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52013   int *pAmt,           /* Write the number of available bytes here */
52014   int skipKey          /* read beginning at data if this is true */
52015 ){
52016   unsigned char *aPayload;
52017   MemPage *pPage;
52018   u32 nKey;
52019   u32 nLocal;
52020
52021   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52022   assert( pCur->eState==CURSOR_VALID );
52023   assert( cursorHoldsMutex(pCur) );
52024   pPage = pCur->apPage[pCur->iPage];
52025   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52026   if( NEVER(pCur->info.nSize==0) ){
52027     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52028                    &pCur->info);
52029   }
52030   aPayload = pCur->info.pCell;
52031   aPayload += pCur->info.nHeader;
52032   if( pPage->intKey ){
52033     nKey = 0;
52034   }else{
52035     nKey = (int)pCur->info.nKey;
52036   }
52037   if( skipKey ){
52038     aPayload += nKey;
52039     nLocal = pCur->info.nLocal - nKey;
52040   }else{
52041     nLocal = pCur->info.nLocal;
52042     assert( nLocal<=nKey );
52043   }
52044   *pAmt = nLocal;
52045   return aPayload;
52046 }
52047
52048
52049 /*
52050 ** For the entry that cursor pCur is point to, return as
52051 ** many bytes of the key or data as are available on the local
52052 ** b-tree page.  Write the number of available bytes into *pAmt.
52053 **
52054 ** The pointer returned is ephemeral.  The key/data may move
52055 ** or be destroyed on the next call to any Btree routine,
52056 ** including calls from other threads against the same cache.
52057 ** Hence, a mutex on the BtShared should be held prior to calling
52058 ** this routine.
52059 **
52060 ** These routines is used to get quick access to key and data
52061 ** in the common case where no overflow pages are used.
52062 */
52063 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52064   const void *p = 0;
52065   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52066   assert( cursorHoldsMutex(pCur) );
52067   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52068     p = (const void*)fetchPayload(pCur, pAmt, 0);
52069   }
52070   return p;
52071 }
52072 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52073   const void *p = 0;
52074   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52075   assert( cursorHoldsMutex(pCur) );
52076   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52077     p = (const void*)fetchPayload(pCur, pAmt, 1);
52078   }
52079   return p;
52080 }
52081
52082
52083 /*
52084 ** Move the cursor down to a new child page.  The newPgno argument is the
52085 ** page number of the child page to move to.
52086 **
52087 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52088 ** the new child page does not match the flags field of the parent (i.e.
52089 ** if an intkey page appears to be the parent of a non-intkey page, or
52090 ** vice-versa).
52091 */
52092 static int moveToChild(BtCursor *pCur, u32 newPgno){
52093   int rc;
52094   int i = pCur->iPage;
52095   MemPage *pNewPage;
52096   BtShared *pBt = pCur->pBt;
52097
52098   assert( cursorHoldsMutex(pCur) );
52099   assert( pCur->eState==CURSOR_VALID );
52100   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52101   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52102     return SQLITE_CORRUPT_BKPT;
52103   }
52104   rc = getAndInitPage(pBt, newPgno, &pNewPage);
52105   if( rc ) return rc;
52106   pCur->apPage[i+1] = pNewPage;
52107   pCur->aiIdx[i+1] = 0;
52108   pCur->iPage++;
52109
52110   pCur->info.nSize = 0;
52111   pCur->validNKey = 0;
52112   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52113     return SQLITE_CORRUPT_BKPT;
52114   }
52115   return SQLITE_OK;
52116 }
52117
52118 #if 0
52119 /*
52120 ** Page pParent is an internal (non-leaf) tree page. This function 
52121 ** asserts that page number iChild is the left-child if the iIdx'th
52122 ** cell in page pParent. Or, if iIdx is equal to the total number of
52123 ** cells in pParent, that page number iChild is the right-child of
52124 ** the page.
52125 */
52126 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52127   assert( iIdx<=pParent->nCell );
52128   if( iIdx==pParent->nCell ){
52129     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52130   }else{
52131     assert( get4byte(findCell(pParent, iIdx))==iChild );
52132   }
52133 }
52134 #else
52135 #  define assertParentIndex(x,y,z) 
52136 #endif
52137
52138 /*
52139 ** Move the cursor up to the parent page.
52140 **
52141 ** pCur->idx is set to the cell index that contains the pointer
52142 ** to the page we are coming from.  If we are coming from the
52143 ** right-most child page then pCur->idx is set to one more than
52144 ** the largest cell index.
52145 */
52146 static void moveToParent(BtCursor *pCur){
52147   assert( cursorHoldsMutex(pCur) );
52148   assert( pCur->eState==CURSOR_VALID );
52149   assert( pCur->iPage>0 );
52150   assert( pCur->apPage[pCur->iPage] );
52151
52152   /* UPDATE: It is actually possible for the condition tested by the assert
52153   ** below to be untrue if the database file is corrupt. This can occur if
52154   ** one cursor has modified page pParent while a reference to it is held 
52155   ** by a second cursor. Which can only happen if a single page is linked
52156   ** into more than one b-tree structure in a corrupt database.  */
52157 #if 0
52158   assertParentIndex(
52159     pCur->apPage[pCur->iPage-1], 
52160     pCur->aiIdx[pCur->iPage-1], 
52161     pCur->apPage[pCur->iPage]->pgno
52162   );
52163 #endif
52164   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
52165
52166   releasePage(pCur->apPage[pCur->iPage]);
52167   pCur->iPage--;
52168   pCur->info.nSize = 0;
52169   pCur->validNKey = 0;
52170 }
52171
52172 /*
52173 ** Move the cursor to point to the root page of its b-tree structure.
52174 **
52175 ** If the table has a virtual root page, then the cursor is moved to point
52176 ** to the virtual root page instead of the actual root page. A table has a
52177 ** virtual root page when the actual root page contains no cells and a 
52178 ** single child page. This can only happen with the table rooted at page 1.
52179 **
52180 ** If the b-tree structure is empty, the cursor state is set to 
52181 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52182 ** cell located on the root (or virtual root) page and the cursor state
52183 ** is set to CURSOR_VALID.
52184 **
52185 ** If this function returns successfully, it may be assumed that the
52186 ** page-header flags indicate that the [virtual] root-page is the expected 
52187 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52188 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52189 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
52190 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52191 ** b-tree).
52192 */
52193 static int moveToRoot(BtCursor *pCur){
52194   MemPage *pRoot;
52195   int rc = SQLITE_OK;
52196   Btree *p = pCur->pBtree;
52197   BtShared *pBt = p->pBt;
52198
52199   assert( cursorHoldsMutex(pCur) );
52200   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52201   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
52202   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
52203   if( pCur->eState>=CURSOR_REQUIRESEEK ){
52204     if( pCur->eState==CURSOR_FAULT ){
52205       assert( pCur->skipNext!=SQLITE_OK );
52206       return pCur->skipNext;
52207     }
52208     sqlite3BtreeClearCursor(pCur);
52209   }
52210
52211   if( pCur->iPage>=0 ){
52212     int i;
52213     for(i=1; i<=pCur->iPage; i++){
52214       releasePage(pCur->apPage[i]);
52215     }
52216     pCur->iPage = 0;
52217   }else if( pCur->pgnoRoot==0 ){
52218     pCur->eState = CURSOR_INVALID;
52219     return SQLITE_OK;
52220   }else{
52221     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52222     if( rc!=SQLITE_OK ){
52223       pCur->eState = CURSOR_INVALID;
52224       return rc;
52225     }
52226     pCur->iPage = 0;
52227
52228     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52229     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52230     ** NULL, the caller expects a table b-tree. If this is not the case,
52231     ** return an SQLITE_CORRUPT error.  */
52232     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52233     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52234       return SQLITE_CORRUPT_BKPT;
52235     }
52236   }
52237
52238   /* Assert that the root page is of the correct type. This must be the
52239   ** case as the call to this function that loaded the root-page (either
52240   ** this call or a previous invocation) would have detected corruption 
52241   ** if the assumption were not true, and it is not possible for the flags 
52242   ** byte to have been modified while this cursor is holding a reference
52243   ** to the page.  */
52244   pRoot = pCur->apPage[0];
52245   assert( pRoot->pgno==pCur->pgnoRoot );
52246   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52247
52248   pCur->aiIdx[0] = 0;
52249   pCur->info.nSize = 0;
52250   pCur->atLast = 0;
52251   pCur->validNKey = 0;
52252
52253   if( pRoot->nCell==0 && !pRoot->leaf ){
52254     Pgno subpage;
52255     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52256     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52257     pCur->eState = CURSOR_VALID;
52258     rc = moveToChild(pCur, subpage);
52259   }else{
52260     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52261   }
52262   return rc;
52263 }
52264
52265 /*
52266 ** Move the cursor down to the left-most leaf entry beneath the
52267 ** entry to which it is currently pointing.
52268 **
52269 ** The left-most leaf is the one with the smallest key - the first
52270 ** in ascending order.
52271 */
52272 static int moveToLeftmost(BtCursor *pCur){
52273   Pgno pgno;
52274   int rc = SQLITE_OK;
52275   MemPage *pPage;
52276
52277   assert( cursorHoldsMutex(pCur) );
52278   assert( pCur->eState==CURSOR_VALID );
52279   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52280     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52281     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52282     rc = moveToChild(pCur, pgno);
52283   }
52284   return rc;
52285 }
52286
52287 /*
52288 ** Move the cursor down to the right-most leaf entry beneath the
52289 ** page to which it is currently pointing.  Notice the difference
52290 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
52291 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52292 ** finds the right-most entry beneath the *page*.
52293 **
52294 ** The right-most entry is the one with the largest key - the last
52295 ** key in ascending order.
52296 */
52297 static int moveToRightmost(BtCursor *pCur){
52298   Pgno pgno;
52299   int rc = SQLITE_OK;
52300   MemPage *pPage = 0;
52301
52302   assert( cursorHoldsMutex(pCur) );
52303   assert( pCur->eState==CURSOR_VALID );
52304   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52305     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52306     pCur->aiIdx[pCur->iPage] = pPage->nCell;
52307     rc = moveToChild(pCur, pgno);
52308   }
52309   if( rc==SQLITE_OK ){
52310     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52311     pCur->info.nSize = 0;
52312     pCur->validNKey = 0;
52313   }
52314   return rc;
52315 }
52316
52317 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
52318 ** on success.  Set *pRes to 0 if the cursor actually points to something
52319 ** or set *pRes to 1 if the table is empty.
52320 */
52321 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52322   int rc;
52323
52324   assert( cursorHoldsMutex(pCur) );
52325   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52326   rc = moveToRoot(pCur);
52327   if( rc==SQLITE_OK ){
52328     if( pCur->eState==CURSOR_INVALID ){
52329       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52330       *pRes = 1;
52331     }else{
52332       assert( pCur->apPage[pCur->iPage]->nCell>0 );
52333       *pRes = 0;
52334       rc = moveToLeftmost(pCur);
52335     }
52336   }
52337   return rc;
52338 }
52339
52340 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
52341 ** on success.  Set *pRes to 0 if the cursor actually points to something
52342 ** or set *pRes to 1 if the table is empty.
52343 */
52344 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52345   int rc;
52346  
52347   assert( cursorHoldsMutex(pCur) );
52348   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52349
52350   /* If the cursor already points to the last entry, this is a no-op. */
52351   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52352 #ifdef SQLITE_DEBUG
52353     /* This block serves to assert() that the cursor really does point 
52354     ** to the last entry in the b-tree. */
52355     int ii;
52356     for(ii=0; ii<pCur->iPage; ii++){
52357       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52358     }
52359     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52360     assert( pCur->apPage[pCur->iPage]->leaf );
52361 #endif
52362     return SQLITE_OK;
52363   }
52364
52365   rc = moveToRoot(pCur);
52366   if( rc==SQLITE_OK ){
52367     if( CURSOR_INVALID==pCur->eState ){
52368       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52369       *pRes = 1;
52370     }else{
52371       assert( pCur->eState==CURSOR_VALID );
52372       *pRes = 0;
52373       rc = moveToRightmost(pCur);
52374       pCur->atLast = rc==SQLITE_OK ?1:0;
52375     }
52376   }
52377   return rc;
52378 }
52379
52380 /* Move the cursor so that it points to an entry near the key 
52381 ** specified by pIdxKey or intKey.   Return a success code.
52382 **
52383 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
52384 ** must be NULL.  For index tables, pIdxKey is used and intKey
52385 ** is ignored.
52386 **
52387 ** If an exact match is not found, then the cursor is always
52388 ** left pointing at a leaf page which would hold the entry if it
52389 ** were present.  The cursor might point to an entry that comes
52390 ** before or after the key.
52391 **
52392 ** An integer is written into *pRes which is the result of
52393 ** comparing the key with the entry to which the cursor is 
52394 ** pointing.  The meaning of the integer written into
52395 ** *pRes is as follows:
52396 **
52397 **     *pRes<0      The cursor is left pointing at an entry that
52398 **                  is smaller than intKey/pIdxKey or if the table is empty
52399 **                  and the cursor is therefore left point to nothing.
52400 **
52401 **     *pRes==0     The cursor is left pointing at an entry that
52402 **                  exactly matches intKey/pIdxKey.
52403 **
52404 **     *pRes>0      The cursor is left pointing at an entry that
52405 **                  is larger than intKey/pIdxKey.
52406 **
52407 */
52408 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52409   BtCursor *pCur,          /* The cursor to be moved */
52410   UnpackedRecord *pIdxKey, /* Unpacked index key */
52411   i64 intKey,              /* The table key */
52412   int biasRight,           /* If true, bias the search to the high end */
52413   int *pRes                /* Write search results here */
52414 ){
52415   int rc;
52416
52417   assert( cursorHoldsMutex(pCur) );
52418   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52419   assert( pRes );
52420   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52421
52422   /* If the cursor is already positioned at the point we are trying
52423   ** to move to, then just return without doing any work */
52424   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
52425    && pCur->apPage[0]->intKey 
52426   ){
52427     if( pCur->info.nKey==intKey ){
52428       *pRes = 0;
52429       return SQLITE_OK;
52430     }
52431     if( pCur->atLast && pCur->info.nKey<intKey ){
52432       *pRes = -1;
52433       return SQLITE_OK;
52434     }
52435   }
52436
52437   rc = moveToRoot(pCur);
52438   if( rc ){
52439     return rc;
52440   }
52441   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52442   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52443   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52444   if( pCur->eState==CURSOR_INVALID ){
52445     *pRes = -1;
52446     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52447     return SQLITE_OK;
52448   }
52449   assert( pCur->apPage[0]->intKey || pIdxKey );
52450   for(;;){
52451     int lwr, upr, idx;
52452     Pgno chldPg;
52453     MemPage *pPage = pCur->apPage[pCur->iPage];
52454     int c;
52455
52456     /* pPage->nCell must be greater than zero. If this is the root-page
52457     ** the cursor would have been INVALID above and this for(;;) loop
52458     ** not run. If this is not the root-page, then the moveToChild() routine
52459     ** would have already detected db corruption. Similarly, pPage must
52460     ** be the right kind (index or table) of b-tree page. Otherwise
52461     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
52462     assert( pPage->nCell>0 );
52463     assert( pPage->intKey==(pIdxKey==0) );
52464     lwr = 0;
52465     upr = pPage->nCell-1;
52466     if( biasRight ){
52467       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
52468     }else{
52469       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
52470     }
52471     for(;;){
52472       u8 *pCell;                          /* Pointer to current cell in pPage */
52473
52474       assert( idx==pCur->aiIdx[pCur->iPage] );
52475       pCur->info.nSize = 0;
52476       pCell = findCell(pPage, idx) + pPage->childPtrSize;
52477       if( pPage->intKey ){
52478         i64 nCellKey;
52479         if( pPage->hasData ){
52480           u32 dummy;
52481           pCell += getVarint32(pCell, dummy);
52482         }
52483         getVarint(pCell, (u64*)&nCellKey);
52484         if( nCellKey==intKey ){
52485           c = 0;
52486         }else if( nCellKey<intKey ){
52487           c = -1;
52488         }else{
52489           assert( nCellKey>intKey );
52490           c = +1;
52491         }
52492         pCur->validNKey = 1;
52493         pCur->info.nKey = nCellKey;
52494       }else{
52495         /* The maximum supported page-size is 65536 bytes. This means that
52496         ** the maximum number of record bytes stored on an index B-Tree
52497         ** page is less than 16384 bytes and may be stored as a 2-byte
52498         ** varint. This information is used to attempt to avoid parsing 
52499         ** the entire cell by checking for the cases where the record is 
52500         ** stored entirely within the b-tree page by inspecting the first 
52501         ** 2 bytes of the cell.
52502         */
52503         int nCell = pCell[0];
52504         if( nCell<=pPage->max1bytePayload
52505          /* && (pCell+nCell)<pPage->aDataEnd */
52506         ){
52507           /* This branch runs if the record-size field of the cell is a
52508           ** single byte varint and the record fits entirely on the main
52509           ** b-tree page.  */
52510           testcase( pCell+nCell+1==pPage->aDataEnd );
52511           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
52512         }else if( !(pCell[1] & 0x80) 
52513           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
52514           /* && (pCell+nCell+2)<=pPage->aDataEnd */
52515         ){
52516           /* The record-size field is a 2 byte varint and the record 
52517           ** fits entirely on the main b-tree page.  */
52518           testcase( pCell+nCell+2==pPage->aDataEnd );
52519           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
52520         }else{
52521           /* The record flows over onto one or more overflow pages. In
52522           ** this case the whole cell needs to be parsed, a buffer allocated
52523           ** and accessPayload() used to retrieve the record into the
52524           ** buffer before VdbeRecordCompare() can be called. */
52525           void *pCellKey;
52526           u8 * const pCellBody = pCell - pPage->childPtrSize;
52527           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
52528           nCell = (int)pCur->info.nKey;
52529           pCellKey = sqlite3Malloc( nCell );
52530           if( pCellKey==0 ){
52531             rc = SQLITE_NOMEM;
52532             goto moveto_finish;
52533           }
52534           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
52535           if( rc ){
52536             sqlite3_free(pCellKey);
52537             goto moveto_finish;
52538           }
52539           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
52540           sqlite3_free(pCellKey);
52541         }
52542       }
52543       if( c==0 ){
52544         if( pPage->intKey && !pPage->leaf ){
52545           lwr = idx;
52546           break;
52547         }else{
52548           *pRes = 0;
52549           rc = SQLITE_OK;
52550           goto moveto_finish;
52551         }
52552       }
52553       if( c<0 ){
52554         lwr = idx+1;
52555       }else{
52556         upr = idx-1;
52557       }
52558       if( lwr>upr ){
52559         break;
52560       }
52561       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
52562     }
52563     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
52564     assert( pPage->isInit );
52565     if( pPage->leaf ){
52566       chldPg = 0;
52567     }else if( lwr>=pPage->nCell ){
52568       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52569     }else{
52570       chldPg = get4byte(findCell(pPage, lwr));
52571     }
52572     if( chldPg==0 ){
52573       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52574       *pRes = c;
52575       rc = SQLITE_OK;
52576       goto moveto_finish;
52577     }
52578     pCur->aiIdx[pCur->iPage] = (u16)lwr;
52579     pCur->info.nSize = 0;
52580     pCur->validNKey = 0;
52581     rc = moveToChild(pCur, chldPg);
52582     if( rc ) goto moveto_finish;
52583   }
52584 moveto_finish:
52585   return rc;
52586 }
52587
52588
52589 /*
52590 ** Return TRUE if the cursor is not pointing at an entry of the table.
52591 **
52592 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
52593 ** past the last entry in the table or sqlite3BtreePrev() moves past
52594 ** the first entry.  TRUE is also returned if the table is empty.
52595 */
52596 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
52597   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
52598   ** have been deleted? This API will need to change to return an error code
52599   ** as well as the boolean result value.
52600   */
52601   return (CURSOR_VALID!=pCur->eState);
52602 }
52603
52604 /*
52605 ** Advance the cursor to the next entry in the database.  If
52606 ** successful then set *pRes=0.  If the cursor
52607 ** was already pointing to the last entry in the database before
52608 ** this routine was called, then set *pRes=1.
52609 */
52610 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
52611   int rc;
52612   int idx;
52613   MemPage *pPage;
52614
52615   assert( cursorHoldsMutex(pCur) );
52616   rc = restoreCursorPosition(pCur);
52617   if( rc!=SQLITE_OK ){
52618     return rc;
52619   }
52620   assert( pRes!=0 );
52621   if( CURSOR_INVALID==pCur->eState ){
52622     *pRes = 1;
52623     return SQLITE_OK;
52624   }
52625   if( pCur->skipNext>0 ){
52626     pCur->skipNext = 0;
52627     *pRes = 0;
52628     return SQLITE_OK;
52629   }
52630   pCur->skipNext = 0;
52631
52632   pPage = pCur->apPage[pCur->iPage];
52633   idx = ++pCur->aiIdx[pCur->iPage];
52634   assert( pPage->isInit );
52635
52636   /* If the database file is corrupt, it is possible for the value of idx 
52637   ** to be invalid here. This can only occur if a second cursor modifies
52638   ** the page while cursor pCur is holding a reference to it. Which can
52639   ** only happen if the database is corrupt in such a way as to link the
52640   ** page into more than one b-tree structure. */
52641   testcase( idx>pPage->nCell );
52642
52643   pCur->info.nSize = 0;
52644   pCur->validNKey = 0;
52645   if( idx>=pPage->nCell ){
52646     if( !pPage->leaf ){
52647       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52648       if( rc ) return rc;
52649       rc = moveToLeftmost(pCur);
52650       *pRes = 0;
52651       return rc;
52652     }
52653     do{
52654       if( pCur->iPage==0 ){
52655         *pRes = 1;
52656         pCur->eState = CURSOR_INVALID;
52657         return SQLITE_OK;
52658       }
52659       moveToParent(pCur);
52660       pPage = pCur->apPage[pCur->iPage];
52661     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
52662     *pRes = 0;
52663     if( pPage->intKey ){
52664       rc = sqlite3BtreeNext(pCur, pRes);
52665     }else{
52666       rc = SQLITE_OK;
52667     }
52668     return rc;
52669   }
52670   *pRes = 0;
52671   if( pPage->leaf ){
52672     return SQLITE_OK;
52673   }
52674   rc = moveToLeftmost(pCur);
52675   return rc;
52676 }
52677
52678
52679 /*
52680 ** Step the cursor to the back to the previous entry in the database.  If
52681 ** successful then set *pRes=0.  If the cursor
52682 ** was already pointing to the first entry in the database before
52683 ** this routine was called, then set *pRes=1.
52684 */
52685 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
52686   int rc;
52687   MemPage *pPage;
52688
52689   assert( cursorHoldsMutex(pCur) );
52690   rc = restoreCursorPosition(pCur);
52691   if( rc!=SQLITE_OK ){
52692     return rc;
52693   }
52694   pCur->atLast = 0;
52695   if( CURSOR_INVALID==pCur->eState ){
52696     *pRes = 1;
52697     return SQLITE_OK;
52698   }
52699   if( pCur->skipNext<0 ){
52700     pCur->skipNext = 0;
52701     *pRes = 0;
52702     return SQLITE_OK;
52703   }
52704   pCur->skipNext = 0;
52705
52706   pPage = pCur->apPage[pCur->iPage];
52707   assert( pPage->isInit );
52708   if( !pPage->leaf ){
52709     int idx = pCur->aiIdx[pCur->iPage];
52710     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
52711     if( rc ){
52712       return rc;
52713     }
52714     rc = moveToRightmost(pCur);
52715   }else{
52716     while( pCur->aiIdx[pCur->iPage]==0 ){
52717       if( pCur->iPage==0 ){
52718         pCur->eState = CURSOR_INVALID;
52719         *pRes = 1;
52720         return SQLITE_OK;
52721       }
52722       moveToParent(pCur);
52723     }
52724     pCur->info.nSize = 0;
52725     pCur->validNKey = 0;
52726
52727     pCur->aiIdx[pCur->iPage]--;
52728     pPage = pCur->apPage[pCur->iPage];
52729     if( pPage->intKey && !pPage->leaf ){
52730       rc = sqlite3BtreePrevious(pCur, pRes);
52731     }else{
52732       rc = SQLITE_OK;
52733     }
52734   }
52735   *pRes = 0;
52736   return rc;
52737 }
52738
52739 /*
52740 ** Allocate a new page from the database file.
52741 **
52742 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
52743 ** has already been called on the new page.)  The new page has also
52744 ** been referenced and the calling routine is responsible for calling
52745 ** sqlite3PagerUnref() on the new page when it is done.
52746 **
52747 ** SQLITE_OK is returned on success.  Any other return value indicates
52748 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
52749 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
52750 **
52751 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
52752 ** locate a page close to the page number "nearby".  This can be used in an
52753 ** attempt to keep related pages close to each other in the database file,
52754 ** which in turn can make database access faster.
52755 **
52756 ** If the "exact" parameter is not 0, and the page-number nearby exists 
52757 ** anywhere on the free-list, then it is guarenteed to be returned. This
52758 ** is only used by auto-vacuum databases when allocating a new table.
52759 */
52760 static int allocateBtreePage(
52761   BtShared *pBt, 
52762   MemPage **ppPage, 
52763   Pgno *pPgno, 
52764   Pgno nearby,
52765   u8 exact
52766 ){
52767   MemPage *pPage1;
52768   int rc;
52769   u32 n;     /* Number of pages on the freelist */
52770   u32 k;     /* Number of leaves on the trunk of the freelist */
52771   MemPage *pTrunk = 0;
52772   MemPage *pPrevTrunk = 0;
52773   Pgno mxPage;     /* Total size of the database file */
52774
52775   assert( sqlite3_mutex_held(pBt->mutex) );
52776   pPage1 = pBt->pPage1;
52777   mxPage = btreePagecount(pBt);
52778   n = get4byte(&pPage1->aData[36]);
52779   testcase( n==mxPage-1 );
52780   if( n>=mxPage ){
52781     return SQLITE_CORRUPT_BKPT;
52782   }
52783   if( n>0 ){
52784     /* There are pages on the freelist.  Reuse one of those pages. */
52785     Pgno iTrunk;
52786     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
52787     
52788     /* If the 'exact' parameter was true and a query of the pointer-map
52789     ** shows that the page 'nearby' is somewhere on the free-list, then
52790     ** the entire-list will be searched for that page.
52791     */
52792 #ifndef SQLITE_OMIT_AUTOVACUUM
52793     if( exact && nearby<=mxPage ){
52794       u8 eType;
52795       assert( nearby>0 );
52796       assert( pBt->autoVacuum );
52797       rc = ptrmapGet(pBt, nearby, &eType, 0);
52798       if( rc ) return rc;
52799       if( eType==PTRMAP_FREEPAGE ){
52800         searchList = 1;
52801       }
52802       *pPgno = nearby;
52803     }
52804 #endif
52805
52806     /* Decrement the free-list count by 1. Set iTrunk to the index of the
52807     ** first free-list trunk page. iPrevTrunk is initially 1.
52808     */
52809     rc = sqlite3PagerWrite(pPage1->pDbPage);
52810     if( rc ) return rc;
52811     put4byte(&pPage1->aData[36], n-1);
52812
52813     /* The code within this loop is run only once if the 'searchList' variable
52814     ** is not true. Otherwise, it runs once for each trunk-page on the
52815     ** free-list until the page 'nearby' is located.
52816     */
52817     do {
52818       pPrevTrunk = pTrunk;
52819       if( pPrevTrunk ){
52820         iTrunk = get4byte(&pPrevTrunk->aData[0]);
52821       }else{
52822         iTrunk = get4byte(&pPage1->aData[32]);
52823       }
52824       testcase( iTrunk==mxPage );
52825       if( iTrunk>mxPage ){
52826         rc = SQLITE_CORRUPT_BKPT;
52827       }else{
52828         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52829       }
52830       if( rc ){
52831         pTrunk = 0;
52832         goto end_allocate_page;
52833       }
52834       assert( pTrunk!=0 );
52835       assert( pTrunk->aData!=0 );
52836
52837       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
52838       if( k==0 && !searchList ){
52839         /* The trunk has no leaves and the list is not being searched. 
52840         ** So extract the trunk page itself and use it as the newly 
52841         ** allocated page */
52842         assert( pPrevTrunk==0 );
52843         rc = sqlite3PagerWrite(pTrunk->pDbPage);
52844         if( rc ){
52845           goto end_allocate_page;
52846         }
52847         *pPgno = iTrunk;
52848         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52849         *ppPage = pTrunk;
52850         pTrunk = 0;
52851         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52852       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
52853         /* Value of k is out of range.  Database corruption */
52854         rc = SQLITE_CORRUPT_BKPT;
52855         goto end_allocate_page;
52856 #ifndef SQLITE_OMIT_AUTOVACUUM
52857       }else if( searchList && nearby==iTrunk ){
52858         /* The list is being searched and this trunk page is the page
52859         ** to allocate, regardless of whether it has leaves.
52860         */
52861         assert( *pPgno==iTrunk );
52862         *ppPage = pTrunk;
52863         searchList = 0;
52864         rc = sqlite3PagerWrite(pTrunk->pDbPage);
52865         if( rc ){
52866           goto end_allocate_page;
52867         }
52868         if( k==0 ){
52869           if( !pPrevTrunk ){
52870             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52871           }else{
52872             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52873             if( rc!=SQLITE_OK ){
52874               goto end_allocate_page;
52875             }
52876             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
52877           }
52878         }else{
52879           /* The trunk page is required by the caller but it contains 
52880           ** pointers to free-list leaves. The first leaf becomes a trunk
52881           ** page in this case.
52882           */
52883           MemPage *pNewTrunk;
52884           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
52885           if( iNewTrunk>mxPage ){ 
52886             rc = SQLITE_CORRUPT_BKPT;
52887             goto end_allocate_page;
52888           }
52889           testcase( iNewTrunk==mxPage );
52890           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
52891           if( rc!=SQLITE_OK ){
52892             goto end_allocate_page;
52893           }
52894           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
52895           if( rc!=SQLITE_OK ){
52896             releasePage(pNewTrunk);
52897             goto end_allocate_page;
52898           }
52899           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
52900           put4byte(&pNewTrunk->aData[4], k-1);
52901           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
52902           releasePage(pNewTrunk);
52903           if( !pPrevTrunk ){
52904             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
52905             put4byte(&pPage1->aData[32], iNewTrunk);
52906           }else{
52907             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52908             if( rc ){
52909               goto end_allocate_page;
52910             }
52911             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
52912           }
52913         }
52914         pTrunk = 0;
52915         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52916 #endif
52917       }else if( k>0 ){
52918         /* Extract a leaf from the trunk */
52919         u32 closest;
52920         Pgno iPage;
52921         unsigned char *aData = pTrunk->aData;
52922         if( nearby>0 ){
52923           u32 i;
52924           int dist;
52925           closest = 0;
52926           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
52927           for(i=1; i<k; i++){
52928             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
52929             if( d2<dist ){
52930               closest = i;
52931               dist = d2;
52932             }
52933           }
52934         }else{
52935           closest = 0;
52936         }
52937
52938         iPage = get4byte(&aData[8+closest*4]);
52939         testcase( iPage==mxPage );
52940         if( iPage>mxPage ){
52941           rc = SQLITE_CORRUPT_BKPT;
52942           goto end_allocate_page;
52943         }
52944         testcase( iPage==mxPage );
52945         if( !searchList || iPage==nearby ){
52946           int noContent;
52947           *pPgno = iPage;
52948           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
52949                  ": %d more free pages\n",
52950                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
52951           rc = sqlite3PagerWrite(pTrunk->pDbPage);
52952           if( rc ) goto end_allocate_page;
52953           if( closest<k-1 ){
52954             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
52955           }
52956           put4byte(&aData[4], k-1);
52957           noContent = !btreeGetHasContent(pBt, *pPgno);
52958           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
52959           if( rc==SQLITE_OK ){
52960             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52961             if( rc!=SQLITE_OK ){
52962               releasePage(*ppPage);
52963             }
52964           }
52965           searchList = 0;
52966         }
52967       }
52968       releasePage(pPrevTrunk);
52969       pPrevTrunk = 0;
52970     }while( searchList );
52971   }else{
52972     /* There are no pages on the freelist, so create a new page at the
52973     ** end of the file */
52974     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52975     if( rc ) return rc;
52976     pBt->nPage++;
52977     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
52978
52979 #ifndef SQLITE_OMIT_AUTOVACUUM
52980     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
52981       /* If *pPgno refers to a pointer-map page, allocate two new pages
52982       ** at the end of the file instead of one. The first allocated page
52983       ** becomes a new pointer-map page, the second is used by the caller.
52984       */
52985       MemPage *pPg = 0;
52986       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
52987       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
52988       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
52989       if( rc==SQLITE_OK ){
52990         rc = sqlite3PagerWrite(pPg->pDbPage);
52991         releasePage(pPg);
52992       }
52993       if( rc ) return rc;
52994       pBt->nPage++;
52995       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
52996     }
52997 #endif
52998     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
52999     *pPgno = pBt->nPage;
53000
53001     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53002     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
53003     if( rc ) return rc;
53004     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53005     if( rc!=SQLITE_OK ){
53006       releasePage(*ppPage);
53007     }
53008     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53009   }
53010
53011   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53012
53013 end_allocate_page:
53014   releasePage(pTrunk);
53015   releasePage(pPrevTrunk);
53016   if( rc==SQLITE_OK ){
53017     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53018       releasePage(*ppPage);
53019       return SQLITE_CORRUPT_BKPT;
53020     }
53021     (*ppPage)->isInit = 0;
53022   }else{
53023     *ppPage = 0;
53024   }
53025   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53026   return rc;
53027 }
53028
53029 /*
53030 ** This function is used to add page iPage to the database file free-list. 
53031 ** It is assumed that the page is not already a part of the free-list.
53032 **
53033 ** The value passed as the second argument to this function is optional.
53034 ** If the caller happens to have a pointer to the MemPage object 
53035 ** corresponding to page iPage handy, it may pass it as the second value. 
53036 ** Otherwise, it may pass NULL.
53037 **
53038 ** If a pointer to a MemPage object is passed as the second argument,
53039 ** its reference count is not altered by this function.
53040 */
53041 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53042   MemPage *pTrunk = 0;                /* Free-list trunk page */
53043   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
53044   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
53045   MemPage *pPage;                     /* Page being freed. May be NULL. */
53046   int rc;                             /* Return Code */
53047   int nFree;                          /* Initial number of pages on free-list */
53048
53049   assert( sqlite3_mutex_held(pBt->mutex) );
53050   assert( iPage>1 );
53051   assert( !pMemPage || pMemPage->pgno==iPage );
53052
53053   if( pMemPage ){
53054     pPage = pMemPage;
53055     sqlite3PagerRef(pPage->pDbPage);
53056   }else{
53057     pPage = btreePageLookup(pBt, iPage);
53058   }
53059
53060   /* Increment the free page count on pPage1 */
53061   rc = sqlite3PagerWrite(pPage1->pDbPage);
53062   if( rc ) goto freepage_out;
53063   nFree = get4byte(&pPage1->aData[36]);
53064   put4byte(&pPage1->aData[36], nFree+1);
53065
53066   if( pBt->btsFlags & BTS_SECURE_DELETE ){
53067     /* If the secure_delete option is enabled, then
53068     ** always fully overwrite deleted information with zeros.
53069     */
53070     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53071      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53072     ){
53073       goto freepage_out;
53074     }
53075     memset(pPage->aData, 0, pPage->pBt->pageSize);
53076   }
53077
53078   /* If the database supports auto-vacuum, write an entry in the pointer-map
53079   ** to indicate that the page is free.
53080   */
53081   if( ISAUTOVACUUM ){
53082     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53083     if( rc ) goto freepage_out;
53084   }
53085
53086   /* Now manipulate the actual database free-list structure. There are two
53087   ** possibilities. If the free-list is currently empty, or if the first
53088   ** trunk page in the free-list is full, then this page will become a
53089   ** new free-list trunk page. Otherwise, it will become a leaf of the
53090   ** first trunk page in the current free-list. This block tests if it
53091   ** is possible to add the page as a new free-list leaf.
53092   */
53093   if( nFree!=0 ){
53094     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
53095
53096     iTrunk = get4byte(&pPage1->aData[32]);
53097     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53098     if( rc!=SQLITE_OK ){
53099       goto freepage_out;
53100     }
53101
53102     nLeaf = get4byte(&pTrunk->aData[4]);
53103     assert( pBt->usableSize>32 );
53104     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53105       rc = SQLITE_CORRUPT_BKPT;
53106       goto freepage_out;
53107     }
53108     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53109       /* In this case there is room on the trunk page to insert the page
53110       ** being freed as a new leaf.
53111       **
53112       ** Note that the trunk page is not really full until it contains
53113       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53114       ** coded.  But due to a coding error in versions of SQLite prior to
53115       ** 3.6.0, databases with freelist trunk pages holding more than
53116       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
53117       ** to maintain backwards compatibility with older versions of SQLite,
53118       ** we will continue to restrict the number of entries to usableSize/4 - 8
53119       ** for now.  At some point in the future (once everyone has upgraded
53120       ** to 3.6.0 or later) we should consider fixing the conditional above
53121       ** to read "usableSize/4-2" instead of "usableSize/4-8".
53122       */
53123       rc = sqlite3PagerWrite(pTrunk->pDbPage);
53124       if( rc==SQLITE_OK ){
53125         put4byte(&pTrunk->aData[4], nLeaf+1);
53126         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53127         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
53128           sqlite3PagerDontWrite(pPage->pDbPage);
53129         }
53130         rc = btreeSetHasContent(pBt, iPage);
53131       }
53132       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53133       goto freepage_out;
53134     }
53135   }
53136
53137   /* If control flows to this point, then it was not possible to add the
53138   ** the page being freed as a leaf page of the first trunk in the free-list.
53139   ** Possibly because the free-list is empty, or possibly because the 
53140   ** first trunk in the free-list is full. Either way, the page being freed
53141   ** will become the new first trunk page in the free-list.
53142   */
53143   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53144     goto freepage_out;
53145   }
53146   rc = sqlite3PagerWrite(pPage->pDbPage);
53147   if( rc!=SQLITE_OK ){
53148     goto freepage_out;
53149   }
53150   put4byte(pPage->aData, iTrunk);
53151   put4byte(&pPage->aData[4], 0);
53152   put4byte(&pPage1->aData[32], iPage);
53153   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53154
53155 freepage_out:
53156   if( pPage ){
53157     pPage->isInit = 0;
53158   }
53159   releasePage(pPage);
53160   releasePage(pTrunk);
53161   return rc;
53162 }
53163 static void freePage(MemPage *pPage, int *pRC){
53164   if( (*pRC)==SQLITE_OK ){
53165     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53166   }
53167 }
53168
53169 /*
53170 ** Free any overflow pages associated with the given Cell.
53171 */
53172 static int clearCell(MemPage *pPage, unsigned char *pCell){
53173   BtShared *pBt = pPage->pBt;
53174   CellInfo info;
53175   Pgno ovflPgno;
53176   int rc;
53177   int nOvfl;
53178   u32 ovflPageSize;
53179
53180   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53181   btreeParseCellPtr(pPage, pCell, &info);
53182   if( info.iOverflow==0 ){
53183     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
53184   }
53185   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53186     return SQLITE_CORRUPT;  /* Cell extends past end of page */
53187   }
53188   ovflPgno = get4byte(&pCell[info.iOverflow]);
53189   assert( pBt->usableSize > 4 );
53190   ovflPageSize = pBt->usableSize - 4;
53191   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53192   assert( ovflPgno==0 || nOvfl>0 );
53193   while( nOvfl-- ){
53194     Pgno iNext = 0;
53195     MemPage *pOvfl = 0;
53196     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53197       /* 0 is not a legal page number and page 1 cannot be an 
53198       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
53199       ** file the database must be corrupt. */
53200       return SQLITE_CORRUPT_BKPT;
53201     }
53202     if( nOvfl ){
53203       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53204       if( rc ) return rc;
53205     }
53206
53207     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53208      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53209     ){
53210       /* There is no reason any cursor should have an outstanding reference 
53211       ** to an overflow page belonging to a cell that is being deleted/updated.
53212       ** So if there exists more than one reference to this page, then it 
53213       ** must not really be an overflow page and the database must be corrupt. 
53214       ** It is helpful to detect this before calling freePage2(), as 
53215       ** freePage2() may zero the page contents if secure-delete mode is
53216       ** enabled. If this 'overflow' page happens to be a page that the
53217       ** caller is iterating through or using in some other way, this
53218       ** can be problematic.
53219       */
53220       rc = SQLITE_CORRUPT_BKPT;
53221     }else{
53222       rc = freePage2(pBt, pOvfl, ovflPgno);
53223     }
53224
53225     if( pOvfl ){
53226       sqlite3PagerUnref(pOvfl->pDbPage);
53227     }
53228     if( rc ) return rc;
53229     ovflPgno = iNext;
53230   }
53231   return SQLITE_OK;
53232 }
53233
53234 /*
53235 ** Create the byte sequence used to represent a cell on page pPage
53236 ** and write that byte sequence into pCell[].  Overflow pages are
53237 ** allocated and filled in as necessary.  The calling procedure
53238 ** is responsible for making sure sufficient space has been allocated
53239 ** for pCell[].
53240 **
53241 ** Note that pCell does not necessary need to point to the pPage->aData
53242 ** area.  pCell might point to some temporary storage.  The cell will
53243 ** be constructed in this temporary area then copied into pPage->aData
53244 ** later.
53245 */
53246 static int fillInCell(
53247   MemPage *pPage,                /* The page that contains the cell */
53248   unsigned char *pCell,          /* Complete text of the cell */
53249   const void *pKey, i64 nKey,    /* The key */
53250   const void *pData,int nData,   /* The data */
53251   int nZero,                     /* Extra zero bytes to append to pData */
53252   int *pnSize                    /* Write cell size here */
53253 ){
53254   int nPayload;
53255   const u8 *pSrc;
53256   int nSrc, n, rc;
53257   int spaceLeft;
53258   MemPage *pOvfl = 0;
53259   MemPage *pToRelease = 0;
53260   unsigned char *pPrior;
53261   unsigned char *pPayload;
53262   BtShared *pBt = pPage->pBt;
53263   Pgno pgnoOvfl = 0;
53264   int nHeader;
53265   CellInfo info;
53266
53267   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53268
53269   /* pPage is not necessarily writeable since pCell might be auxiliary
53270   ** buffer space that is separate from the pPage buffer area */
53271   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53272             || sqlite3PagerIswriteable(pPage->pDbPage) );
53273
53274   /* Fill in the header. */
53275   nHeader = 0;
53276   if( !pPage->leaf ){
53277     nHeader += 4;
53278   }
53279   if( pPage->hasData ){
53280     nHeader += putVarint(&pCell[nHeader], nData+nZero);
53281   }else{
53282     nData = nZero = 0;
53283   }
53284   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53285   btreeParseCellPtr(pPage, pCell, &info);
53286   assert( info.nHeader==nHeader );
53287   assert( info.nKey==nKey );
53288   assert( info.nData==(u32)(nData+nZero) );
53289   
53290   /* Fill in the payload */
53291   nPayload = nData + nZero;
53292   if( pPage->intKey ){
53293     pSrc = pData;
53294     nSrc = nData;
53295     nData = 0;
53296   }else{ 
53297     if( NEVER(nKey>0x7fffffff || pKey==0) ){
53298       return SQLITE_CORRUPT_BKPT;
53299     }
53300     nPayload += (int)nKey;
53301     pSrc = pKey;
53302     nSrc = (int)nKey;
53303   }
53304   *pnSize = info.nSize;
53305   spaceLeft = info.nLocal;
53306   pPayload = &pCell[nHeader];
53307   pPrior = &pCell[info.iOverflow];
53308
53309   while( nPayload>0 ){
53310     if( spaceLeft==0 ){
53311 #ifndef SQLITE_OMIT_AUTOVACUUM
53312       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53313       if( pBt->autoVacuum ){
53314         do{
53315           pgnoOvfl++;
53316         } while( 
53317           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
53318         );
53319       }
53320 #endif
53321       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53322 #ifndef SQLITE_OMIT_AUTOVACUUM
53323       /* If the database supports auto-vacuum, and the second or subsequent
53324       ** overflow page is being allocated, add an entry to the pointer-map
53325       ** for that page now. 
53326       **
53327       ** If this is the first overflow page, then write a partial entry 
53328       ** to the pointer-map. If we write nothing to this pointer-map slot,
53329       ** then the optimistic overflow chain processing in clearCell()
53330       ** may misinterpret the uninitialised values and delete the
53331       ** wrong pages from the database.
53332       */
53333       if( pBt->autoVacuum && rc==SQLITE_OK ){
53334         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53335         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53336         if( rc ){
53337           releasePage(pOvfl);
53338         }
53339       }
53340 #endif
53341       if( rc ){
53342         releasePage(pToRelease);
53343         return rc;
53344       }
53345
53346       /* If pToRelease is not zero than pPrior points into the data area
53347       ** of pToRelease.  Make sure pToRelease is still writeable. */
53348       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53349
53350       /* If pPrior is part of the data area of pPage, then make sure pPage
53351       ** is still writeable */
53352       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53353             || sqlite3PagerIswriteable(pPage->pDbPage) );
53354
53355       put4byte(pPrior, pgnoOvfl);
53356       releasePage(pToRelease);
53357       pToRelease = pOvfl;
53358       pPrior = pOvfl->aData;
53359       put4byte(pPrior, 0);
53360       pPayload = &pOvfl->aData[4];
53361       spaceLeft = pBt->usableSize - 4;
53362     }
53363     n = nPayload;
53364     if( n>spaceLeft ) n = spaceLeft;
53365
53366     /* If pToRelease is not zero than pPayload points into the data area
53367     ** of pToRelease.  Make sure pToRelease is still writeable. */
53368     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53369
53370     /* If pPayload is part of the data area of pPage, then make sure pPage
53371     ** is still writeable */
53372     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53373             || sqlite3PagerIswriteable(pPage->pDbPage) );
53374
53375     if( nSrc>0 ){
53376       if( n>nSrc ) n = nSrc;
53377       assert( pSrc );
53378       memcpy(pPayload, pSrc, n);
53379     }else{
53380       memset(pPayload, 0, n);
53381     }
53382     nPayload -= n;
53383     pPayload += n;
53384     pSrc += n;
53385     nSrc -= n;
53386     spaceLeft -= n;
53387     if( nSrc==0 ){
53388       nSrc = nData;
53389       pSrc = pData;
53390     }
53391   }
53392   releasePage(pToRelease);
53393   return SQLITE_OK;
53394 }
53395
53396 /*
53397 ** Remove the i-th cell from pPage.  This routine effects pPage only.
53398 ** The cell content is not freed or deallocated.  It is assumed that
53399 ** the cell content has been copied someplace else.  This routine just
53400 ** removes the reference to the cell from pPage.
53401 **
53402 ** "sz" must be the number of bytes in the cell.
53403 */
53404 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53405   u32 pc;         /* Offset to cell content of cell being deleted */
53406   u8 *data;       /* pPage->aData */
53407   u8 *ptr;        /* Used to move bytes around within data[] */
53408   u8 *endPtr;     /* End of loop */
53409   int rc;         /* The return code */
53410   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
53411
53412   if( *pRC ) return;
53413
53414   assert( idx>=0 && idx<pPage->nCell );
53415   assert( sz==cellSize(pPage, idx) );
53416   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53417   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53418   data = pPage->aData;
53419   ptr = &pPage->aCellIdx[2*idx];
53420   pc = get2byte(ptr);
53421   hdr = pPage->hdrOffset;
53422   testcase( pc==get2byte(&data[hdr+5]) );
53423   testcase( pc+sz==pPage->pBt->usableSize );
53424   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
53425     *pRC = SQLITE_CORRUPT_BKPT;
53426     return;
53427   }
53428   rc = freeSpace(pPage, pc, sz);
53429   if( rc ){
53430     *pRC = rc;
53431     return;
53432   }
53433   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
53434   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53435   while( ptr<endPtr ){
53436     *(u16*)ptr = *(u16*)&ptr[2];
53437     ptr += 2;
53438   }
53439   pPage->nCell--;
53440   put2byte(&data[hdr+3], pPage->nCell);
53441   pPage->nFree += 2;
53442 }
53443
53444 /*
53445 ** Insert a new cell on pPage at cell index "i".  pCell points to the
53446 ** content of the cell.
53447 **
53448 ** If the cell content will fit on the page, then put it there.  If it
53449 ** will not fit, then make a copy of the cell content into pTemp if
53450 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
53451 ** in pPage->apOvfl[] and make it point to the cell content (either
53452 ** in pTemp or the original pCell) and also record its index. 
53453 ** Allocating a new entry in pPage->aCell[] implies that 
53454 ** pPage->nOverflow is incremented.
53455 **
53456 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
53457 ** cell. The caller will overwrite them after this function returns. If
53458 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
53459 ** (but pCell+nSkip is always valid).
53460 */
53461 static void insertCell(
53462   MemPage *pPage,   /* Page into which we are copying */
53463   int i,            /* New cell becomes the i-th cell of the page */
53464   u8 *pCell,        /* Content of the new cell */
53465   int sz,           /* Bytes of content in pCell */
53466   u8 *pTemp,        /* Temp storage space for pCell, if needed */
53467   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
53468   int *pRC          /* Read and write return code from here */
53469 ){
53470   int idx = 0;      /* Where to write new cell content in data[] */
53471   int j;            /* Loop counter */
53472   int end;          /* First byte past the last cell pointer in data[] */
53473   int ins;          /* Index in data[] where new cell pointer is inserted */
53474   int cellOffset;   /* Address of first cell pointer in data[] */
53475   u8 *data;         /* The content of the whole page */
53476   u8 *ptr;          /* Used for moving information around in data[] */
53477   u8 *endPtr;       /* End of the loop */
53478
53479   int nSkip = (iChild ? 4 : 0);
53480
53481   if( *pRC ) return;
53482
53483   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
53484   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
53485   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
53486   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
53487   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53488   /* The cell should normally be sized correctly.  However, when moving a
53489   ** malformed cell from a leaf page to an interior page, if the cell size
53490   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
53491   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
53492   ** the term after the || in the following assert(). */
53493   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
53494   if( pPage->nOverflow || sz+2>pPage->nFree ){
53495     if( pTemp ){
53496       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
53497       pCell = pTemp;
53498     }
53499     if( iChild ){
53500       put4byte(pCell, iChild);
53501     }
53502     j = pPage->nOverflow++;
53503     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
53504     pPage->apOvfl[j] = pCell;
53505     pPage->aiOvfl[j] = (u16)i;
53506   }else{
53507     int rc = sqlite3PagerWrite(pPage->pDbPage);
53508     if( rc!=SQLITE_OK ){
53509       *pRC = rc;
53510       return;
53511     }
53512     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53513     data = pPage->aData;
53514     cellOffset = pPage->cellOffset;
53515     end = cellOffset + 2*pPage->nCell;
53516     ins = cellOffset + 2*i;
53517     rc = allocateSpace(pPage, sz, &idx);
53518     if( rc ){ *pRC = rc; return; }
53519     /* The allocateSpace() routine guarantees the following two properties
53520     ** if it returns success */
53521     assert( idx >= end+2 );
53522     assert( idx+sz <= (int)pPage->pBt->usableSize );
53523     pPage->nCell++;
53524     pPage->nFree -= (u16)(2 + sz);
53525     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
53526     if( iChild ){
53527       put4byte(&data[idx], iChild);
53528     }
53529     ptr = &data[end];
53530     endPtr = &data[ins];
53531     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53532     while( ptr>endPtr ){
53533       *(u16*)ptr = *(u16*)&ptr[-2];
53534       ptr -= 2;
53535     }
53536     put2byte(&data[ins], idx);
53537     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
53538 #ifndef SQLITE_OMIT_AUTOVACUUM
53539     if( pPage->pBt->autoVacuum ){
53540       /* The cell may contain a pointer to an overflow page. If so, write
53541       ** the entry for the overflow page into the pointer map.
53542       */
53543       ptrmapPutOvflPtr(pPage, pCell, pRC);
53544     }
53545 #endif
53546   }
53547 }
53548
53549 /*
53550 ** Add a list of cells to a page.  The page should be initially empty.
53551 ** The cells are guaranteed to fit on the page.
53552 */
53553 static void assemblePage(
53554   MemPage *pPage,   /* The page to be assemblied */
53555   int nCell,        /* The number of cells to add to this page */
53556   u8 **apCell,      /* Pointers to cell bodies */
53557   u16 *aSize        /* Sizes of the cells */
53558 ){
53559   int i;            /* Loop counter */
53560   u8 *pCellptr;     /* Address of next cell pointer */
53561   int cellbody;     /* Address of next cell body */
53562   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
53563   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
53564   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
53565
53566   assert( pPage->nOverflow==0 );
53567   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53568   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
53569             && (int)MX_CELL(pPage->pBt)<=10921);
53570   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53571
53572   /* Check that the page has just been zeroed by zeroPage() */
53573   assert( pPage->nCell==0 );
53574   assert( get2byteNotZero(&data[hdr+5])==nUsable );
53575
53576   pCellptr = &pPage->aCellIdx[nCell*2];
53577   cellbody = nUsable;
53578   for(i=nCell-1; i>=0; i--){
53579     u16 sz = aSize[i];
53580     pCellptr -= 2;
53581     cellbody -= sz;
53582     put2byte(pCellptr, cellbody);
53583     memcpy(&data[cellbody], apCell[i], sz);
53584   }
53585   put2byte(&data[hdr+3], nCell);
53586   put2byte(&data[hdr+5], cellbody);
53587   pPage->nFree -= (nCell*2 + nUsable - cellbody);
53588   pPage->nCell = (u16)nCell;
53589 }
53590
53591 /*
53592 ** The following parameters determine how many adjacent pages get involved
53593 ** in a balancing operation.  NN is the number of neighbors on either side
53594 ** of the page that participate in the balancing operation.  NB is the
53595 ** total number of pages that participate, including the target page and
53596 ** NN neighbors on either side.
53597 **
53598 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
53599 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
53600 ** in exchange for a larger degradation in INSERT and UPDATE performance.
53601 ** The value of NN appears to give the best results overall.
53602 */
53603 #define NN 1             /* Number of neighbors on either side of pPage */
53604 #define NB (NN*2+1)      /* Total pages involved in the balance */
53605
53606
53607 #ifndef SQLITE_OMIT_QUICKBALANCE
53608 /*
53609 ** This version of balance() handles the common special case where
53610 ** a new entry is being inserted on the extreme right-end of the
53611 ** tree, in other words, when the new entry will become the largest
53612 ** entry in the tree.
53613 **
53614 ** Instead of trying to balance the 3 right-most leaf pages, just add
53615 ** a new page to the right-hand side and put the one new entry in
53616 ** that page.  This leaves the right side of the tree somewhat
53617 ** unbalanced.  But odds are that we will be inserting new entries
53618 ** at the end soon afterwards so the nearly empty page will quickly
53619 ** fill up.  On average.
53620 **
53621 ** pPage is the leaf page which is the right-most page in the tree.
53622 ** pParent is its parent.  pPage must have a single overflow entry
53623 ** which is also the right-most entry on the page.
53624 **
53625 ** The pSpace buffer is used to store a temporary copy of the divider
53626 ** cell that will be inserted into pParent. Such a cell consists of a 4
53627 ** byte page number followed by a variable length integer. In other
53628 ** words, at most 13 bytes. Hence the pSpace buffer must be at
53629 ** least 13 bytes in size.
53630 */
53631 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
53632   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
53633   MemPage *pNew;                       /* Newly allocated page */
53634   int rc;                              /* Return Code */
53635   Pgno pgnoNew;                        /* Page number of pNew */
53636
53637   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53638   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53639   assert( pPage->nOverflow==1 );
53640
53641   /* This error condition is now caught prior to reaching this function */
53642   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
53643
53644   /* Allocate a new page. This page will become the right-sibling of 
53645   ** pPage. Make the parent page writable, so that the new divider cell
53646   ** may be inserted. If both these operations are successful, proceed.
53647   */
53648   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
53649
53650   if( rc==SQLITE_OK ){
53651
53652     u8 *pOut = &pSpace[4];
53653     u8 *pCell = pPage->apOvfl[0];
53654     u16 szCell = cellSizePtr(pPage, pCell);
53655     u8 *pStop;
53656
53657     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
53658     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
53659     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
53660     assemblePage(pNew, 1, &pCell, &szCell);
53661
53662     /* If this is an auto-vacuum database, update the pointer map
53663     ** with entries for the new page, and any pointer from the 
53664     ** cell on the page to an overflow page. If either of these
53665     ** operations fails, the return code is set, but the contents
53666     ** of the parent page are still manipulated by thh code below.
53667     ** That is Ok, at this point the parent page is guaranteed to
53668     ** be marked as dirty. Returning an error code will cause a
53669     ** rollback, undoing any changes made to the parent page.
53670     */
53671     if( ISAUTOVACUUM ){
53672       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
53673       if( szCell>pNew->minLocal ){
53674         ptrmapPutOvflPtr(pNew, pCell, &rc);
53675       }
53676     }
53677   
53678     /* Create a divider cell to insert into pParent. The divider cell
53679     ** consists of a 4-byte page number (the page number of pPage) and
53680     ** a variable length key value (which must be the same value as the
53681     ** largest key on pPage).
53682     **
53683     ** To find the largest key value on pPage, first find the right-most 
53684     ** cell on pPage. The first two fields of this cell are the 
53685     ** record-length (a variable length integer at most 32-bits in size)
53686     ** and the key value (a variable length integer, may have any value).
53687     ** The first of the while(...) loops below skips over the record-length
53688     ** field. The second while(...) loop copies the key value from the
53689     ** cell on pPage into the pSpace buffer.
53690     */
53691     pCell = findCell(pPage, pPage->nCell-1);
53692     pStop = &pCell[9];
53693     while( (*(pCell++)&0x80) && pCell<pStop );
53694     pStop = &pCell[9];
53695     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
53696
53697     /* Insert the new divider cell into pParent. */
53698     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
53699                0, pPage->pgno, &rc);
53700
53701     /* Set the right-child pointer of pParent to point to the new page. */
53702     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
53703   
53704     /* Release the reference to the new page. */
53705     releasePage(pNew);
53706   }
53707
53708   return rc;
53709 }
53710 #endif /* SQLITE_OMIT_QUICKBALANCE */
53711
53712 #if 0
53713 /*
53714 ** This function does not contribute anything to the operation of SQLite.
53715 ** it is sometimes activated temporarily while debugging code responsible 
53716 ** for setting pointer-map entries.
53717 */
53718 static int ptrmapCheckPages(MemPage **apPage, int nPage){
53719   int i, j;
53720   for(i=0; i<nPage; i++){
53721     Pgno n;
53722     u8 e;
53723     MemPage *pPage = apPage[i];
53724     BtShared *pBt = pPage->pBt;
53725     assert( pPage->isInit );
53726
53727     for(j=0; j<pPage->nCell; j++){
53728       CellInfo info;
53729       u8 *z;
53730      
53731       z = findCell(pPage, j);
53732       btreeParseCellPtr(pPage, z, &info);
53733       if( info.iOverflow ){
53734         Pgno ovfl = get4byte(&z[info.iOverflow]);
53735         ptrmapGet(pBt, ovfl, &e, &n);
53736         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
53737       }
53738       if( !pPage->leaf ){
53739         Pgno child = get4byte(z);
53740         ptrmapGet(pBt, child, &e, &n);
53741         assert( n==pPage->pgno && e==PTRMAP_BTREE );
53742       }
53743     }
53744     if( !pPage->leaf ){
53745       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53746       ptrmapGet(pBt, child, &e, &n);
53747       assert( n==pPage->pgno && e==PTRMAP_BTREE );
53748     }
53749   }
53750   return 1;
53751 }
53752 #endif
53753
53754 /*
53755 ** This function is used to copy the contents of the b-tree node stored 
53756 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
53757 ** the pointer-map entries for each child page are updated so that the
53758 ** parent page stored in the pointer map is page pTo. If pFrom contained
53759 ** any cells with overflow page pointers, then the corresponding pointer
53760 ** map entries are also updated so that the parent page is page pTo.
53761 **
53762 ** If pFrom is currently carrying any overflow cells (entries in the
53763 ** MemPage.apOvfl[] array), they are not copied to pTo. 
53764 **
53765 ** Before returning, page pTo is reinitialized using btreeInitPage().
53766 **
53767 ** The performance of this function is not critical. It is only used by 
53768 ** the balance_shallower() and balance_deeper() procedures, neither of
53769 ** which are called often under normal circumstances.
53770 */
53771 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
53772   if( (*pRC)==SQLITE_OK ){
53773     BtShared * const pBt = pFrom->pBt;
53774     u8 * const aFrom = pFrom->aData;
53775     u8 * const aTo = pTo->aData;
53776     int const iFromHdr = pFrom->hdrOffset;
53777     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
53778     int rc;
53779     int iData;
53780   
53781   
53782     assert( pFrom->isInit );
53783     assert( pFrom->nFree>=iToHdr );
53784     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
53785   
53786     /* Copy the b-tree node content from page pFrom to page pTo. */
53787     iData = get2byte(&aFrom[iFromHdr+5]);
53788     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
53789     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
53790   
53791     /* Reinitialize page pTo so that the contents of the MemPage structure
53792     ** match the new data. The initialization of pTo can actually fail under
53793     ** fairly obscure circumstances, even though it is a copy of initialized 
53794     ** page pFrom.
53795     */
53796     pTo->isInit = 0;
53797     rc = btreeInitPage(pTo);
53798     if( rc!=SQLITE_OK ){
53799       *pRC = rc;
53800       return;
53801     }
53802   
53803     /* If this is an auto-vacuum database, update the pointer-map entries
53804     ** for any b-tree or overflow pages that pTo now contains the pointers to.
53805     */
53806     if( ISAUTOVACUUM ){
53807       *pRC = setChildPtrmaps(pTo);
53808     }
53809   }
53810 }
53811
53812 /*
53813 ** This routine redistributes cells on the iParentIdx'th child of pParent
53814 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
53815 ** same amount of free space. Usually a single sibling on either side of the
53816 ** page are used in the balancing, though both siblings might come from one
53817 ** side if the page is the first or last child of its parent. If the page 
53818 ** has fewer than 2 siblings (something which can only happen if the page
53819 ** is a root page or a child of a root page) then all available siblings
53820 ** participate in the balancing.
53821 **
53822 ** The number of siblings of the page might be increased or decreased by 
53823 ** one or two in an effort to keep pages nearly full but not over full. 
53824 **
53825 ** Note that when this routine is called, some of the cells on the page
53826 ** might not actually be stored in MemPage.aData[]. This can happen
53827 ** if the page is overfull. This routine ensures that all cells allocated
53828 ** to the page and its siblings fit into MemPage.aData[] before returning.
53829 **
53830 ** In the course of balancing the page and its siblings, cells may be
53831 ** inserted into or removed from the parent page (pParent). Doing so
53832 ** may cause the parent page to become overfull or underfull. If this
53833 ** happens, it is the responsibility of the caller to invoke the correct
53834 ** balancing routine to fix this problem (see the balance() routine). 
53835 **
53836 ** If this routine fails for any reason, it might leave the database
53837 ** in a corrupted state. So if this routine fails, the database should
53838 ** be rolled back.
53839 **
53840 ** The third argument to this function, aOvflSpace, is a pointer to a
53841 ** buffer big enough to hold one page. If while inserting cells into the parent
53842 ** page (pParent) the parent page becomes overfull, this buffer is
53843 ** used to store the parent's overflow cells. Because this function inserts
53844 ** a maximum of four divider cells into the parent page, and the maximum
53845 ** size of a cell stored within an internal node is always less than 1/4
53846 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
53847 ** enough for all overflow cells.
53848 **
53849 ** If aOvflSpace is set to a null pointer, this function returns 
53850 ** SQLITE_NOMEM.
53851 */
53852 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
53853 #pragma optimize("", off)
53854 #endif
53855 static int balance_nonroot(
53856   MemPage *pParent,               /* Parent page of siblings being balanced */
53857   int iParentIdx,                 /* Index of "the page" in pParent */
53858   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
53859   int isRoot,                     /* True if pParent is a root-page */
53860   int bBulk                       /* True if this call is part of a bulk load */
53861 ){
53862   BtShared *pBt;               /* The whole database */
53863   int nCell = 0;               /* Number of cells in apCell[] */
53864   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
53865   int nNew = 0;                /* Number of pages in apNew[] */
53866   int nOld;                    /* Number of pages in apOld[] */
53867   int i, j, k;                 /* Loop counters */
53868   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
53869   int rc = SQLITE_OK;          /* The return code */
53870   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
53871   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
53872   int usableSpace;             /* Bytes in pPage beyond the header */
53873   int pageFlags;               /* Value of pPage->aData[0] */
53874   int subtotal;                /* Subtotal of bytes in cells on one page */
53875   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
53876   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
53877   int szScratch;               /* Size of scratch memory requested */
53878   MemPage *apOld[NB];          /* pPage and up to two siblings */
53879   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
53880   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
53881   u8 *pRight;                  /* Location in parent of right-sibling pointer */
53882   u8 *apDiv[NB-1];             /* Divider cells in pParent */
53883   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
53884   int szNew[NB+2];             /* Combined size of cells place on i-th page */
53885   u8 **apCell = 0;             /* All cells begin balanced */
53886   u16 *szCell;                 /* Local size of all cells in apCell[] */
53887   u8 *aSpace1;                 /* Space for copies of dividers cells */
53888   Pgno pgno;                   /* Temp var to store a page number in */
53889
53890   pBt = pParent->pBt;
53891   assert( sqlite3_mutex_held(pBt->mutex) );
53892   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53893
53894 #if 0
53895   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
53896 #endif
53897
53898   /* At this point pParent may have at most one overflow cell. And if
53899   ** this overflow cell is present, it must be the cell with 
53900   ** index iParentIdx. This scenario comes about when this function
53901   ** is called (indirectly) from sqlite3BtreeDelete().
53902   */
53903   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
53904   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
53905
53906   if( !aOvflSpace ){
53907     return SQLITE_NOMEM;
53908   }
53909
53910   /* Find the sibling pages to balance. Also locate the cells in pParent 
53911   ** that divide the siblings. An attempt is made to find NN siblings on 
53912   ** either side of pPage. More siblings are taken from one side, however, 
53913   ** if there are fewer than NN siblings on the other side. If pParent
53914   ** has NB or fewer children then all children of pParent are taken.  
53915   **
53916   ** This loop also drops the divider cells from the parent page. This
53917   ** way, the remainder of the function does not have to deal with any
53918   ** overflow cells in the parent page, since if any existed they will
53919   ** have already been removed.
53920   */
53921   i = pParent->nOverflow + pParent->nCell;
53922   if( i<2 ){
53923     nxDiv = 0;
53924   }else{
53925     assert( bBulk==0 || bBulk==1 );
53926     if( iParentIdx==0 ){                 
53927       nxDiv = 0;
53928     }else if( iParentIdx==i ){
53929       nxDiv = i-2+bBulk;
53930     }else{
53931       assert( bBulk==0 );
53932       nxDiv = iParentIdx-1;
53933     }
53934     i = 2-bBulk;
53935   }
53936   nOld = i+1;
53937   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
53938     pRight = &pParent->aData[pParent->hdrOffset+8];
53939   }else{
53940     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
53941   }
53942   pgno = get4byte(pRight);
53943   while( 1 ){
53944     rc = getAndInitPage(pBt, pgno, &apOld[i]);
53945     if( rc ){
53946       memset(apOld, 0, (i+1)*sizeof(MemPage*));
53947       goto balance_cleanup;
53948     }
53949     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
53950     if( (i--)==0 ) break;
53951
53952     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
53953       apDiv[i] = pParent->apOvfl[0];
53954       pgno = get4byte(apDiv[i]);
53955       szNew[i] = cellSizePtr(pParent, apDiv[i]);
53956       pParent->nOverflow = 0;
53957     }else{
53958       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
53959       pgno = get4byte(apDiv[i]);
53960       szNew[i] = cellSizePtr(pParent, apDiv[i]);
53961
53962       /* Drop the cell from the parent page. apDiv[i] still points to
53963       ** the cell within the parent, even though it has been dropped.
53964       ** This is safe because dropping a cell only overwrites the first
53965       ** four bytes of it, and this function does not need the first
53966       ** four bytes of the divider cell. So the pointer is safe to use
53967       ** later on.  
53968       **
53969       ** But not if we are in secure-delete mode. In secure-delete mode,
53970       ** the dropCell() routine will overwrite the entire cell with zeroes.
53971       ** In this case, temporarily copy the cell into the aOvflSpace[]
53972       ** buffer. It will be copied out again as soon as the aSpace[] buffer
53973       ** is allocated.  */
53974       if( pBt->btsFlags & BTS_SECURE_DELETE ){
53975         int iOff;
53976
53977         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
53978         if( (iOff+szNew[i])>(int)pBt->usableSize ){
53979           rc = SQLITE_CORRUPT_BKPT;
53980           memset(apOld, 0, (i+1)*sizeof(MemPage*));
53981           goto balance_cleanup;
53982         }else{
53983           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
53984           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
53985         }
53986       }
53987       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
53988     }
53989   }
53990
53991   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
53992   ** alignment */
53993   nMaxCells = (nMaxCells + 3)&~3;
53994
53995   /*
53996   ** Allocate space for memory structures
53997   */
53998   k = pBt->pageSize + ROUND8(sizeof(MemPage));
53999   szScratch =
54000        nMaxCells*sizeof(u8*)                       /* apCell */
54001      + nMaxCells*sizeof(u16)                       /* szCell */
54002      + pBt->pageSize                               /* aSpace1 */
54003      + k*nOld;                                     /* Page copies (apCopy) */
54004   apCell = sqlite3ScratchMalloc( szScratch ); 
54005   if( apCell==0 ){
54006     rc = SQLITE_NOMEM;
54007     goto balance_cleanup;
54008   }
54009   szCell = (u16*)&apCell[nMaxCells];
54010   aSpace1 = (u8*)&szCell[nMaxCells];
54011   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54012
54013   /*
54014   ** Load pointers to all cells on sibling pages and the divider cells
54015   ** into the local apCell[] array.  Make copies of the divider cells
54016   ** into space obtained from aSpace1[] and remove the divider cells
54017   ** from pParent.
54018   **
54019   ** If the siblings are on leaf pages, then the child pointers of the
54020   ** divider cells are stripped from the cells before they are copied
54021   ** into aSpace1[].  In this way, all cells in apCell[] are without
54022   ** child pointers.  If siblings are not leaves, then all cell in
54023   ** apCell[] include child pointers.  Either way, all cells in apCell[]
54024   ** are alike.
54025   **
54026   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
54027   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
54028   */
54029   leafCorrection = apOld[0]->leaf*4;
54030   leafData = apOld[0]->hasData;
54031   for(i=0; i<nOld; i++){
54032     int limit;
54033     
54034     /* Before doing anything else, take a copy of the i'th original sibling
54035     ** The rest of this function will use data from the copies rather
54036     ** that the original pages since the original pages will be in the
54037     ** process of being overwritten.  */
54038     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54039     memcpy(pOld, apOld[i], sizeof(MemPage));
54040     pOld->aData = (void*)&pOld[1];
54041     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54042
54043     limit = pOld->nCell+pOld->nOverflow;
54044     if( pOld->nOverflow>0 ){
54045       for(j=0; j<limit; j++){
54046         assert( nCell<nMaxCells );
54047         apCell[nCell] = findOverflowCell(pOld, j);
54048         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54049         nCell++;
54050       }
54051     }else{
54052       u8 *aData = pOld->aData;
54053       u16 maskPage = pOld->maskPage;
54054       u16 cellOffset = pOld->cellOffset;
54055       for(j=0; j<limit; j++){
54056         assert( nCell<nMaxCells );
54057         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54058         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54059         nCell++;
54060       }
54061     }       
54062     if( i<nOld-1 && !leafData){
54063       u16 sz = (u16)szNew[i];
54064       u8 *pTemp;
54065       assert( nCell<nMaxCells );
54066       szCell[nCell] = sz;
54067       pTemp = &aSpace1[iSpace1];
54068       iSpace1 += sz;
54069       assert( sz<=pBt->maxLocal+23 );
54070       assert( iSpace1 <= (int)pBt->pageSize );
54071       memcpy(pTemp, apDiv[i], sz);
54072       apCell[nCell] = pTemp+leafCorrection;
54073       assert( leafCorrection==0 || leafCorrection==4 );
54074       szCell[nCell] = szCell[nCell] - leafCorrection;
54075       if( !pOld->leaf ){
54076         assert( leafCorrection==0 );
54077         assert( pOld->hdrOffset==0 );
54078         /* The right pointer of the child page pOld becomes the left
54079         ** pointer of the divider cell */
54080         memcpy(apCell[nCell], &pOld->aData[8], 4);
54081       }else{
54082         assert( leafCorrection==4 );
54083         if( szCell[nCell]<4 ){
54084           /* Do not allow any cells smaller than 4 bytes. */
54085           szCell[nCell] = 4;
54086         }
54087       }
54088       nCell++;
54089     }
54090   }
54091
54092   /*
54093   ** Figure out the number of pages needed to hold all nCell cells.
54094   ** Store this number in "k".  Also compute szNew[] which is the total
54095   ** size of all cells on the i-th page and cntNew[] which is the index
54096   ** in apCell[] of the cell that divides page i from page i+1.  
54097   ** cntNew[k] should equal nCell.
54098   **
54099   ** Values computed by this block:
54100   **
54101   **           k: The total number of sibling pages
54102   **    szNew[i]: Spaced used on the i-th sibling page.
54103   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54104   **              the right of the i-th sibling page.
54105   ** usableSpace: Number of bytes of space available on each sibling.
54106   ** 
54107   */
54108   usableSpace = pBt->usableSize - 12 + leafCorrection;
54109   for(subtotal=k=i=0; i<nCell; i++){
54110     assert( i<nMaxCells );
54111     subtotal += szCell[i] + 2;
54112     if( subtotal > usableSpace ){
54113       szNew[k] = subtotal - szCell[i];
54114       cntNew[k] = i;
54115       if( leafData ){ i--; }
54116       subtotal = 0;
54117       k++;
54118       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54119     }
54120   }
54121   szNew[k] = subtotal;
54122   cntNew[k] = nCell;
54123   k++;
54124
54125   /*
54126   ** The packing computed by the previous block is biased toward the siblings
54127   ** on the left side.  The left siblings are always nearly full, while the
54128   ** right-most sibling might be nearly empty.  This block of code attempts
54129   ** to adjust the packing of siblings to get a better balance.
54130   **
54131   ** This adjustment is more than an optimization.  The packing above might
54132   ** be so out of balance as to be illegal.  For example, the right-most
54133   ** sibling might be completely empty.  This adjustment is not optional.
54134   */
54135   for(i=k-1; i>0; i--){
54136     int szRight = szNew[i];  /* Size of sibling on the right */
54137     int szLeft = szNew[i-1]; /* Size of sibling on the left */
54138     int r;              /* Index of right-most cell in left sibling */
54139     int d;              /* Index of first cell to the left of right sibling */
54140
54141     r = cntNew[i-1] - 1;
54142     d = r + 1 - leafData;
54143     assert( d<nMaxCells );
54144     assert( r<nMaxCells );
54145     while( szRight==0 
54146        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
54147     ){
54148       szRight += szCell[d] + 2;
54149       szLeft -= szCell[r] + 2;
54150       cntNew[i-1]--;
54151       r = cntNew[i-1] - 1;
54152       d = r + 1 - leafData;
54153     }
54154     szNew[i] = szRight;
54155     szNew[i-1] = szLeft;
54156   }
54157
54158   /* Either we found one or more cells (cntnew[0])>0) or pPage is
54159   ** a virtual root page.  A virtual root page is when the real root
54160   ** page is page 1 and we are the only child of that page.
54161   **
54162   ** UPDATE:  The assert() below is not necessarily true if the database
54163   ** file is corrupt.  The corruption will be detected and reported later
54164   ** in this procedure so there is no need to act upon it now.
54165   */
54166 #if 0
54167   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54168 #endif
54169
54170   TRACE(("BALANCE: old: %d %d %d  ",
54171     apOld[0]->pgno, 
54172     nOld>=2 ? apOld[1]->pgno : 0,
54173     nOld>=3 ? apOld[2]->pgno : 0
54174   ));
54175
54176   /*
54177   ** Allocate k new pages.  Reuse old pages where possible.
54178   */
54179   if( apOld[0]->pgno<=1 ){
54180     rc = SQLITE_CORRUPT_BKPT;
54181     goto balance_cleanup;
54182   }
54183   pageFlags = apOld[0]->aData[0];
54184   for(i=0; i<k; i++){
54185     MemPage *pNew;
54186     if( i<nOld ){
54187       pNew = apNew[i] = apOld[i];
54188       apOld[i] = 0;
54189       rc = sqlite3PagerWrite(pNew->pDbPage);
54190       nNew++;
54191       if( rc ) goto balance_cleanup;
54192     }else{
54193       assert( i>0 );
54194       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
54195       if( rc ) goto balance_cleanup;
54196       apNew[i] = pNew;
54197       nNew++;
54198
54199       /* Set the pointer-map entry for the new sibling page. */
54200       if( ISAUTOVACUUM ){
54201         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54202         if( rc!=SQLITE_OK ){
54203           goto balance_cleanup;
54204         }
54205       }
54206     }
54207   }
54208
54209   /* Free any old pages that were not reused as new pages.
54210   */
54211   while( i<nOld ){
54212     freePage(apOld[i], &rc);
54213     if( rc ) goto balance_cleanup;
54214     releasePage(apOld[i]);
54215     apOld[i] = 0;
54216     i++;
54217   }
54218
54219   /*
54220   ** Put the new pages in accending order.  This helps to
54221   ** keep entries in the disk file in order so that a scan
54222   ** of the table is a linear scan through the file.  That
54223   ** in turn helps the operating system to deliver pages
54224   ** from the disk more rapidly.
54225   **
54226   ** An O(n^2) insertion sort algorithm is used, but since
54227   ** n is never more than NB (a small constant), that should
54228   ** not be a problem.
54229   **
54230   ** When NB==3, this one optimization makes the database
54231   ** about 25% faster for large insertions and deletions.
54232   */
54233   for(i=0; i<k-1; i++){
54234     int minV = apNew[i]->pgno;
54235     int minI = i;
54236     for(j=i+1; j<k; j++){
54237       if( apNew[j]->pgno<(unsigned)minV ){
54238         minI = j;
54239         minV = apNew[j]->pgno;
54240       }
54241     }
54242     if( minI>i ){
54243       MemPage *pT;
54244       pT = apNew[i];
54245       apNew[i] = apNew[minI];
54246       apNew[minI] = pT;
54247     }
54248   }
54249   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54250     apNew[0]->pgno, szNew[0],
54251     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54252     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54253     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54254     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54255
54256   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54257   put4byte(pRight, apNew[nNew-1]->pgno);
54258
54259   /*
54260   ** Evenly distribute the data in apCell[] across the new pages.
54261   ** Insert divider cells into pParent as necessary.
54262   */
54263   j = 0;
54264   for(i=0; i<nNew; i++){
54265     /* Assemble the new sibling page. */
54266     MemPage *pNew = apNew[i];
54267     assert( j<nMaxCells );
54268     zeroPage(pNew, pageFlags);
54269     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54270     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54271     assert( pNew->nOverflow==0 );
54272
54273     j = cntNew[i];
54274
54275     /* If the sibling page assembled above was not the right-most sibling,
54276     ** insert a divider cell into the parent page.
54277     */
54278     assert( i<nNew-1 || j==nCell );
54279     if( j<nCell ){
54280       u8 *pCell;
54281       u8 *pTemp;
54282       int sz;
54283
54284       assert( j<nMaxCells );
54285       pCell = apCell[j];
54286       sz = szCell[j] + leafCorrection;
54287       pTemp = &aOvflSpace[iOvflSpace];
54288       if( !pNew->leaf ){
54289         memcpy(&pNew->aData[8], pCell, 4);
54290       }else if( leafData ){
54291         /* If the tree is a leaf-data tree, and the siblings are leaves, 
54292         ** then there is no divider cell in apCell[]. Instead, the divider 
54293         ** cell consists of the integer key for the right-most cell of 
54294         ** the sibling-page assembled above only.
54295         */
54296         CellInfo info;
54297         j--;
54298         btreeParseCellPtr(pNew, apCell[j], &info);
54299         pCell = pTemp;
54300         sz = 4 + putVarint(&pCell[4], info.nKey);
54301         pTemp = 0;
54302       }else{
54303         pCell -= 4;
54304         /* Obscure case for non-leaf-data trees: If the cell at pCell was
54305         ** previously stored on a leaf node, and its reported size was 4
54306         ** bytes, then it may actually be smaller than this 
54307         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54308         ** any cell). But it is important to pass the correct size to 
54309         ** insertCell(), so reparse the cell now.
54310         **
54311         ** Note that this can never happen in an SQLite data file, as all
54312         ** cells are at least 4 bytes. It only happens in b-trees used
54313         ** to evaluate "IN (SELECT ...)" and similar clauses.
54314         */
54315         if( szCell[j]==4 ){
54316           assert(leafCorrection==4);
54317           sz = cellSizePtr(pParent, pCell);
54318         }
54319       }
54320       iOvflSpace += sz;
54321       assert( sz<=pBt->maxLocal+23 );
54322       assert( iOvflSpace <= (int)pBt->pageSize );
54323       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54324       if( rc!=SQLITE_OK ) goto balance_cleanup;
54325       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54326
54327       j++;
54328       nxDiv++;
54329     }
54330   }
54331   assert( j==nCell );
54332   assert( nOld>0 );
54333   assert( nNew>0 );
54334   if( (pageFlags & PTF_LEAF)==0 ){
54335     u8 *zChild = &apCopy[nOld-1]->aData[8];
54336     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54337   }
54338
54339   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54340     /* The root page of the b-tree now contains no cells. The only sibling
54341     ** page is the right-child of the parent. Copy the contents of the
54342     ** child page into the parent, decreasing the overall height of the
54343     ** b-tree structure by one. This is described as the "balance-shallower"
54344     ** sub-algorithm in some documentation.
54345     **
54346     ** If this is an auto-vacuum database, the call to copyNodeContent() 
54347     ** sets all pointer-map entries corresponding to database image pages 
54348     ** for which the pointer is stored within the content being copied.
54349     **
54350     ** The second assert below verifies that the child page is defragmented
54351     ** (it must be, as it was just reconstructed using assemblePage()). This
54352     ** is important if the parent page happens to be page 1 of the database
54353     ** image.  */
54354     assert( nNew==1 );
54355     assert( apNew[0]->nFree == 
54356         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
54357     );
54358     copyNodeContent(apNew[0], pParent, &rc);
54359     freePage(apNew[0], &rc);
54360   }else if( ISAUTOVACUUM ){
54361     /* Fix the pointer-map entries for all the cells that were shifted around. 
54362     ** There are several different types of pointer-map entries that need to
54363     ** be dealt with by this routine. Some of these have been set already, but
54364     ** many have not. The following is a summary:
54365     **
54366     **   1) The entries associated with new sibling pages that were not
54367     **      siblings when this function was called. These have already
54368     **      been set. We don't need to worry about old siblings that were
54369     **      moved to the free-list - the freePage() code has taken care
54370     **      of those.
54371     **
54372     **   2) The pointer-map entries associated with the first overflow
54373     **      page in any overflow chains used by new divider cells. These 
54374     **      have also already been taken care of by the insertCell() code.
54375     **
54376     **   3) If the sibling pages are not leaves, then the child pages of
54377     **      cells stored on the sibling pages may need to be updated.
54378     **
54379     **   4) If the sibling pages are not internal intkey nodes, then any
54380     **      overflow pages used by these cells may need to be updated
54381     **      (internal intkey nodes never contain pointers to overflow pages).
54382     **
54383     **   5) If the sibling pages are not leaves, then the pointer-map
54384     **      entries for the right-child pages of each sibling may need
54385     **      to be updated.
54386     **
54387     ** Cases 1 and 2 are dealt with above by other code. The next
54388     ** block deals with cases 3 and 4 and the one after that, case 5. Since
54389     ** setting a pointer map entry is a relatively expensive operation, this
54390     ** code only sets pointer map entries for child or overflow pages that have
54391     ** actually moved between pages.  */
54392     MemPage *pNew = apNew[0];
54393     MemPage *pOld = apCopy[0];
54394     int nOverflow = pOld->nOverflow;
54395     int iNextOld = pOld->nCell + nOverflow;
54396     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
54397     j = 0;                             /* Current 'old' sibling page */
54398     k = 0;                             /* Current 'new' sibling page */
54399     for(i=0; i<nCell; i++){
54400       int isDivider = 0;
54401       while( i==iNextOld ){
54402         /* Cell i is the cell immediately following the last cell on old
54403         ** sibling page j. If the siblings are not leaf pages of an
54404         ** intkey b-tree, then cell i was a divider cell. */
54405         assert( j+1 < ArraySize(apCopy) );
54406         assert( j+1 < nOld );
54407         pOld = apCopy[++j];
54408         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54409         if( pOld->nOverflow ){
54410           nOverflow = pOld->nOverflow;
54411           iOverflow = i + !leafData + pOld->aiOvfl[0];
54412         }
54413         isDivider = !leafData;  
54414       }
54415
54416       assert(nOverflow>0 || iOverflow<i );
54417       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
54418       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
54419       if( i==iOverflow ){
54420         isDivider = 1;
54421         if( (--nOverflow)>0 ){
54422           iOverflow++;
54423         }
54424       }
54425
54426       if( i==cntNew[k] ){
54427         /* Cell i is the cell immediately following the last cell on new
54428         ** sibling page k. If the siblings are not leaf pages of an
54429         ** intkey b-tree, then cell i is a divider cell.  */
54430         pNew = apNew[++k];
54431         if( !leafData ) continue;
54432       }
54433       assert( j<nOld );
54434       assert( k<nNew );
54435
54436       /* If the cell was originally divider cell (and is not now) or
54437       ** an overflow cell, or if the cell was located on a different sibling
54438       ** page before the balancing, then the pointer map entries associated
54439       ** with any child or overflow pages need to be updated.  */
54440       if( isDivider || pOld->pgno!=pNew->pgno ){
54441         if( !leafCorrection ){
54442           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
54443         }
54444         if( szCell[i]>pNew->minLocal ){
54445           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
54446         }
54447       }
54448     }
54449
54450     if( !leafCorrection ){
54451       for(i=0; i<nNew; i++){
54452         u32 key = get4byte(&apNew[i]->aData[8]);
54453         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
54454       }
54455     }
54456
54457 #if 0
54458     /* The ptrmapCheckPages() contains assert() statements that verify that
54459     ** all pointer map pages are set correctly. This is helpful while 
54460     ** debugging. This is usually disabled because a corrupt database may
54461     ** cause an assert() statement to fail.  */
54462     ptrmapCheckPages(apNew, nNew);
54463     ptrmapCheckPages(&pParent, 1);
54464 #endif
54465   }
54466
54467   assert( pParent->isInit );
54468   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
54469           nOld, nNew, nCell));
54470
54471   /*
54472   ** Cleanup before returning.
54473   */
54474 balance_cleanup:
54475   sqlite3ScratchFree(apCell);
54476   for(i=0; i<nOld; i++){
54477     releasePage(apOld[i]);
54478   }
54479   for(i=0; i<nNew; i++){
54480     releasePage(apNew[i]);
54481   }
54482
54483   return rc;
54484 }
54485 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
54486 #pragma optimize("", on)
54487 #endif
54488
54489
54490 /*
54491 ** This function is called when the root page of a b-tree structure is
54492 ** overfull (has one or more overflow pages).
54493 **
54494 ** A new child page is allocated and the contents of the current root
54495 ** page, including overflow cells, are copied into the child. The root
54496 ** page is then overwritten to make it an empty page with the right-child 
54497 ** pointer pointing to the new page.
54498 **
54499 ** Before returning, all pointer-map entries corresponding to pages 
54500 ** that the new child-page now contains pointers to are updated. The
54501 ** entry corresponding to the new right-child pointer of the root
54502 ** page is also updated.
54503 **
54504 ** If successful, *ppChild is set to contain a reference to the child 
54505 ** page and SQLITE_OK is returned. In this case the caller is required
54506 ** to call releasePage() on *ppChild exactly once. If an error occurs,
54507 ** an error code is returned and *ppChild is set to 0.
54508 */
54509 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
54510   int rc;                        /* Return value from subprocedures */
54511   MemPage *pChild = 0;           /* Pointer to a new child page */
54512   Pgno pgnoChild = 0;            /* Page number of the new child page */
54513   BtShared *pBt = pRoot->pBt;    /* The BTree */
54514
54515   assert( pRoot->nOverflow>0 );
54516   assert( sqlite3_mutex_held(pBt->mutex) );
54517
54518   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
54519   ** page that will become the new right-child of pPage. Copy the contents
54520   ** of the node stored on pRoot into the new child page.
54521   */
54522   rc = sqlite3PagerWrite(pRoot->pDbPage);
54523   if( rc==SQLITE_OK ){
54524     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
54525     copyNodeContent(pRoot, pChild, &rc);
54526     if( ISAUTOVACUUM ){
54527       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
54528     }
54529   }
54530   if( rc ){
54531     *ppChild = 0;
54532     releasePage(pChild);
54533     return rc;
54534   }
54535   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
54536   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54537   assert( pChild->nCell==pRoot->nCell );
54538
54539   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
54540
54541   /* Copy the overflow cells from pRoot to pChild */
54542   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
54543          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
54544   memcpy(pChild->apOvfl, pRoot->apOvfl,
54545          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
54546   pChild->nOverflow = pRoot->nOverflow;
54547
54548   /* Zero the contents of pRoot. Then install pChild as the right-child. */
54549   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
54550   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
54551
54552   *ppChild = pChild;
54553   return SQLITE_OK;
54554 }
54555
54556 /*
54557 ** The page that pCur currently points to has just been modified in
54558 ** some way. This function figures out if this modification means the
54559 ** tree needs to be balanced, and if so calls the appropriate balancing 
54560 ** routine. Balancing routines are:
54561 **
54562 **   balance_quick()
54563 **   balance_deeper()
54564 **   balance_nonroot()
54565 */
54566 static int balance(BtCursor *pCur){
54567   int rc = SQLITE_OK;
54568   const int nMin = pCur->pBt->usableSize * 2 / 3;
54569   u8 aBalanceQuickSpace[13];
54570   u8 *pFree = 0;
54571
54572   TESTONLY( int balance_quick_called = 0 );
54573   TESTONLY( int balance_deeper_called = 0 );
54574
54575   do {
54576     int iPage = pCur->iPage;
54577     MemPage *pPage = pCur->apPage[iPage];
54578
54579     if( iPage==0 ){
54580       if( pPage->nOverflow ){
54581         /* The root page of the b-tree is overfull. In this case call the
54582         ** balance_deeper() function to create a new child for the root-page
54583         ** and copy the current contents of the root-page to it. The
54584         ** next iteration of the do-loop will balance the child page.
54585         */ 
54586         assert( (balance_deeper_called++)==0 );
54587         rc = balance_deeper(pPage, &pCur->apPage[1]);
54588         if( rc==SQLITE_OK ){
54589           pCur->iPage = 1;
54590           pCur->aiIdx[0] = 0;
54591           pCur->aiIdx[1] = 0;
54592           assert( pCur->apPage[1]->nOverflow );
54593         }
54594       }else{
54595         break;
54596       }
54597     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
54598       break;
54599     }else{
54600       MemPage * const pParent = pCur->apPage[iPage-1];
54601       int const iIdx = pCur->aiIdx[iPage-1];
54602
54603       rc = sqlite3PagerWrite(pParent->pDbPage);
54604       if( rc==SQLITE_OK ){
54605 #ifndef SQLITE_OMIT_QUICKBALANCE
54606         if( pPage->hasData
54607          && pPage->nOverflow==1
54608          && pPage->aiOvfl[0]==pPage->nCell
54609          && pParent->pgno!=1
54610          && pParent->nCell==iIdx
54611         ){
54612           /* Call balance_quick() to create a new sibling of pPage on which
54613           ** to store the overflow cell. balance_quick() inserts a new cell
54614           ** into pParent, which may cause pParent overflow. If this
54615           ** happens, the next interation of the do-loop will balance pParent 
54616           ** use either balance_nonroot() or balance_deeper(). Until this
54617           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
54618           ** buffer. 
54619           **
54620           ** The purpose of the following assert() is to check that only a
54621           ** single call to balance_quick() is made for each call to this
54622           ** function. If this were not verified, a subtle bug involving reuse
54623           ** of the aBalanceQuickSpace[] might sneak in.
54624           */
54625           assert( (balance_quick_called++)==0 );
54626           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
54627         }else
54628 #endif
54629         {
54630           /* In this case, call balance_nonroot() to redistribute cells
54631           ** between pPage and up to 2 of its sibling pages. This involves
54632           ** modifying the contents of pParent, which may cause pParent to
54633           ** become overfull or underfull. The next iteration of the do-loop
54634           ** will balance the parent page to correct this.
54635           ** 
54636           ** If the parent page becomes overfull, the overflow cell or cells
54637           ** are stored in the pSpace buffer allocated immediately below. 
54638           ** A subsequent iteration of the do-loop will deal with this by
54639           ** calling balance_nonroot() (balance_deeper() may be called first,
54640           ** but it doesn't deal with overflow cells - just moves them to a
54641           ** different page). Once this subsequent call to balance_nonroot() 
54642           ** has completed, it is safe to release the pSpace buffer used by
54643           ** the previous call, as the overflow cell data will have been 
54644           ** copied either into the body of a database page or into the new
54645           ** pSpace buffer passed to the latter call to balance_nonroot().
54646           */
54647           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
54648           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
54649           if( pFree ){
54650             /* If pFree is not NULL, it points to the pSpace buffer used 
54651             ** by a previous call to balance_nonroot(). Its contents are
54652             ** now stored either on real database pages or within the 
54653             ** new pSpace buffer, so it may be safely freed here. */
54654             sqlite3PageFree(pFree);
54655           }
54656
54657           /* The pSpace buffer will be freed after the next call to
54658           ** balance_nonroot(), or just before this function returns, whichever
54659           ** comes first. */
54660           pFree = pSpace;
54661         }
54662       }
54663
54664       pPage->nOverflow = 0;
54665
54666       /* The next iteration of the do-loop balances the parent page. */
54667       releasePage(pPage);
54668       pCur->iPage--;
54669     }
54670   }while( rc==SQLITE_OK );
54671
54672   if( pFree ){
54673     sqlite3PageFree(pFree);
54674   }
54675   return rc;
54676 }
54677
54678
54679 /*
54680 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
54681 ** and the data is given by (pData,nData).  The cursor is used only to
54682 ** define what table the record should be inserted into.  The cursor
54683 ** is left pointing at a random location.
54684 **
54685 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
54686 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
54687 **
54688 ** If the seekResult parameter is non-zero, then a successful call to
54689 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
54690 ** been performed. seekResult is the search result returned (a negative
54691 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
54692 ** a positive value if pCur points at an etry that is larger than 
54693 ** (pKey, nKey)). 
54694 **
54695 ** If the seekResult parameter is non-zero, then the caller guarantees that
54696 ** cursor pCur is pointing at the existing copy of a row that is to be
54697 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
54698 ** point to any entry or to no entry at all and so this function has to seek
54699 ** the cursor before the new key can be inserted.
54700 */
54701 SQLITE_PRIVATE int sqlite3BtreeInsert(
54702   BtCursor *pCur,                /* Insert data into the table of this cursor */
54703   const void *pKey, i64 nKey,    /* The key of the new record */
54704   const void *pData, int nData,  /* The data of the new record */
54705   int nZero,                     /* Number of extra 0 bytes to append to data */
54706   int appendBias,                /* True if this is likely an append */
54707   int seekResult                 /* Result of prior MovetoUnpacked() call */
54708 ){
54709   int rc;
54710   int loc = seekResult;          /* -1: before desired location  +1: after */
54711   int szNew = 0;
54712   int idx;
54713   MemPage *pPage;
54714   Btree *p = pCur->pBtree;
54715   BtShared *pBt = p->pBt;
54716   unsigned char *oldCell;
54717   unsigned char *newCell = 0;
54718
54719   if( pCur->eState==CURSOR_FAULT ){
54720     assert( pCur->skipNext!=SQLITE_OK );
54721     return pCur->skipNext;
54722   }
54723
54724   assert( cursorHoldsMutex(pCur) );
54725   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
54726               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
54727   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54728
54729   /* Assert that the caller has been consistent. If this cursor was opened
54730   ** expecting an index b-tree, then the caller should be inserting blob
54731   ** keys with no associated data. If the cursor was opened expecting an
54732   ** intkey table, the caller should be inserting integer keys with a
54733   ** blob of associated data.  */
54734   assert( (pKey==0)==(pCur->pKeyInfo==0) );
54735
54736   /* Save the positions of any other cursors open on this table.
54737   **
54738   ** In some cases, the call to btreeMoveto() below is a no-op. For
54739   ** example, when inserting data into a table with auto-generated integer
54740   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
54741   ** integer key to use. It then calls this function to actually insert the 
54742   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
54743   ** that the cursor is already where it needs to be and returns without
54744   ** doing any work. To avoid thwarting these optimizations, it is important
54745   ** not to clear the cursor here.
54746   */
54747   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54748   if( rc ) return rc;
54749
54750   /* If this is an insert into a table b-tree, invalidate any incrblob 
54751   ** cursors open on the row being replaced (assuming this is a replace
54752   ** operation - if it is not, the following is a no-op).  */
54753   if( pCur->pKeyInfo==0 ){
54754     invalidateIncrblobCursors(p, nKey, 0);
54755   }
54756
54757   if( !loc ){
54758     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
54759     if( rc ) return rc;
54760   }
54761   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
54762
54763   pPage = pCur->apPage[pCur->iPage];
54764   assert( pPage->intKey || nKey>=0 );
54765   assert( pPage->leaf || !pPage->intKey );
54766
54767   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
54768           pCur->pgnoRoot, nKey, nData, pPage->pgno,
54769           loc==0 ? "overwrite" : "new entry"));
54770   assert( pPage->isInit );
54771   allocateTempSpace(pBt);
54772   newCell = pBt->pTmpSpace;
54773   if( newCell==0 ) return SQLITE_NOMEM;
54774   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
54775   if( rc ) goto end_insert;
54776   assert( szNew==cellSizePtr(pPage, newCell) );
54777   assert( szNew <= MX_CELL_SIZE(pBt) );
54778   idx = pCur->aiIdx[pCur->iPage];
54779   if( loc==0 ){
54780     u16 szOld;
54781     assert( idx<pPage->nCell );
54782     rc = sqlite3PagerWrite(pPage->pDbPage);
54783     if( rc ){
54784       goto end_insert;
54785     }
54786     oldCell = findCell(pPage, idx);
54787     if( !pPage->leaf ){
54788       memcpy(newCell, oldCell, 4);
54789     }
54790     szOld = cellSizePtr(pPage, oldCell);
54791     rc = clearCell(pPage, oldCell);
54792     dropCell(pPage, idx, szOld, &rc);
54793     if( rc ) goto end_insert;
54794   }else if( loc<0 && pPage->nCell>0 ){
54795     assert( pPage->leaf );
54796     idx = ++pCur->aiIdx[pCur->iPage];
54797   }else{
54798     assert( pPage->leaf );
54799   }
54800   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
54801   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
54802
54803   /* If no error has occured and pPage has an overflow cell, call balance() 
54804   ** to redistribute the cells within the tree. Since balance() may move
54805   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
54806   ** variables.
54807   **
54808   ** Previous versions of SQLite called moveToRoot() to move the cursor
54809   ** back to the root page as balance() used to invalidate the contents
54810   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
54811   ** set the cursor state to "invalid". This makes common insert operations
54812   ** slightly faster.
54813   **
54814   ** There is a subtle but important optimization here too. When inserting
54815   ** multiple records into an intkey b-tree using a single cursor (as can
54816   ** happen while processing an "INSERT INTO ... SELECT" statement), it
54817   ** is advantageous to leave the cursor pointing to the last entry in
54818   ** the b-tree if possible. If the cursor is left pointing to the last
54819   ** entry in the table, and the next row inserted has an integer key
54820   ** larger than the largest existing key, it is possible to insert the
54821   ** row without seeking the cursor. This can be a big performance boost.
54822   */
54823   pCur->info.nSize = 0;
54824   pCur->validNKey = 0;
54825   if( rc==SQLITE_OK && pPage->nOverflow ){
54826     rc = balance(pCur);
54827
54828     /* Must make sure nOverflow is reset to zero even if the balance()
54829     ** fails. Internal data structure corruption will result otherwise. 
54830     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
54831     ** from trying to save the current position of the cursor.  */
54832     pCur->apPage[pCur->iPage]->nOverflow = 0;
54833     pCur->eState = CURSOR_INVALID;
54834   }
54835   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
54836
54837 end_insert:
54838   return rc;
54839 }
54840
54841 /*
54842 ** Delete the entry that the cursor is pointing to.  The cursor
54843 ** is left pointing at a arbitrary location.
54844 */
54845 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
54846   Btree *p = pCur->pBtree;
54847   BtShared *pBt = p->pBt;              
54848   int rc;                              /* Return code */
54849   MemPage *pPage;                      /* Page to delete cell from */
54850   unsigned char *pCell;                /* Pointer to cell to delete */
54851   int iCellIdx;                        /* Index of cell to delete */
54852   int iCellDepth;                      /* Depth of node containing pCell */ 
54853
54854   assert( cursorHoldsMutex(pCur) );
54855   assert( pBt->inTransaction==TRANS_WRITE );
54856   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
54857   assert( pCur->wrFlag );
54858   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54859   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
54860
54861   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
54862    || NEVER(pCur->eState!=CURSOR_VALID)
54863   ){
54864     return SQLITE_ERROR;  /* Something has gone awry. */
54865   }
54866
54867   iCellDepth = pCur->iPage;
54868   iCellIdx = pCur->aiIdx[iCellDepth];
54869   pPage = pCur->apPage[iCellDepth];
54870   pCell = findCell(pPage, iCellIdx);
54871
54872   /* If the page containing the entry to delete is not a leaf page, move
54873   ** the cursor to the largest entry in the tree that is smaller than
54874   ** the entry being deleted. This cell will replace the cell being deleted
54875   ** from the internal node. The 'previous' entry is used for this instead
54876   ** of the 'next' entry, as the previous entry is always a part of the
54877   ** sub-tree headed by the child page of the cell being deleted. This makes
54878   ** balancing the tree following the delete operation easier.  */
54879   if( !pPage->leaf ){
54880     int notUsed;
54881     rc = sqlite3BtreePrevious(pCur, &notUsed);
54882     if( rc ) return rc;
54883   }
54884
54885   /* Save the positions of any other cursors open on this table before
54886   ** making any modifications. Make the page containing the entry to be 
54887   ** deleted writable. Then free any overflow pages associated with the 
54888   ** entry and finally remove the cell itself from within the page.  
54889   */
54890   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54891   if( rc ) return rc;
54892
54893   /* If this is a delete operation to remove a row from a table b-tree,
54894   ** invalidate any incrblob cursors open on the row being deleted.  */
54895   if( pCur->pKeyInfo==0 ){
54896     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
54897   }
54898
54899   rc = sqlite3PagerWrite(pPage->pDbPage);
54900   if( rc ) return rc;
54901   rc = clearCell(pPage, pCell);
54902   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
54903   if( rc ) return rc;
54904
54905   /* If the cell deleted was not located on a leaf page, then the cursor
54906   ** is currently pointing to the largest entry in the sub-tree headed
54907   ** by the child-page of the cell that was just deleted from an internal
54908   ** node. The cell from the leaf node needs to be moved to the internal
54909   ** node to replace the deleted cell.  */
54910   if( !pPage->leaf ){
54911     MemPage *pLeaf = pCur->apPage[pCur->iPage];
54912     int nCell;
54913     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
54914     unsigned char *pTmp;
54915
54916     pCell = findCell(pLeaf, pLeaf->nCell-1);
54917     nCell = cellSizePtr(pLeaf, pCell);
54918     assert( MX_CELL_SIZE(pBt) >= nCell );
54919
54920     allocateTempSpace(pBt);
54921     pTmp = pBt->pTmpSpace;
54922
54923     rc = sqlite3PagerWrite(pLeaf->pDbPage);
54924     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
54925     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
54926     if( rc ) return rc;
54927   }
54928
54929   /* Balance the tree. If the entry deleted was located on a leaf page,
54930   ** then the cursor still points to that page. In this case the first
54931   ** call to balance() repairs the tree, and the if(...) condition is
54932   ** never true.
54933   **
54934   ** Otherwise, if the entry deleted was on an internal node page, then
54935   ** pCur is pointing to the leaf page from which a cell was removed to
54936   ** replace the cell deleted from the internal node. This is slightly
54937   ** tricky as the leaf node may be underfull, and the internal node may
54938   ** be either under or overfull. In this case run the balancing algorithm
54939   ** on the leaf node first. If the balance proceeds far enough up the
54940   ** tree that we can be sure that any problem in the internal node has
54941   ** been corrected, so be it. Otherwise, after balancing the leaf node,
54942   ** walk the cursor up the tree to the internal node and balance it as 
54943   ** well.  */
54944   rc = balance(pCur);
54945   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
54946     while( pCur->iPage>iCellDepth ){
54947       releasePage(pCur->apPage[pCur->iPage--]);
54948     }
54949     rc = balance(pCur);
54950   }
54951
54952   if( rc==SQLITE_OK ){
54953     moveToRoot(pCur);
54954   }
54955   return rc;
54956 }
54957
54958 /*
54959 ** Create a new BTree table.  Write into *piTable the page
54960 ** number for the root page of the new table.
54961 **
54962 ** The type of type is determined by the flags parameter.  Only the
54963 ** following values of flags are currently in use.  Other values for
54964 ** flags might not work:
54965 **
54966 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
54967 **     BTREE_ZERODATA                  Used for SQL indices
54968 */
54969 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
54970   BtShared *pBt = p->pBt;
54971   MemPage *pRoot;
54972   Pgno pgnoRoot;
54973   int rc;
54974   int ptfFlags;          /* Page-type flage for the root page of new table */
54975
54976   assert( sqlite3BtreeHoldsMutex(p) );
54977   assert( pBt->inTransaction==TRANS_WRITE );
54978   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
54979
54980 #ifdef SQLITE_OMIT_AUTOVACUUM
54981   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54982   if( rc ){
54983     return rc;
54984   }
54985 #else
54986   if( pBt->autoVacuum ){
54987     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
54988     MemPage *pPageMove; /* The page to move to. */
54989
54990     /* Creating a new table may probably require moving an existing database
54991     ** to make room for the new tables root page. In case this page turns
54992     ** out to be an overflow page, delete all overflow page-map caches
54993     ** held by open cursors.
54994     */
54995     invalidateAllOverflowCache(pBt);
54996
54997     /* Read the value of meta[3] from the database to determine where the
54998     ** root page of the new table should go. meta[3] is the largest root-page
54999     ** created so far, so the new root-page is (meta[3]+1).
55000     */
55001     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55002     pgnoRoot++;
55003
55004     /* The new root-page may not be allocated on a pointer-map page, or the
55005     ** PENDING_BYTE page.
55006     */
55007     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55008         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55009       pgnoRoot++;
55010     }
55011     assert( pgnoRoot>=3 );
55012
55013     /* Allocate a page. The page that currently resides at pgnoRoot will
55014     ** be moved to the allocated page (unless the allocated page happens
55015     ** to reside at pgnoRoot).
55016     */
55017     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
55018     if( rc!=SQLITE_OK ){
55019       return rc;
55020     }
55021
55022     if( pgnoMove!=pgnoRoot ){
55023       /* pgnoRoot is the page that will be used for the root-page of
55024       ** the new table (assuming an error did not occur). But we were
55025       ** allocated pgnoMove. If required (i.e. if it was not allocated
55026       ** by extending the file), the current page at position pgnoMove
55027       ** is already journaled.
55028       */
55029       u8 eType = 0;
55030       Pgno iPtrPage = 0;
55031
55032       releasePage(pPageMove);
55033
55034       /* Move the page currently at pgnoRoot to pgnoMove. */
55035       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55036       if( rc!=SQLITE_OK ){
55037         return rc;
55038       }
55039       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55040       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55041         rc = SQLITE_CORRUPT_BKPT;
55042       }
55043       if( rc!=SQLITE_OK ){
55044         releasePage(pRoot);
55045         return rc;
55046       }
55047       assert( eType!=PTRMAP_ROOTPAGE );
55048       assert( eType!=PTRMAP_FREEPAGE );
55049       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55050       releasePage(pRoot);
55051
55052       /* Obtain the page at pgnoRoot */
55053       if( rc!=SQLITE_OK ){
55054         return rc;
55055       }
55056       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55057       if( rc!=SQLITE_OK ){
55058         return rc;
55059       }
55060       rc = sqlite3PagerWrite(pRoot->pDbPage);
55061       if( rc!=SQLITE_OK ){
55062         releasePage(pRoot);
55063         return rc;
55064       }
55065     }else{
55066       pRoot = pPageMove;
55067     } 
55068
55069     /* Update the pointer-map and meta-data with the new root-page number. */
55070     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55071     if( rc ){
55072       releasePage(pRoot);
55073       return rc;
55074     }
55075
55076     /* When the new root page was allocated, page 1 was made writable in
55077     ** order either to increase the database filesize, or to decrement the
55078     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55079     */
55080     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55081     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55082     if( NEVER(rc) ){
55083       releasePage(pRoot);
55084       return rc;
55085     }
55086
55087   }else{
55088     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55089     if( rc ) return rc;
55090   }
55091 #endif
55092   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55093   if( createTabFlags & BTREE_INTKEY ){
55094     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55095   }else{
55096     ptfFlags = PTF_ZERODATA | PTF_LEAF;
55097   }
55098   zeroPage(pRoot, ptfFlags);
55099   sqlite3PagerUnref(pRoot->pDbPage);
55100   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55101   *piTable = (int)pgnoRoot;
55102   return SQLITE_OK;
55103 }
55104 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55105   int rc;
55106   sqlite3BtreeEnter(p);
55107   rc = btreeCreateTable(p, piTable, flags);
55108   sqlite3BtreeLeave(p);
55109   return rc;
55110 }
55111
55112 /*
55113 ** Erase the given database page and all its children.  Return
55114 ** the page to the freelist.
55115 */
55116 static int clearDatabasePage(
55117   BtShared *pBt,           /* The BTree that contains the table */
55118   Pgno pgno,               /* Page number to clear */
55119   int freePageFlag,        /* Deallocate page if true */
55120   int *pnChange            /* Add number of Cells freed to this counter */
55121 ){
55122   MemPage *pPage;
55123   int rc;
55124   unsigned char *pCell;
55125   int i;
55126
55127   assert( sqlite3_mutex_held(pBt->mutex) );
55128   if( pgno>btreePagecount(pBt) ){
55129     return SQLITE_CORRUPT_BKPT;
55130   }
55131
55132   rc = getAndInitPage(pBt, pgno, &pPage);
55133   if( rc ) return rc;
55134   for(i=0; i<pPage->nCell; i++){
55135     pCell = findCell(pPage, i);
55136     if( !pPage->leaf ){
55137       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55138       if( rc ) goto cleardatabasepage_out;
55139     }
55140     rc = clearCell(pPage, pCell);
55141     if( rc ) goto cleardatabasepage_out;
55142   }
55143   if( !pPage->leaf ){
55144     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55145     if( rc ) goto cleardatabasepage_out;
55146   }else if( pnChange ){
55147     assert( pPage->intKey );
55148     *pnChange += pPage->nCell;
55149   }
55150   if( freePageFlag ){
55151     freePage(pPage, &rc);
55152   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55153     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55154   }
55155
55156 cleardatabasepage_out:
55157   releasePage(pPage);
55158   return rc;
55159 }
55160
55161 /*
55162 ** Delete all information from a single table in the database.  iTable is
55163 ** the page number of the root of the table.  After this routine returns,
55164 ** the root page is empty, but still exists.
55165 **
55166 ** This routine will fail with SQLITE_LOCKED if there are any open
55167 ** read cursors on the table.  Open write cursors are moved to the
55168 ** root of the table.
55169 **
55170 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55171 ** integer value pointed to by pnChange is incremented by the number of
55172 ** entries in the table.
55173 */
55174 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55175   int rc;
55176   BtShared *pBt = p->pBt;
55177   sqlite3BtreeEnter(p);
55178   assert( p->inTrans==TRANS_WRITE );
55179
55180   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55181
55182   if( SQLITE_OK==rc ){
55183     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55184     ** is the root of a table b-tree - if it is not, the following call is
55185     ** a no-op).  */
55186     invalidateIncrblobCursors(p, 0, 1);
55187     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55188   }
55189   sqlite3BtreeLeave(p);
55190   return rc;
55191 }
55192
55193 /*
55194 ** Erase all information in a table and add the root of the table to
55195 ** the freelist.  Except, the root of the principle table (the one on
55196 ** page 1) is never added to the freelist.
55197 **
55198 ** This routine will fail with SQLITE_LOCKED if there are any open
55199 ** cursors on the table.
55200 **
55201 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55202 ** root page in the database file, then the last root page 
55203 ** in the database file is moved into the slot formerly occupied by
55204 ** iTable and that last slot formerly occupied by the last root page
55205 ** is added to the freelist instead of iTable.  In this say, all
55206 ** root pages are kept at the beginning of the database file, which
55207 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
55208 ** page number that used to be the last root page in the file before
55209 ** the move.  If no page gets moved, *piMoved is set to 0.
55210 ** The last root page is recorded in meta[3] and the value of
55211 ** meta[3] is updated by this procedure.
55212 */
55213 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55214   int rc;
55215   MemPage *pPage = 0;
55216   BtShared *pBt = p->pBt;
55217
55218   assert( sqlite3BtreeHoldsMutex(p) );
55219   assert( p->inTrans==TRANS_WRITE );
55220
55221   /* It is illegal to drop a table if any cursors are open on the
55222   ** database. This is because in auto-vacuum mode the backend may
55223   ** need to move another root-page to fill a gap left by the deleted
55224   ** root page. If an open cursor was using this page a problem would 
55225   ** occur.
55226   **
55227   ** This error is caught long before control reaches this point.
55228   */
55229   if( NEVER(pBt->pCursor) ){
55230     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55231     return SQLITE_LOCKED_SHAREDCACHE;
55232   }
55233
55234   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55235   if( rc ) return rc;
55236   rc = sqlite3BtreeClearTable(p, iTable, 0);
55237   if( rc ){
55238     releasePage(pPage);
55239     return rc;
55240   }
55241
55242   *piMoved = 0;
55243
55244   if( iTable>1 ){
55245 #ifdef SQLITE_OMIT_AUTOVACUUM
55246     freePage(pPage, &rc);
55247     releasePage(pPage);
55248 #else
55249     if( pBt->autoVacuum ){
55250       Pgno maxRootPgno;
55251       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55252
55253       if( iTable==maxRootPgno ){
55254         /* If the table being dropped is the table with the largest root-page
55255         ** number in the database, put the root page on the free list. 
55256         */
55257         freePage(pPage, &rc);
55258         releasePage(pPage);
55259         if( rc!=SQLITE_OK ){
55260           return rc;
55261         }
55262       }else{
55263         /* The table being dropped does not have the largest root-page
55264         ** number in the database. So move the page that does into the 
55265         ** gap left by the deleted root-page.
55266         */
55267         MemPage *pMove;
55268         releasePage(pPage);
55269         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55270         if( rc!=SQLITE_OK ){
55271           return rc;
55272         }
55273         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55274         releasePage(pMove);
55275         if( rc!=SQLITE_OK ){
55276           return rc;
55277         }
55278         pMove = 0;
55279         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55280         freePage(pMove, &rc);
55281         releasePage(pMove);
55282         if( rc!=SQLITE_OK ){
55283           return rc;
55284         }
55285         *piMoved = maxRootPgno;
55286       }
55287
55288       /* Set the new 'max-root-page' value in the database header. This
55289       ** is the old value less one, less one more if that happens to
55290       ** be a root-page number, less one again if that is the
55291       ** PENDING_BYTE_PAGE.
55292       */
55293       maxRootPgno--;
55294       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55295              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55296         maxRootPgno--;
55297       }
55298       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55299
55300       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55301     }else{
55302       freePage(pPage, &rc);
55303       releasePage(pPage);
55304     }
55305 #endif
55306   }else{
55307     /* If sqlite3BtreeDropTable was called on page 1.
55308     ** This really never should happen except in a corrupt
55309     ** database. 
55310     */
55311     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55312     releasePage(pPage);
55313   }
55314   return rc;  
55315 }
55316 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55317   int rc;
55318   sqlite3BtreeEnter(p);
55319   rc = btreeDropTable(p, iTable, piMoved);
55320   sqlite3BtreeLeave(p);
55321   return rc;
55322 }
55323
55324
55325 /*
55326 ** This function may only be called if the b-tree connection already
55327 ** has a read or write transaction open on the database.
55328 **
55329 ** Read the meta-information out of a database file.  Meta[0]
55330 ** is the number of free pages currently in the database.  Meta[1]
55331 ** through meta[15] are available for use by higher layers.  Meta[0]
55332 ** is read-only, the others are read/write.
55333 ** 
55334 ** The schema layer numbers meta values differently.  At the schema
55335 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55336 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
55337 */
55338 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55339   BtShared *pBt = p->pBt;
55340
55341   sqlite3BtreeEnter(p);
55342   assert( p->inTrans>TRANS_NONE );
55343   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55344   assert( pBt->pPage1 );
55345   assert( idx>=0 && idx<=15 );
55346
55347   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55348
55349   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55350   ** database, mark the database as read-only.  */
55351 #ifdef SQLITE_OMIT_AUTOVACUUM
55352   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
55353     pBt->btsFlags |= BTS_READ_ONLY;
55354   }
55355 #endif
55356
55357   sqlite3BtreeLeave(p);
55358 }
55359
55360 /*
55361 ** Write meta-information back into the database.  Meta[0] is
55362 ** read-only and may not be written.
55363 */
55364 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55365   BtShared *pBt = p->pBt;
55366   unsigned char *pP1;
55367   int rc;
55368   assert( idx>=1 && idx<=15 );
55369   sqlite3BtreeEnter(p);
55370   assert( p->inTrans==TRANS_WRITE );
55371   assert( pBt->pPage1!=0 );
55372   pP1 = pBt->pPage1->aData;
55373   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55374   if( rc==SQLITE_OK ){
55375     put4byte(&pP1[36 + idx*4], iMeta);
55376 #ifndef SQLITE_OMIT_AUTOVACUUM
55377     if( idx==BTREE_INCR_VACUUM ){
55378       assert( pBt->autoVacuum || iMeta==0 );
55379       assert( iMeta==0 || iMeta==1 );
55380       pBt->incrVacuum = (u8)iMeta;
55381     }
55382 #endif
55383   }
55384   sqlite3BtreeLeave(p);
55385   return rc;
55386 }
55387
55388 #ifndef SQLITE_OMIT_BTREECOUNT
55389 /*
55390 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55391 ** number of entries in the b-tree and write the result to *pnEntry.
55392 **
55393 ** SQLITE_OK is returned if the operation is successfully executed. 
55394 ** Otherwise, if an error is encountered (i.e. an IO error or database
55395 ** corruption) an SQLite error code is returned.
55396 */
55397 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55398   i64 nEntry = 0;                      /* Value to return in *pnEntry */
55399   int rc;                              /* Return code */
55400
55401   if( pCur->pgnoRoot==0 ){
55402     *pnEntry = 0;
55403     return SQLITE_OK;
55404   }
55405   rc = moveToRoot(pCur);
55406
55407   /* Unless an error occurs, the following loop runs one iteration for each
55408   ** page in the B-Tree structure (not including overflow pages). 
55409   */
55410   while( rc==SQLITE_OK ){
55411     int iIdx;                          /* Index of child node in parent */
55412     MemPage *pPage;                    /* Current page of the b-tree */
55413
55414     /* If this is a leaf page or the tree is not an int-key tree, then 
55415     ** this page contains countable entries. Increment the entry counter
55416     ** accordingly.
55417     */
55418     pPage = pCur->apPage[pCur->iPage];
55419     if( pPage->leaf || !pPage->intKey ){
55420       nEntry += pPage->nCell;
55421     }
55422
55423     /* pPage is a leaf node. This loop navigates the cursor so that it 
55424     ** points to the first interior cell that it points to the parent of
55425     ** the next page in the tree that has not yet been visited. The
55426     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
55427     ** of the page, or to the number of cells in the page if the next page
55428     ** to visit is the right-child of its parent.
55429     **
55430     ** If all pages in the tree have been visited, return SQLITE_OK to the
55431     ** caller.
55432     */
55433     if( pPage->leaf ){
55434       do {
55435         if( pCur->iPage==0 ){
55436           /* All pages of the b-tree have been visited. Return successfully. */
55437           *pnEntry = nEntry;
55438           return SQLITE_OK;
55439         }
55440         moveToParent(pCur);
55441       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
55442
55443       pCur->aiIdx[pCur->iPage]++;
55444       pPage = pCur->apPage[pCur->iPage];
55445     }
55446
55447     /* Descend to the child node of the cell that the cursor currently 
55448     ** points at. This is the right-child if (iIdx==pPage->nCell).
55449     */
55450     iIdx = pCur->aiIdx[pCur->iPage];
55451     if( iIdx==pPage->nCell ){
55452       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
55453     }else{
55454       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
55455     }
55456   }
55457
55458   /* An error has occurred. Return an error code. */
55459   return rc;
55460 }
55461 #endif
55462
55463 /*
55464 ** Return the pager associated with a BTree.  This routine is used for
55465 ** testing and debugging only.
55466 */
55467 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
55468   return p->pBt->pPager;
55469 }
55470
55471 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55472 /*
55473 ** Append a message to the error message string.
55474 */
55475 static void checkAppendMsg(
55476   IntegrityCk *pCheck,
55477   char *zMsg1,
55478   const char *zFormat,
55479   ...
55480 ){
55481   va_list ap;
55482   if( !pCheck->mxErr ) return;
55483   pCheck->mxErr--;
55484   pCheck->nErr++;
55485   va_start(ap, zFormat);
55486   if( pCheck->errMsg.nChar ){
55487     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
55488   }
55489   if( zMsg1 ){
55490     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
55491   }
55492   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
55493   va_end(ap);
55494   if( pCheck->errMsg.mallocFailed ){
55495     pCheck->mallocFailed = 1;
55496   }
55497 }
55498 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55499
55500 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55501
55502 /*
55503 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
55504 ** corresponds to page iPg is already set.
55505 */
55506 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
55507   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
55508   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
55509 }
55510
55511 /*
55512 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
55513 */
55514 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
55515   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
55516   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
55517 }
55518
55519
55520 /*
55521 ** Add 1 to the reference count for page iPage.  If this is the second
55522 ** reference to the page, add an error message to pCheck->zErrMsg.
55523 ** Return 1 if there are 2 ore more references to the page and 0 if
55524 ** if this is the first reference to the page.
55525 **
55526 ** Also check that the page number is in bounds.
55527 */
55528 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
55529   if( iPage==0 ) return 1;
55530   if( iPage>pCheck->nPage ){
55531     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
55532     return 1;
55533   }
55534   if( getPageReferenced(pCheck, iPage) ){
55535     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
55536     return 1;
55537   }
55538   setPageReferenced(pCheck, iPage);
55539   return 0;
55540 }
55541
55542 #ifndef SQLITE_OMIT_AUTOVACUUM
55543 /*
55544 ** Check that the entry in the pointer-map for page iChild maps to 
55545 ** page iParent, pointer type ptrType. If not, append an error message
55546 ** to pCheck.
55547 */
55548 static void checkPtrmap(
55549   IntegrityCk *pCheck,   /* Integrity check context */
55550   Pgno iChild,           /* Child page number */
55551   u8 eType,              /* Expected pointer map type */
55552   Pgno iParent,          /* Expected pointer map parent page number */
55553   char *zContext         /* Context description (used for error msg) */
55554 ){
55555   int rc;
55556   u8 ePtrmapType;
55557   Pgno iPtrmapParent;
55558
55559   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
55560   if( rc!=SQLITE_OK ){
55561     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
55562     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
55563     return;
55564   }
55565
55566   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
55567     checkAppendMsg(pCheck, zContext, 
55568       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
55569       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
55570   }
55571 }
55572 #endif
55573
55574 /*
55575 ** Check the integrity of the freelist or of an overflow page list.
55576 ** Verify that the number of pages on the list is N.
55577 */
55578 static void checkList(
55579   IntegrityCk *pCheck,  /* Integrity checking context */
55580   int isFreeList,       /* True for a freelist.  False for overflow page list */
55581   int iPage,            /* Page number for first page in the list */
55582   int N,                /* Expected number of pages in the list */
55583   char *zContext        /* Context for error messages */
55584 ){
55585   int i;
55586   int expected = N;
55587   int iFirst = iPage;
55588   while( N-- > 0 && pCheck->mxErr ){
55589     DbPage *pOvflPage;
55590     unsigned char *pOvflData;
55591     if( iPage<1 ){
55592       checkAppendMsg(pCheck, zContext,
55593          "%d of %d pages missing from overflow list starting at %d",
55594           N+1, expected, iFirst);
55595       break;
55596     }
55597     if( checkRef(pCheck, iPage, zContext) ) break;
55598     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
55599       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
55600       break;
55601     }
55602     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
55603     if( isFreeList ){
55604       int n = get4byte(&pOvflData[4]);
55605 #ifndef SQLITE_OMIT_AUTOVACUUM
55606       if( pCheck->pBt->autoVacuum ){
55607         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
55608       }
55609 #endif
55610       if( n>(int)pCheck->pBt->usableSize/4-2 ){
55611         checkAppendMsg(pCheck, zContext,
55612            "freelist leaf count too big on page %d", iPage);
55613         N--;
55614       }else{
55615         for(i=0; i<n; i++){
55616           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
55617 #ifndef SQLITE_OMIT_AUTOVACUUM
55618           if( pCheck->pBt->autoVacuum ){
55619             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
55620           }
55621 #endif
55622           checkRef(pCheck, iFreePage, zContext);
55623         }
55624         N -= n;
55625       }
55626     }
55627 #ifndef SQLITE_OMIT_AUTOVACUUM
55628     else{
55629       /* If this database supports auto-vacuum and iPage is not the last
55630       ** page in this overflow list, check that the pointer-map entry for
55631       ** the following page matches iPage.
55632       */
55633       if( pCheck->pBt->autoVacuum && N>0 ){
55634         i = get4byte(pOvflData);
55635         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
55636       }
55637     }
55638 #endif
55639     iPage = get4byte(pOvflData);
55640     sqlite3PagerUnref(pOvflPage);
55641   }
55642 }
55643 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55644
55645 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55646 /*
55647 ** Do various sanity checks on a single page of a tree.  Return
55648 ** the tree depth.  Root pages return 0.  Parents of root pages
55649 ** return 1, and so forth.
55650 ** 
55651 ** These checks are done:
55652 **
55653 **      1.  Make sure that cells and freeblocks do not overlap
55654 **          but combine to completely cover the page.
55655 **  NO  2.  Make sure cell keys are in order.
55656 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
55657 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
55658 **      5.  Check the integrity of overflow pages.
55659 **      6.  Recursively call checkTreePage on all children.
55660 **      7.  Verify that the depth of all children is the same.
55661 **      8.  Make sure this page is at least 33% full or else it is
55662 **          the root of the tree.
55663 */
55664 static int checkTreePage(
55665   IntegrityCk *pCheck,  /* Context for the sanity check */
55666   int iPage,            /* Page number of the page to check */
55667   char *zParentContext, /* Parent context */
55668   i64 *pnParentMinKey, 
55669   i64 *pnParentMaxKey
55670 ){
55671   MemPage *pPage;
55672   int i, rc, depth, d2, pgno, cnt;
55673   int hdr, cellStart;
55674   int nCell;
55675   u8 *data;
55676   BtShared *pBt;
55677   int usableSize;
55678   char zContext[100];
55679   char *hit = 0;
55680   i64 nMinKey = 0;
55681   i64 nMaxKey = 0;
55682
55683   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
55684
55685   /* Check that the page exists
55686   */
55687   pBt = pCheck->pBt;
55688   usableSize = pBt->usableSize;
55689   if( iPage==0 ) return 0;
55690   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
55691   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
55692     checkAppendMsg(pCheck, zContext,
55693        "unable to get the page. error code=%d", rc);
55694     return 0;
55695   }
55696
55697   /* Clear MemPage.isInit to make sure the corruption detection code in
55698   ** btreeInitPage() is executed.  */
55699   pPage->isInit = 0;
55700   if( (rc = btreeInitPage(pPage))!=0 ){
55701     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
55702     checkAppendMsg(pCheck, zContext, 
55703                    "btreeInitPage() returns error code %d", rc);
55704     releasePage(pPage);
55705     return 0;
55706   }
55707
55708   /* Check out all the cells.
55709   */
55710   depth = 0;
55711   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
55712     u8 *pCell;
55713     u32 sz;
55714     CellInfo info;
55715
55716     /* Check payload overflow pages
55717     */
55718     sqlite3_snprintf(sizeof(zContext), zContext,
55719              "On tree page %d cell %d: ", iPage, i);
55720     pCell = findCell(pPage,i);
55721     btreeParseCellPtr(pPage, pCell, &info);
55722     sz = info.nData;
55723     if( !pPage->intKey ) sz += (int)info.nKey;
55724     /* For intKey pages, check that the keys are in order.
55725     */
55726     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
55727     else{
55728       if( info.nKey <= nMaxKey ){
55729         checkAppendMsg(pCheck, zContext, 
55730             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
55731       }
55732       nMaxKey = info.nKey;
55733     }
55734     assert( sz==info.nPayload );
55735     if( (sz>info.nLocal) 
55736      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
55737     ){
55738       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
55739       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
55740 #ifndef SQLITE_OMIT_AUTOVACUUM
55741       if( pBt->autoVacuum ){
55742         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
55743       }
55744 #endif
55745       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
55746     }
55747
55748     /* Check sanity of left child page.
55749     */
55750     if( !pPage->leaf ){
55751       pgno = get4byte(pCell);
55752 #ifndef SQLITE_OMIT_AUTOVACUUM
55753       if( pBt->autoVacuum ){
55754         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55755       }
55756 #endif
55757       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
55758       if( i>0 && d2!=depth ){
55759         checkAppendMsg(pCheck, zContext, "Child page depth differs");
55760       }
55761       depth = d2;
55762     }
55763   }
55764
55765   if( !pPage->leaf ){
55766     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55767     sqlite3_snprintf(sizeof(zContext), zContext, 
55768                      "On page %d at right child: ", iPage);
55769 #ifndef SQLITE_OMIT_AUTOVACUUM
55770     if( pBt->autoVacuum ){
55771       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55772     }
55773 #endif
55774     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
55775   }
55776  
55777   /* For intKey leaf pages, check that the min/max keys are in order
55778   ** with any left/parent/right pages.
55779   */
55780   if( pPage->leaf && pPage->intKey ){
55781     /* if we are a left child page */
55782     if( pnParentMinKey ){
55783       /* if we are the left most child page */
55784       if( !pnParentMaxKey ){
55785         if( nMaxKey > *pnParentMinKey ){
55786           checkAppendMsg(pCheck, zContext, 
55787               "Rowid %lld out of order (max larger than parent min of %lld)",
55788               nMaxKey, *pnParentMinKey);
55789         }
55790       }else{
55791         if( nMinKey <= *pnParentMinKey ){
55792           checkAppendMsg(pCheck, zContext, 
55793               "Rowid %lld out of order (min less than parent min of %lld)",
55794               nMinKey, *pnParentMinKey);
55795         }
55796         if( nMaxKey > *pnParentMaxKey ){
55797           checkAppendMsg(pCheck, zContext, 
55798               "Rowid %lld out of order (max larger than parent max of %lld)",
55799               nMaxKey, *pnParentMaxKey);
55800         }
55801         *pnParentMinKey = nMaxKey;
55802       }
55803     /* else if we're a right child page */
55804     } else if( pnParentMaxKey ){
55805       if( nMinKey <= *pnParentMaxKey ){
55806         checkAppendMsg(pCheck, zContext, 
55807             "Rowid %lld out of order (min less than parent max of %lld)",
55808             nMinKey, *pnParentMaxKey);
55809       }
55810     }
55811   }
55812
55813   /* Check for complete coverage of the page
55814   */
55815   data = pPage->aData;
55816   hdr = pPage->hdrOffset;
55817   hit = sqlite3PageMalloc( pBt->pageSize );
55818   if( hit==0 ){
55819     pCheck->mallocFailed = 1;
55820   }else{
55821     int contentOffset = get2byteNotZero(&data[hdr+5]);
55822     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
55823     memset(hit+contentOffset, 0, usableSize-contentOffset);
55824     memset(hit, 1, contentOffset);
55825     nCell = get2byte(&data[hdr+3]);
55826     cellStart = hdr + 12 - 4*pPage->leaf;
55827     for(i=0; i<nCell; i++){
55828       int pc = get2byte(&data[cellStart+i*2]);
55829       u32 size = 65536;
55830       int j;
55831       if( pc<=usableSize-4 ){
55832         size = cellSizePtr(pPage, &data[pc]);
55833       }
55834       if( (int)(pc+size-1)>=usableSize ){
55835         checkAppendMsg(pCheck, 0, 
55836             "Corruption detected in cell %d on page %d",i,iPage);
55837       }else{
55838         for(j=pc+size-1; j>=pc; j--) hit[j]++;
55839       }
55840     }
55841     i = get2byte(&data[hdr+1]);
55842     while( i>0 ){
55843       int size, j;
55844       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
55845       size = get2byte(&data[i+2]);
55846       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
55847       for(j=i+size-1; j>=i; j--) hit[j]++;
55848       j = get2byte(&data[i]);
55849       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
55850       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
55851       i = j;
55852     }
55853     for(i=cnt=0; i<usableSize; i++){
55854       if( hit[i]==0 ){
55855         cnt++;
55856       }else if( hit[i]>1 ){
55857         checkAppendMsg(pCheck, 0,
55858           "Multiple uses for byte %d of page %d", i, iPage);
55859         break;
55860       }
55861     }
55862     if( cnt!=data[hdr+7] ){
55863       checkAppendMsg(pCheck, 0, 
55864           "Fragmentation of %d bytes reported as %d on page %d",
55865           cnt, data[hdr+7], iPage);
55866     }
55867   }
55868   sqlite3PageFree(hit);
55869   releasePage(pPage);
55870   return depth+1;
55871 }
55872 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55873
55874 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55875 /*
55876 ** This routine does a complete check of the given BTree file.  aRoot[] is
55877 ** an array of pages numbers were each page number is the root page of
55878 ** a table.  nRoot is the number of entries in aRoot.
55879 **
55880 ** A read-only or read-write transaction must be opened before calling
55881 ** this function.
55882 **
55883 ** Write the number of error seen in *pnErr.  Except for some memory
55884 ** allocation errors,  an error message held in memory obtained from
55885 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
55886 ** returned.  If a memory allocation error occurs, NULL is returned.
55887 */
55888 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
55889   Btree *p,     /* The btree to be checked */
55890   int *aRoot,   /* An array of root pages numbers for individual trees */
55891   int nRoot,    /* Number of entries in aRoot[] */
55892   int mxErr,    /* Stop reporting errors after this many */
55893   int *pnErr    /* Write number of errors seen to this variable */
55894 ){
55895   Pgno i;
55896   int nRef;
55897   IntegrityCk sCheck;
55898   BtShared *pBt = p->pBt;
55899   char zErr[100];
55900
55901   sqlite3BtreeEnter(p);
55902   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
55903   nRef = sqlite3PagerRefcount(pBt->pPager);
55904   sCheck.pBt = pBt;
55905   sCheck.pPager = pBt->pPager;
55906   sCheck.nPage = btreePagecount(sCheck.pBt);
55907   sCheck.mxErr = mxErr;
55908   sCheck.nErr = 0;
55909   sCheck.mallocFailed = 0;
55910   *pnErr = 0;
55911   if( sCheck.nPage==0 ){
55912     sqlite3BtreeLeave(p);
55913     return 0;
55914   }
55915
55916   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
55917   if( !sCheck.aPgRef ){
55918     *pnErr = 1;
55919     sqlite3BtreeLeave(p);
55920     return 0;
55921   }
55922   i = PENDING_BYTE_PAGE(pBt);
55923   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
55924   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
55925   sCheck.errMsg.useMalloc = 2;
55926
55927   /* Check the integrity of the freelist
55928   */
55929   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
55930             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
55931
55932   /* Check all the tables.
55933   */
55934   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
55935     if( aRoot[i]==0 ) continue;
55936 #ifndef SQLITE_OMIT_AUTOVACUUM
55937     if( pBt->autoVacuum && aRoot[i]>1 ){
55938       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
55939     }
55940 #endif
55941     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
55942   }
55943
55944   /* Make sure every page in the file is referenced
55945   */
55946   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
55947 #ifdef SQLITE_OMIT_AUTOVACUUM
55948     if( getPageReferenced(&sCheck, i)==0 ){
55949       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55950     }
55951 #else
55952     /* If the database supports auto-vacuum, make sure no tables contain
55953     ** references to pointer-map pages.
55954     */
55955     if( getPageReferenced(&sCheck, i)==0 && 
55956        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
55957       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55958     }
55959     if( getPageReferenced(&sCheck, i)!=0 && 
55960        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
55961       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
55962     }
55963 #endif
55964   }
55965
55966   /* Make sure this analysis did not leave any unref() pages.
55967   ** This is an internal consistency check; an integrity check
55968   ** of the integrity check.
55969   */
55970   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
55971     checkAppendMsg(&sCheck, 0, 
55972       "Outstanding page count goes from %d to %d during this analysis",
55973       nRef, sqlite3PagerRefcount(pBt->pPager)
55974     );
55975   }
55976
55977   /* Clean  up and report errors.
55978   */
55979   sqlite3BtreeLeave(p);
55980   sqlite3_free(sCheck.aPgRef);
55981   if( sCheck.mallocFailed ){
55982     sqlite3StrAccumReset(&sCheck.errMsg);
55983     *pnErr = sCheck.nErr+1;
55984     return 0;
55985   }
55986   *pnErr = sCheck.nErr;
55987   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
55988   return sqlite3StrAccumFinish(&sCheck.errMsg);
55989 }
55990 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55991
55992 /*
55993 ** Return the full pathname of the underlying database file.  Return
55994 ** an empty string if the database is in-memory or a TEMP database.
55995 **
55996 ** The pager filename is invariant as long as the pager is
55997 ** open so it is safe to access without the BtShared mutex.
55998 */
55999 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56000   assert( p->pBt->pPager!=0 );
56001   return sqlite3PagerFilename(p->pBt->pPager, 1);
56002 }
56003
56004 /*
56005 ** Return the pathname of the journal file for this database. The return
56006 ** value of this routine is the same regardless of whether the journal file
56007 ** has been created or not.
56008 **
56009 ** The pager journal filename is invariant as long as the pager is
56010 ** open so it is safe to access without the BtShared mutex.
56011 */
56012 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56013   assert( p->pBt->pPager!=0 );
56014   return sqlite3PagerJournalname(p->pBt->pPager);
56015 }
56016
56017 /*
56018 ** Return non-zero if a transaction is active.
56019 */
56020 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56021   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56022   return (p && (p->inTrans==TRANS_WRITE));
56023 }
56024
56025 #ifndef SQLITE_OMIT_WAL
56026 /*
56027 ** Run a checkpoint on the Btree passed as the first argument.
56028 **
56029 ** Return SQLITE_LOCKED if this or any other connection has an open 
56030 ** transaction on the shared-cache the argument Btree is connected to.
56031 **
56032 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56033 */
56034 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56035   int rc = SQLITE_OK;
56036   if( p ){
56037     BtShared *pBt = p->pBt;
56038     sqlite3BtreeEnter(p);
56039     if( pBt->inTransaction!=TRANS_NONE ){
56040       rc = SQLITE_LOCKED;
56041     }else{
56042       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56043     }
56044     sqlite3BtreeLeave(p);
56045   }
56046   return rc;
56047 }
56048 #endif
56049
56050 /*
56051 ** Return non-zero if a read (or write) transaction is active.
56052 */
56053 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56054   assert( p );
56055   assert( sqlite3_mutex_held(p->db->mutex) );
56056   return p->inTrans!=TRANS_NONE;
56057 }
56058
56059 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56060   assert( p );
56061   assert( sqlite3_mutex_held(p->db->mutex) );
56062   return p->nBackup!=0;
56063 }
56064
56065 /*
56066 ** This function returns a pointer to a blob of memory associated with
56067 ** a single shared-btree. The memory is used by client code for its own
56068 ** purposes (for example, to store a high-level schema associated with 
56069 ** the shared-btree). The btree layer manages reference counting issues.
56070 **
56071 ** The first time this is called on a shared-btree, nBytes bytes of memory
56072 ** are allocated, zeroed, and returned to the caller. For each subsequent 
56073 ** call the nBytes parameter is ignored and a pointer to the same blob
56074 ** of memory returned. 
56075 **
56076 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56077 ** allocated, a null pointer is returned. If the blob has already been
56078 ** allocated, it is returned as normal.
56079 **
56080 ** Just before the shared-btree is closed, the function passed as the 
56081 ** xFree argument when the memory allocation was made is invoked on the 
56082 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56083 ** on the memory, the btree layer does that.
56084 */
56085 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56086   BtShared *pBt = p->pBt;
56087   sqlite3BtreeEnter(p);
56088   if( !pBt->pSchema && nBytes ){
56089     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56090     pBt->xFreeSchema = xFree;
56091   }
56092   sqlite3BtreeLeave(p);
56093   return pBt->pSchema;
56094 }
56095
56096 /*
56097 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
56098 ** btree as the argument handle holds an exclusive lock on the 
56099 ** sqlite_master table. Otherwise SQLITE_OK.
56100 */
56101 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56102   int rc;
56103   assert( sqlite3_mutex_held(p->db->mutex) );
56104   sqlite3BtreeEnter(p);
56105   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56106   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56107   sqlite3BtreeLeave(p);
56108   return rc;
56109 }
56110
56111
56112 #ifndef SQLITE_OMIT_SHARED_CACHE
56113 /*
56114 ** Obtain a lock on the table whose root page is iTab.  The
56115 ** lock is a write lock if isWritelock is true or a read lock
56116 ** if it is false.
56117 */
56118 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56119   int rc = SQLITE_OK;
56120   assert( p->inTrans!=TRANS_NONE );
56121   if( p->sharable ){
56122     u8 lockType = READ_LOCK + isWriteLock;
56123     assert( READ_LOCK+1==WRITE_LOCK );
56124     assert( isWriteLock==0 || isWriteLock==1 );
56125
56126     sqlite3BtreeEnter(p);
56127     rc = querySharedCacheTableLock(p, iTab, lockType);
56128     if( rc==SQLITE_OK ){
56129       rc = setSharedCacheTableLock(p, iTab, lockType);
56130     }
56131     sqlite3BtreeLeave(p);
56132   }
56133   return rc;
56134 }
56135 #endif
56136
56137 #ifndef SQLITE_OMIT_INCRBLOB
56138 /*
56139 ** Argument pCsr must be a cursor opened for writing on an 
56140 ** INTKEY table currently pointing at a valid table entry. 
56141 ** This function modifies the data stored as part of that entry.
56142 **
56143 ** Only the data content may only be modified, it is not possible to 
56144 ** change the length of the data stored. If this function is called with
56145 ** parameters that attempt to write past the end of the existing data,
56146 ** no modifications are made and SQLITE_CORRUPT is returned.
56147 */
56148 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56149   int rc;
56150   assert( cursorHoldsMutex(pCsr) );
56151   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56152   assert( pCsr->isIncrblobHandle );
56153
56154   rc = restoreCursorPosition(pCsr);
56155   if( rc!=SQLITE_OK ){
56156     return rc;
56157   }
56158   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56159   if( pCsr->eState!=CURSOR_VALID ){
56160     return SQLITE_ABORT;
56161   }
56162
56163   /* Check some assumptions: 
56164   **   (a) the cursor is open for writing,
56165   **   (b) there is a read/write transaction open,
56166   **   (c) the connection holds a write-lock on the table (if required),
56167   **   (d) there are no conflicting read-locks, and
56168   **   (e) the cursor points at a valid row of an intKey table.
56169   */
56170   if( !pCsr->wrFlag ){
56171     return SQLITE_READONLY;
56172   }
56173   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
56174               && pCsr->pBt->inTransaction==TRANS_WRITE );
56175   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56176   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56177   assert( pCsr->apPage[pCsr->iPage]->intKey );
56178
56179   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56180 }
56181
56182 /* 
56183 ** Set a flag on this cursor to cache the locations of pages from the 
56184 ** overflow list for the current row. This is used by cursors opened
56185 ** for incremental blob IO only.
56186 **
56187 ** This function sets a flag only. The actual page location cache
56188 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56189 ** accessPayload() (the worker function for sqlite3BtreeData() and
56190 ** sqlite3BtreePutData()).
56191 */
56192 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56193   assert( cursorHoldsMutex(pCur) );
56194   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56195   invalidateOverflowCache(pCur);
56196   pCur->isIncrblobHandle = 1;
56197 }
56198 #endif
56199
56200 /*
56201 ** Set both the "read version" (single byte at byte offset 18) and 
56202 ** "write version" (single byte at byte offset 19) fields in the database
56203 ** header to iVersion.
56204 */
56205 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56206   BtShared *pBt = pBtree->pBt;
56207   int rc;                         /* Return code */
56208  
56209   assert( iVersion==1 || iVersion==2 );
56210
56211   /* If setting the version fields to 1, do not automatically open the
56212   ** WAL connection, even if the version fields are currently set to 2.
56213   */
56214   pBt->btsFlags &= ~BTS_NO_WAL;
56215   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
56216
56217   rc = sqlite3BtreeBeginTrans(pBtree, 0);
56218   if( rc==SQLITE_OK ){
56219     u8 *aData = pBt->pPage1->aData;
56220     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56221       rc = sqlite3BtreeBeginTrans(pBtree, 2);
56222       if( rc==SQLITE_OK ){
56223         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56224         if( rc==SQLITE_OK ){
56225           aData[18] = (u8)iVersion;
56226           aData[19] = (u8)iVersion;
56227         }
56228       }
56229     }
56230   }
56231
56232   pBt->btsFlags &= ~BTS_NO_WAL;
56233   return rc;
56234 }
56235
56236 /*
56237 ** set the mask of hint flags for cursor pCsr. Currently the only valid
56238 ** values are 0 and BTREE_BULKLOAD.
56239 */
56240 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
56241   assert( mask==BTREE_BULKLOAD || mask==0 );
56242   pCsr->hints = mask;
56243 }
56244
56245 /************** End of btree.c ***********************************************/
56246 /************** Begin file backup.c ******************************************/
56247 /*
56248 ** 2009 January 28
56249 **
56250 ** The author disclaims copyright to this source code.  In place of
56251 ** a legal notice, here is a blessing:
56252 **
56253 **    May you do good and not evil.
56254 **    May you find forgiveness for yourself and forgive others.
56255 **    May you share freely, never taking more than you give.
56256 **
56257 *************************************************************************
56258 ** This file contains the implementation of the sqlite3_backup_XXX() 
56259 ** API functions and the related features.
56260 */
56261
56262 /* Macro to find the minimum of two numeric values.
56263 */
56264 #ifndef MIN
56265 # define MIN(x,y) ((x)<(y)?(x):(y))
56266 #endif
56267
56268 /*
56269 ** Structure allocated for each backup operation.
56270 */
56271 struct sqlite3_backup {
56272   sqlite3* pDestDb;        /* Destination database handle */
56273   Btree *pDest;            /* Destination b-tree file */
56274   u32 iDestSchema;         /* Original schema cookie in destination */
56275   int bDestLocked;         /* True once a write-transaction is open on pDest */
56276
56277   Pgno iNext;              /* Page number of the next source page to copy */
56278   sqlite3* pSrcDb;         /* Source database handle */
56279   Btree *pSrc;             /* Source b-tree file */
56280
56281   int rc;                  /* Backup process error code */
56282
56283   /* These two variables are set by every call to backup_step(). They are
56284   ** read by calls to backup_remaining() and backup_pagecount().
56285   */
56286   Pgno nRemaining;         /* Number of pages left to copy */
56287   Pgno nPagecount;         /* Total number of pages to copy */
56288
56289   int isAttached;          /* True once backup has been registered with pager */
56290   sqlite3_backup *pNext;   /* Next backup associated with source pager */
56291 };
56292
56293 /*
56294 ** THREAD SAFETY NOTES:
56295 **
56296 **   Once it has been created using backup_init(), a single sqlite3_backup
56297 **   structure may be accessed via two groups of thread-safe entry points:
56298 **
56299 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
56300 **       backup_finish(). Both these functions obtain the source database
56301 **       handle mutex and the mutex associated with the source BtShared 
56302 **       structure, in that order.
56303 **
56304 **     * Via the BackupUpdate() and BackupRestart() functions, which are
56305 **       invoked by the pager layer to report various state changes in
56306 **       the page cache associated with the source database. The mutex
56307 **       associated with the source database BtShared structure will always 
56308 **       be held when either of these functions are invoked.
56309 **
56310 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
56311 **   backup_pagecount() are not thread-safe functions. If they are called
56312 **   while some other thread is calling backup_step() or backup_finish(),
56313 **   the values returned may be invalid. There is no way for a call to
56314 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56315 **   or backup_pagecount().
56316 **
56317 **   Depending on the SQLite configuration, the database handles and/or
56318 **   the Btree objects may have their own mutexes that require locking.
56319 **   Non-sharable Btrees (in-memory databases for example), do not have
56320 **   associated mutexes.
56321 */
56322
56323 /*
56324 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56325 ** in connection handle pDb. If such a database cannot be found, return
56326 ** a NULL pointer and write an error message to pErrorDb.
56327 **
56328 ** If the "temp" database is requested, it may need to be opened by this 
56329 ** function. If an error occurs while doing so, return 0 and write an 
56330 ** error message to pErrorDb.
56331 */
56332 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56333   int i = sqlite3FindDbName(pDb, zDb);
56334
56335   if( i==1 ){
56336     Parse *pParse;
56337     int rc = 0;
56338     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56339     if( pParse==0 ){
56340       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56341       rc = SQLITE_NOMEM;
56342     }else{
56343       pParse->db = pDb;
56344       if( sqlite3OpenTempDatabase(pParse) ){
56345         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56346         rc = SQLITE_ERROR;
56347       }
56348       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56349       sqlite3StackFree(pErrorDb, pParse);
56350     }
56351     if( rc ){
56352       return 0;
56353     }
56354   }
56355
56356   if( i<0 ){
56357     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56358     return 0;
56359   }
56360
56361   return pDb->aDb[i].pBt;
56362 }
56363
56364 /*
56365 ** Attempt to set the page size of the destination to match the page size
56366 ** of the source.
56367 */
56368 static int setDestPgsz(sqlite3_backup *p){
56369   int rc;
56370   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56371   return rc;
56372 }
56373
56374 /*
56375 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56376 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56377 ** a pointer to the new sqlite3_backup object.
56378 **
56379 ** If an error occurs, NULL is returned and an error code and error message
56380 ** stored in database handle pDestDb.
56381 */
56382 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56383   sqlite3* pDestDb,                     /* Database to write to */
56384   const char *zDestDb,                  /* Name of database within pDestDb */
56385   sqlite3* pSrcDb,                      /* Database connection to read from */
56386   const char *zSrcDb                    /* Name of database within pSrcDb */
56387 ){
56388   sqlite3_backup *p;                    /* Value to return */
56389
56390   /* Lock the source database handle. The destination database
56391   ** handle is not locked in this routine, but it is locked in
56392   ** sqlite3_backup_step(). The user is required to ensure that no
56393   ** other thread accesses the destination handle for the duration
56394   ** of the backup operation.  Any attempt to use the destination
56395   ** database connection while a backup is in progress may cause
56396   ** a malfunction or a deadlock.
56397   */
56398   sqlite3_mutex_enter(pSrcDb->mutex);
56399   sqlite3_mutex_enter(pDestDb->mutex);
56400
56401   if( pSrcDb==pDestDb ){
56402     sqlite3Error(
56403         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56404     );
56405     p = 0;
56406   }else {
56407     /* Allocate space for a new sqlite3_backup object...
56408     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56409     ** call to sqlite3_backup_init() and is destroyed by a call to
56410     ** sqlite3_backup_finish(). */
56411     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
56412     if( !p ){
56413       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56414     }
56415   }
56416
56417   /* If the allocation succeeded, populate the new object. */
56418   if( p ){
56419     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56420     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
56421     p->pDestDb = pDestDb;
56422     p->pSrcDb = pSrcDb;
56423     p->iNext = 1;
56424     p->isAttached = 0;
56425
56426     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
56427       /* One (or both) of the named databases did not exist or an OOM
56428       ** error was hit.  The error has already been written into the
56429       ** pDestDb handle.  All that is left to do here is free the
56430       ** sqlite3_backup structure.
56431       */
56432       sqlite3_free(p);
56433       p = 0;
56434     }
56435   }
56436   if( p ){
56437     p->pSrc->nBackup++;
56438   }
56439
56440   sqlite3_mutex_leave(pDestDb->mutex);
56441   sqlite3_mutex_leave(pSrcDb->mutex);
56442   return p;
56443 }
56444
56445 /*
56446 ** Argument rc is an SQLite error code. Return true if this error is 
56447 ** considered fatal if encountered during a backup operation. All errors
56448 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
56449 */
56450 static int isFatalError(int rc){
56451   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
56452 }
56453
56454 /*
56455 ** Parameter zSrcData points to a buffer containing the data for 
56456 ** page iSrcPg from the source database. Copy this data into the 
56457 ** destination database.
56458 */
56459 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
56460   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
56461   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
56462   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
56463   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
56464   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
56465 #ifdef SQLITE_HAS_CODEC
56466   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
56467   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
56468 #endif
56469
56470   int rc = SQLITE_OK;
56471   i64 iOff;
56472
56473   assert( p->bDestLocked );
56474   assert( !isFatalError(p->rc) );
56475   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
56476   assert( zSrcData );
56477
56478   /* Catch the case where the destination is an in-memory database and the
56479   ** page sizes of the source and destination differ. 
56480   */
56481   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
56482     rc = SQLITE_READONLY;
56483   }
56484
56485 #ifdef SQLITE_HAS_CODEC
56486   /* Backup is not possible if the page size of the destination is changing
56487   ** and a codec is in use.
56488   */
56489   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
56490     rc = SQLITE_READONLY;
56491   }
56492
56493   /* Backup is not possible if the number of bytes of reserve space differ
56494   ** between source and destination.  If there is a difference, try to
56495   ** fix the destination to agree with the source.  If that is not possible,
56496   ** then the backup cannot proceed.
56497   */
56498   if( nSrcReserve!=nDestReserve ){
56499     u32 newPgsz = nSrcPgsz;
56500     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
56501     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
56502   }
56503 #endif
56504
56505   /* This loop runs once for each destination page spanned by the source 
56506   ** page. For each iteration, variable iOff is set to the byte offset
56507   ** of the destination page.
56508   */
56509   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
56510     DbPage *pDestPg = 0;
56511     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
56512     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
56513     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
56514      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
56515     ){
56516       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
56517       u8 *zDestData = sqlite3PagerGetData(pDestPg);
56518       u8 *zOut = &zDestData[iOff%nDestPgsz];
56519
56520       /* Copy the data from the source page into the destination page.
56521       ** Then clear the Btree layer MemPage.isInit flag. Both this module
56522       ** and the pager code use this trick (clearing the first byte
56523       ** of the page 'extra' space to invalidate the Btree layers
56524       ** cached parse of the page). MemPage.isInit is marked 
56525       ** "MUST BE FIRST" for this purpose.
56526       */
56527       memcpy(zOut, zIn, nCopy);
56528       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
56529     }
56530     sqlite3PagerUnref(pDestPg);
56531   }
56532
56533   return rc;
56534 }
56535
56536 /*
56537 ** If pFile is currently larger than iSize bytes, then truncate it to
56538 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
56539 ** this function is a no-op.
56540 **
56541 ** Return SQLITE_OK if everything is successful, or an SQLite error 
56542 ** code if an error occurs.
56543 */
56544 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
56545   i64 iCurrent;
56546   int rc = sqlite3OsFileSize(pFile, &iCurrent);
56547   if( rc==SQLITE_OK && iCurrent>iSize ){
56548     rc = sqlite3OsTruncate(pFile, iSize);
56549   }
56550   return rc;
56551 }
56552
56553 /*
56554 ** Register this backup object with the associated source pager for
56555 ** callbacks when pages are changed or the cache invalidated.
56556 */
56557 static void attachBackupObject(sqlite3_backup *p){
56558   sqlite3_backup **pp;
56559   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
56560   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56561   p->pNext = *pp;
56562   *pp = p;
56563   p->isAttached = 1;
56564 }
56565
56566 /*
56567 ** Copy nPage pages from the source b-tree to the destination.
56568 */
56569 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
56570   int rc;
56571   int destMode;       /* Destination journal mode */
56572   int pgszSrc = 0;    /* Source page size */
56573   int pgszDest = 0;   /* Destination page size */
56574
56575   sqlite3_mutex_enter(p->pSrcDb->mutex);
56576   sqlite3BtreeEnter(p->pSrc);
56577   if( p->pDestDb ){
56578     sqlite3_mutex_enter(p->pDestDb->mutex);
56579   }
56580
56581   rc = p->rc;
56582   if( !isFatalError(rc) ){
56583     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
56584     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
56585     int ii;                            /* Iterator variable */
56586     int nSrcPage = -1;                 /* Size of source db in pages */
56587     int bCloseTrans = 0;               /* True if src db requires unlocking */
56588
56589     /* If the source pager is currently in a write-transaction, return
56590     ** SQLITE_BUSY immediately.
56591     */
56592     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
56593       rc = SQLITE_BUSY;
56594     }else{
56595       rc = SQLITE_OK;
56596     }
56597
56598     /* Lock the destination database, if it is not locked already. */
56599     if( SQLITE_OK==rc && p->bDestLocked==0
56600      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
56601     ){
56602       p->bDestLocked = 1;
56603       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
56604     }
56605
56606     /* If there is no open read-transaction on the source database, open
56607     ** one now. If a transaction is opened here, then it will be closed
56608     ** before this function exits.
56609     */
56610     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
56611       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
56612       bCloseTrans = 1;
56613     }
56614
56615     /* Do not allow backup if the destination database is in WAL mode
56616     ** and the page sizes are different between source and destination */
56617     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
56618     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
56619     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
56620     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
56621       rc = SQLITE_READONLY;
56622     }
56623   
56624     /* Now that there is a read-lock on the source database, query the
56625     ** source pager for the number of pages in the database.
56626     */
56627     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
56628     assert( nSrcPage>=0 );
56629     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
56630       const Pgno iSrcPg = p->iNext;                 /* Source page number */
56631       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
56632         DbPage *pSrcPg;                             /* Source page object */
56633         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56634         if( rc==SQLITE_OK ){
56635           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
56636           sqlite3PagerUnref(pSrcPg);
56637         }
56638       }
56639       p->iNext++;
56640     }
56641     if( rc==SQLITE_OK ){
56642       p->nPagecount = nSrcPage;
56643       p->nRemaining = nSrcPage+1-p->iNext;
56644       if( p->iNext>(Pgno)nSrcPage ){
56645         rc = SQLITE_DONE;
56646       }else if( !p->isAttached ){
56647         attachBackupObject(p);
56648       }
56649     }
56650   
56651     /* Update the schema version field in the destination database. This
56652     ** is to make sure that the schema-version really does change in
56653     ** the case where the source and destination databases have the
56654     ** same schema version.
56655     */
56656     if( rc==SQLITE_DONE ){
56657       rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
56658       if( rc==SQLITE_OK ){
56659         if( p->pDestDb ){
56660           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
56661         }
56662         if( destMode==PAGER_JOURNALMODE_WAL ){
56663           rc = sqlite3BtreeSetVersion(p->pDest, 2);
56664         }
56665       }
56666       if( rc==SQLITE_OK ){
56667         int nDestTruncate;
56668         /* Set nDestTruncate to the final number of pages in the destination
56669         ** database. The complication here is that the destination page
56670         ** size may be different to the source page size. 
56671         **
56672         ** If the source page size is smaller than the destination page size, 
56673         ** round up. In this case the call to sqlite3OsTruncate() below will
56674         ** fix the size of the file. However it is important to call
56675         ** sqlite3PagerTruncateImage() here so that any pages in the 
56676         ** destination file that lie beyond the nDestTruncate page mark are
56677         ** journalled by PagerCommitPhaseOne() before they are destroyed
56678         ** by the file truncation.
56679         */
56680         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
56681         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
56682         if( pgszSrc<pgszDest ){
56683           int ratio = pgszDest/pgszSrc;
56684           nDestTruncate = (nSrcPage+ratio-1)/ratio;
56685           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
56686             nDestTruncate--;
56687           }
56688         }else{
56689           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
56690         }
56691         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
56692
56693         if( pgszSrc<pgszDest ){
56694           /* If the source page-size is smaller than the destination page-size,
56695           ** two extra things may need to happen:
56696           **
56697           **   * The destination may need to be truncated, and
56698           **
56699           **   * Data stored on the pages immediately following the 
56700           **     pending-byte page in the source database may need to be
56701           **     copied into the destination database.
56702           */
56703           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
56704           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
56705           i64 iOff;
56706           i64 iEnd;
56707
56708           assert( pFile );
56709           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
56710                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
56711              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
56712           ));
56713
56714           /* This call ensures that all data required to recreate the original
56715           ** database has been stored in the journal for pDestPager and the
56716           ** journal synced to disk. So at this point we may safely modify
56717           ** the database file in any way, knowing that if a power failure
56718           ** occurs, the original database will be reconstructed from the 
56719           ** journal file.  */
56720           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
56721
56722           /* Write the extra pages and truncate the database file as required */
56723           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
56724           for(
56725             iOff=PENDING_BYTE+pgszSrc; 
56726             rc==SQLITE_OK && iOff<iEnd; 
56727             iOff+=pgszSrc
56728           ){
56729             PgHdr *pSrcPg = 0;
56730             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
56731             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56732             if( rc==SQLITE_OK ){
56733               u8 *zData = sqlite3PagerGetData(pSrcPg);
56734               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
56735             }
56736             sqlite3PagerUnref(pSrcPg);
56737           }
56738           if( rc==SQLITE_OK ){
56739             rc = backupTruncateFile(pFile, iSize);
56740           }
56741
56742           /* Sync the database file to disk. */
56743           if( rc==SQLITE_OK ){
56744             rc = sqlite3PagerSync(pDestPager);
56745           }
56746         }else{
56747           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
56748         }
56749     
56750         /* Finish committing the transaction to the destination database. */
56751         if( SQLITE_OK==rc
56752          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
56753         ){
56754           rc = SQLITE_DONE;
56755         }
56756       }
56757     }
56758   
56759     /* If bCloseTrans is true, then this function opened a read transaction
56760     ** on the source database. Close the read transaction here. There is
56761     ** no need to check the return values of the btree methods here, as
56762     ** "committing" a read-only transaction cannot fail.
56763     */
56764     if( bCloseTrans ){
56765       TESTONLY( int rc2 );
56766       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
56767       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
56768       assert( rc2==SQLITE_OK );
56769     }
56770   
56771     if( rc==SQLITE_IOERR_NOMEM ){
56772       rc = SQLITE_NOMEM;
56773     }
56774     p->rc = rc;
56775   }
56776   if( p->pDestDb ){
56777     sqlite3_mutex_leave(p->pDestDb->mutex);
56778   }
56779   sqlite3BtreeLeave(p->pSrc);
56780   sqlite3_mutex_leave(p->pSrcDb->mutex);
56781   return rc;
56782 }
56783
56784 /*
56785 ** Release all resources associated with an sqlite3_backup* handle.
56786 */
56787 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
56788   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
56789   sqlite3 *pSrcDb;                     /* Source database connection */
56790   int rc;                              /* Value to return */
56791
56792   /* Enter the mutexes */
56793   if( p==0 ) return SQLITE_OK;
56794   pSrcDb = p->pSrcDb;
56795   sqlite3_mutex_enter(pSrcDb->mutex);
56796   sqlite3BtreeEnter(p->pSrc);
56797   if( p->pDestDb ){
56798     sqlite3_mutex_enter(p->pDestDb->mutex);
56799   }
56800
56801   /* Detach this backup from the source pager. */
56802   if( p->pDestDb ){
56803     p->pSrc->nBackup--;
56804   }
56805   if( p->isAttached ){
56806     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56807     while( *pp!=p ){
56808       pp = &(*pp)->pNext;
56809     }
56810     *pp = p->pNext;
56811   }
56812
56813   /* If a transaction is still open on the Btree, roll it back. */
56814   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
56815
56816   /* Set the error code of the destination database handle. */
56817   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
56818   sqlite3Error(p->pDestDb, rc, 0);
56819
56820   /* Exit the mutexes and free the backup context structure. */
56821   if( p->pDestDb ){
56822     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
56823   }
56824   sqlite3BtreeLeave(p->pSrc);
56825   if( p->pDestDb ){
56826     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56827     ** call to sqlite3_backup_init() and is destroyed by a call to
56828     ** sqlite3_backup_finish(). */
56829     sqlite3_free(p);
56830   }
56831   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
56832   return rc;
56833 }
56834
56835 /*
56836 ** Return the number of pages still to be backed up as of the most recent
56837 ** call to sqlite3_backup_step().
56838 */
56839 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
56840   return p->nRemaining;
56841 }
56842
56843 /*
56844 ** Return the total number of pages in the source database as of the most 
56845 ** recent call to sqlite3_backup_step().
56846 */
56847 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
56848   return p->nPagecount;
56849 }
56850
56851 /*
56852 ** This function is called after the contents of page iPage of the
56853 ** source database have been modified. If page iPage has already been 
56854 ** copied into the destination database, then the data written to the
56855 ** destination is now invalidated. The destination copy of iPage needs
56856 ** to be updated with the new data before the backup operation is
56857 ** complete.
56858 **
56859 ** It is assumed that the mutex associated with the BtShared object
56860 ** corresponding to the source database is held when this function is
56861 ** called.
56862 */
56863 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
56864   sqlite3_backup *p;                   /* Iterator variable */
56865   for(p=pBackup; p; p=p->pNext){
56866     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56867     if( !isFatalError(p->rc) && iPage<p->iNext ){
56868       /* The backup process p has already copied page iPage. But now it
56869       ** has been modified by a transaction on the source pager. Copy
56870       ** the new data into the backup.
56871       */
56872       int rc;
56873       assert( p->pDestDb );
56874       sqlite3_mutex_enter(p->pDestDb->mutex);
56875       rc = backupOnePage(p, iPage, aData);
56876       sqlite3_mutex_leave(p->pDestDb->mutex);
56877       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
56878       if( rc!=SQLITE_OK ){
56879         p->rc = rc;
56880       }
56881     }
56882   }
56883 }
56884
56885 /*
56886 ** Restart the backup process. This is called when the pager layer
56887 ** detects that the database has been modified by an external database
56888 ** connection. In this case there is no way of knowing which of the
56889 ** pages that have been copied into the destination database are still 
56890 ** valid and which are not, so the entire process needs to be restarted.
56891 **
56892 ** It is assumed that the mutex associated with the BtShared object
56893 ** corresponding to the source database is held when this function is
56894 ** called.
56895 */
56896 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
56897   sqlite3_backup *p;                   /* Iterator variable */
56898   for(p=pBackup; p; p=p->pNext){
56899     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56900     p->iNext = 1;
56901   }
56902 }
56903
56904 #ifndef SQLITE_OMIT_VACUUM
56905 /*
56906 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
56907 ** must be active for both files.
56908 **
56909 ** The size of file pTo may be reduced by this operation. If anything 
56910 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
56911 ** transaction is committed before returning.
56912 */
56913 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
56914   int rc;
56915   sqlite3_file *pFd;              /* File descriptor for database pTo */
56916   sqlite3_backup b;
56917   sqlite3BtreeEnter(pTo);
56918   sqlite3BtreeEnter(pFrom);
56919
56920   assert( sqlite3BtreeIsInTrans(pTo) );
56921   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
56922   if( pFd->pMethods ){
56923     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
56924     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
56925     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
56926     if( rc ) goto copy_finished;
56927   }
56928
56929   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
56930   ** to 0. This is used by the implementations of sqlite3_backup_step()
56931   ** and sqlite3_backup_finish() to detect that they are being called
56932   ** from this function, not directly by the user.
56933   */
56934   memset(&b, 0, sizeof(b));
56935   b.pSrcDb = pFrom->db;
56936   b.pSrc = pFrom;
56937   b.pDest = pTo;
56938   b.iNext = 1;
56939
56940   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
56941   ** file. By passing this as the number of pages to copy to
56942   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
56943   ** within a single call (unless an error occurs). The assert() statement
56944   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
56945   ** or an error code.
56946   */
56947   sqlite3_backup_step(&b, 0x7FFFFFFF);
56948   assert( b.rc!=SQLITE_OK );
56949   rc = sqlite3_backup_finish(&b);
56950   if( rc==SQLITE_OK ){
56951     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
56952   }else{
56953     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
56954   }
56955
56956   assert( sqlite3BtreeIsInTrans(pTo)==0 );
56957 copy_finished:
56958   sqlite3BtreeLeave(pFrom);
56959   sqlite3BtreeLeave(pTo);
56960   return rc;
56961 }
56962 #endif /* SQLITE_OMIT_VACUUM */
56963
56964 /************** End of backup.c **********************************************/
56965 /************** Begin file vdbemem.c *****************************************/
56966 /*
56967 ** 2004 May 26
56968 **
56969 ** The author disclaims copyright to this source code.  In place of
56970 ** a legal notice, here is a blessing:
56971 **
56972 **    May you do good and not evil.
56973 **    May you find forgiveness for yourself and forgive others.
56974 **    May you share freely, never taking more than you give.
56975 **
56976 *************************************************************************
56977 **
56978 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
56979 ** stores a single value in the VDBE.  Mem is an opaque structure visible
56980 ** only within the VDBE.  Interface routines refer to a Mem using the
56981 ** name sqlite_value
56982 */
56983
56984 /*
56985 ** If pMem is an object with a valid string representation, this routine
56986 ** ensures the internal encoding for the string representation is
56987 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
56988 **
56989 ** If pMem is not a string object, or the encoding of the string
56990 ** representation is already stored using the requested encoding, then this
56991 ** routine is a no-op.
56992 **
56993 ** SQLITE_OK is returned if the conversion is successful (or not required).
56994 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
56995 ** between formats.
56996 */
56997 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
56998   int rc;
56999   assert( (pMem->flags&MEM_RowSet)==0 );
57000   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57001            || desiredEnc==SQLITE_UTF16BE );
57002   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57003     return SQLITE_OK;
57004   }
57005   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57006 #ifdef SQLITE_OMIT_UTF16
57007   return SQLITE_ERROR;
57008 #else
57009
57010   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57011   ** then the encoding of the value may not have changed.
57012   */
57013   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57014   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
57015   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57016   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57017   return rc;
57018 #endif
57019 }
57020
57021 /*
57022 ** Make sure pMem->z points to a writable allocation of at least 
57023 ** n bytes.
57024 **
57025 ** If the third argument passed to this function is true, then memory
57026 ** cell pMem must contain a string or blob. In this case the content is
57027 ** preserved. Otherwise, if the third parameter to this function is false,
57028 ** any current string or blob value may be discarded.
57029 **
57030 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57031 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
57032 ** not set, Mem.n is zeroed.
57033 */
57034 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57035   assert( 1 >=
57036     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57037     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
57038     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
57039     ((pMem->flags&MEM_Static) ? 1 : 0)
57040   );
57041   assert( (pMem->flags&MEM_RowSet)==0 );
57042
57043   /* If the preserve flag is set to true, then the memory cell must already
57044   ** contain a valid string or blob value.  */
57045   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
57046
57047   if( n<32 ) n = 32;
57048   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57049     if( preserve && pMem->z==pMem->zMalloc ){
57050       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57051       preserve = 0;
57052     }else{
57053       sqlite3DbFree(pMem->db, pMem->zMalloc);
57054       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57055     }
57056   }
57057
57058   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57059     memcpy(pMem->zMalloc, pMem->z, pMem->n);
57060   }
57061   if( pMem->flags&MEM_Dyn && pMem->xDel ){
57062     assert( pMem->xDel!=SQLITE_DYNAMIC );
57063     pMem->xDel((void *)(pMem->z));
57064   }
57065
57066   pMem->z = pMem->zMalloc;
57067   if( pMem->z==0 ){
57068     pMem->flags = MEM_Null;
57069   }else{
57070     pMem->flags &= ~(MEM_Ephem|MEM_Static);
57071   }
57072   pMem->xDel = 0;
57073   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57074 }
57075
57076 /*
57077 ** Make the given Mem object MEM_Dyn.  In other words, make it so
57078 ** that any TEXT or BLOB content is stored in memory obtained from
57079 ** malloc().  In this way, we know that the memory is safe to be
57080 ** overwritten or altered.
57081 **
57082 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57083 */
57084 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57085   int f;
57086   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57087   assert( (pMem->flags&MEM_RowSet)==0 );
57088   ExpandBlob(pMem);
57089   f = pMem->flags;
57090   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57091     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57092       return SQLITE_NOMEM;
57093     }
57094     pMem->z[pMem->n] = 0;
57095     pMem->z[pMem->n+1] = 0;
57096     pMem->flags |= MEM_Term;
57097 #ifdef SQLITE_DEBUG
57098     pMem->pScopyFrom = 0;
57099 #endif
57100   }
57101
57102   return SQLITE_OK;
57103 }
57104
57105 /*
57106 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57107 ** blob stored in dynamically allocated space.
57108 */
57109 #ifndef SQLITE_OMIT_INCRBLOB
57110 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57111   if( pMem->flags & MEM_Zero ){
57112     int nByte;
57113     assert( pMem->flags&MEM_Blob );
57114     assert( (pMem->flags&MEM_RowSet)==0 );
57115     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57116
57117     /* Set nByte to the number of bytes required to store the expanded blob. */
57118     nByte = pMem->n + pMem->u.nZero;
57119     if( nByte<=0 ){
57120       nByte = 1;
57121     }
57122     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57123       return SQLITE_NOMEM;
57124     }
57125
57126     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57127     pMem->n += pMem->u.nZero;
57128     pMem->flags &= ~(MEM_Zero|MEM_Term);
57129   }
57130   return SQLITE_OK;
57131 }
57132 #endif
57133
57134
57135 /*
57136 ** Make sure the given Mem is \u0000 terminated.
57137 */
57138 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57139   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57140   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57141     return SQLITE_OK;   /* Nothing to do */
57142   }
57143   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57144     return SQLITE_NOMEM;
57145   }
57146   pMem->z[pMem->n] = 0;
57147   pMem->z[pMem->n+1] = 0;
57148   pMem->flags |= MEM_Term;
57149   return SQLITE_OK;
57150 }
57151
57152 /*
57153 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
57154 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
57155 ** is a no-op.
57156 **
57157 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57158 **
57159 ** A MEM_Null value will never be passed to this function. This function is
57160 ** used for converting values to text for returning to the user (i.e. via
57161 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57162 ** keys are strings. In the former case a NULL pointer is returned the
57163 ** user and the later is an internal programming error.
57164 */
57165 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57166   int rc = SQLITE_OK;
57167   int fg = pMem->flags;
57168   const int nByte = 32;
57169
57170   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57171   assert( !(fg&MEM_Zero) );
57172   assert( !(fg&(MEM_Str|MEM_Blob)) );
57173   assert( fg&(MEM_Int|MEM_Real) );
57174   assert( (pMem->flags&MEM_RowSet)==0 );
57175   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57176
57177
57178   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57179     return SQLITE_NOMEM;
57180   }
57181
57182   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57183   ** string representation of the value. Then, if the required encoding
57184   ** is UTF-16le or UTF-16be do a translation.
57185   ** 
57186   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57187   */
57188   if( fg & MEM_Int ){
57189     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57190   }else{
57191     assert( fg & MEM_Real );
57192     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57193   }
57194   pMem->n = sqlite3Strlen30(pMem->z);
57195   pMem->enc = SQLITE_UTF8;
57196   pMem->flags |= MEM_Str|MEM_Term;
57197   sqlite3VdbeChangeEncoding(pMem, enc);
57198   return rc;
57199 }
57200
57201 /*
57202 ** Memory cell pMem contains the context of an aggregate function.
57203 ** This routine calls the finalize method for that function.  The
57204 ** result of the aggregate is stored back into pMem.
57205 **
57206 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
57207 ** otherwise.
57208 */
57209 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57210   int rc = SQLITE_OK;
57211   if( ALWAYS(pFunc && pFunc->xFinalize) ){
57212     sqlite3_context ctx;
57213     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57214     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57215     memset(&ctx, 0, sizeof(ctx));
57216     ctx.s.flags = MEM_Null;
57217     ctx.s.db = pMem->db;
57218     ctx.pMem = pMem;
57219     ctx.pFunc = pFunc;
57220     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57221     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57222     sqlite3DbFree(pMem->db, pMem->zMalloc);
57223     memcpy(pMem, &ctx.s, sizeof(ctx.s));
57224     rc = ctx.isError;
57225   }
57226   return rc;
57227 }
57228
57229 /*
57230 ** If the memory cell contains a string value that must be freed by
57231 ** invoking an external callback, free it now. Calling this function
57232 ** does not free any Mem.zMalloc buffer.
57233 */
57234 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57235   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57236   if( p->flags&MEM_Agg ){
57237     sqlite3VdbeMemFinalize(p, p->u.pDef);
57238     assert( (p->flags & MEM_Agg)==0 );
57239     sqlite3VdbeMemRelease(p);
57240   }else if( p->flags&MEM_Dyn && p->xDel ){
57241     assert( (p->flags&MEM_RowSet)==0 );
57242     assert( p->xDel!=SQLITE_DYNAMIC );
57243     p->xDel((void *)p->z);
57244     p->xDel = 0;
57245   }else if( p->flags&MEM_RowSet ){
57246     sqlite3RowSetClear(p->u.pRowSet);
57247   }else if( p->flags&MEM_Frame ){
57248     sqlite3VdbeMemSetNull(p);
57249   }
57250 }
57251
57252 /*
57253 ** Release any memory held by the Mem. This may leave the Mem in an
57254 ** inconsistent state, for example with (Mem.z==0) and
57255 ** (Mem.type==SQLITE_TEXT).
57256 */
57257 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57258   VdbeMemRelease(p);
57259   sqlite3DbFree(p->db, p->zMalloc);
57260   p->z = 0;
57261   p->zMalloc = 0;
57262   p->xDel = 0;
57263 }
57264
57265 /*
57266 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57267 ** If the double is too large, return 0x8000000000000000.
57268 **
57269 ** Most systems appear to do this simply by assigning
57270 ** variables and without the extra range tests.  But
57271 ** there are reports that windows throws an expection
57272 ** if the floating point value is out of range. (See ticket #2880.)
57273 ** Because we do not completely understand the problem, we will
57274 ** take the conservative approach and always do range tests
57275 ** before attempting the conversion.
57276 */
57277 static i64 doubleToInt64(double r){
57278 #ifdef SQLITE_OMIT_FLOATING_POINT
57279   /* When floating-point is omitted, double and int64 are the same thing */
57280   return r;
57281 #else
57282   /*
57283   ** Many compilers we encounter do not define constants for the
57284   ** minimum and maximum 64-bit integers, or they define them
57285   ** inconsistently.  And many do not understand the "LL" notation.
57286   ** So we define our own static constants here using nothing
57287   ** larger than a 32-bit integer constant.
57288   */
57289   static const i64 maxInt = LARGEST_INT64;
57290   static const i64 minInt = SMALLEST_INT64;
57291
57292   if( r<(double)minInt ){
57293     return minInt;
57294   }else if( r>(double)maxInt ){
57295     /* minInt is correct here - not maxInt.  It turns out that assigning
57296     ** a very large positive number to an integer results in a very large
57297     ** negative integer.  This makes no sense, but it is what x86 hardware
57298     ** does so for compatibility we will do the same in software. */
57299     return minInt;
57300   }else{
57301     return (i64)r;
57302   }
57303 #endif
57304 }
57305
57306 /*
57307 ** Return some kind of integer value which is the best we can do
57308 ** at representing the value that *pMem describes as an integer.
57309 ** If pMem is an integer, then the value is exact.  If pMem is
57310 ** a floating-point then the value returned is the integer part.
57311 ** If pMem is a string or blob, then we make an attempt to convert
57312 ** it into a integer and return that.  If pMem represents an
57313 ** an SQL-NULL value, return 0.
57314 **
57315 ** If pMem represents a string value, its encoding might be changed.
57316 */
57317 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57318   int flags;
57319   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57320   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57321   flags = pMem->flags;
57322   if( flags & MEM_Int ){
57323     return pMem->u.i;
57324   }else if( flags & MEM_Real ){
57325     return doubleToInt64(pMem->r);
57326   }else if( flags & (MEM_Str|MEM_Blob) ){
57327     i64 value = 0;
57328     assert( pMem->z || pMem->n==0 );
57329     testcase( pMem->z==0 );
57330     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57331     return value;
57332   }else{
57333     return 0;
57334   }
57335 }
57336
57337 /*
57338 ** Return the best representation of pMem that we can get into a
57339 ** double.  If pMem is already a double or an integer, return its
57340 ** value.  If it is a string or blob, try to convert it to a double.
57341 ** If it is a NULL, return 0.0.
57342 */
57343 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57344   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57345   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57346   if( pMem->flags & MEM_Real ){
57347     return pMem->r;
57348   }else if( pMem->flags & MEM_Int ){
57349     return (double)pMem->u.i;
57350   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57351     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57352     double val = (double)0;
57353     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57354     return val;
57355   }else{
57356     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57357     return (double)0;
57358   }
57359 }
57360
57361 /*
57362 ** The MEM structure is already a MEM_Real.  Try to also make it a
57363 ** MEM_Int if we can.
57364 */
57365 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57366   assert( pMem->flags & MEM_Real );
57367   assert( (pMem->flags & MEM_RowSet)==0 );
57368   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57369   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57370
57371   pMem->u.i = doubleToInt64(pMem->r);
57372
57373   /* Only mark the value as an integer if
57374   **
57375   **    (1) the round-trip conversion real->int->real is a no-op, and
57376   **    (2) The integer is neither the largest nor the smallest
57377   **        possible integer (ticket #3922)
57378   **
57379   ** The second and third terms in the following conditional enforces
57380   ** the second condition under the assumption that addition overflow causes
57381   ** values to wrap around.  On x86 hardware, the third term is always
57382   ** true and could be omitted.  But we leave it in because other
57383   ** architectures might behave differently.
57384   */
57385   if( pMem->r==(double)pMem->u.i
57386    && pMem->u.i>SMALLEST_INT64
57387 #if defined(__i486__) || defined(__x86_64__)
57388    && ALWAYS(pMem->u.i<LARGEST_INT64)
57389 #else
57390    && pMem->u.i<LARGEST_INT64
57391 #endif
57392   ){
57393     pMem->flags |= MEM_Int;
57394   }
57395 }
57396
57397 /*
57398 ** Convert pMem to type integer.  Invalidate any prior representations.
57399 */
57400 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
57401   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57402   assert( (pMem->flags & MEM_RowSet)==0 );
57403   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57404
57405   pMem->u.i = sqlite3VdbeIntValue(pMem);
57406   MemSetTypeFlag(pMem, MEM_Int);
57407   return SQLITE_OK;
57408 }
57409
57410 /*
57411 ** Convert pMem so that it is of type MEM_Real.
57412 ** Invalidate any prior representations.
57413 */
57414 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
57415   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57416   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57417
57418   pMem->r = sqlite3VdbeRealValue(pMem);
57419   MemSetTypeFlag(pMem, MEM_Real);
57420   return SQLITE_OK;
57421 }
57422
57423 /*
57424 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
57425 ** Invalidate any prior representations.
57426 **
57427 ** Every effort is made to force the conversion, even if the input
57428 ** is a string that does not look completely like a number.  Convert
57429 ** as much of the string as we can and ignore the rest.
57430 */
57431 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
57432   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
57433     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
57434     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57435     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
57436       MemSetTypeFlag(pMem, MEM_Int);
57437     }else{
57438       pMem->r = sqlite3VdbeRealValue(pMem);
57439       MemSetTypeFlag(pMem, MEM_Real);
57440       sqlite3VdbeIntegerAffinity(pMem);
57441     }
57442   }
57443   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
57444   pMem->flags &= ~(MEM_Str|MEM_Blob);
57445   return SQLITE_OK;
57446 }
57447
57448 /*
57449 ** Delete any previous value and set the value stored in *pMem to NULL.
57450 */
57451 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
57452   if( pMem->flags & MEM_Frame ){
57453     VdbeFrame *pFrame = pMem->u.pFrame;
57454     pFrame->pParent = pFrame->v->pDelFrame;
57455     pFrame->v->pDelFrame = pFrame;
57456   }
57457   if( pMem->flags & MEM_RowSet ){
57458     sqlite3RowSetClear(pMem->u.pRowSet);
57459   }
57460   MemSetTypeFlag(pMem, MEM_Null);
57461   pMem->type = SQLITE_NULL;
57462 }
57463
57464 /*
57465 ** Delete any previous value and set the value to be a BLOB of length
57466 ** n containing all zeros.
57467 */
57468 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
57469   sqlite3VdbeMemRelease(pMem);
57470   pMem->flags = MEM_Blob|MEM_Zero;
57471   pMem->type = SQLITE_BLOB;
57472   pMem->n = 0;
57473   if( n<0 ) n = 0;
57474   pMem->u.nZero = n;
57475   pMem->enc = SQLITE_UTF8;
57476
57477 #ifdef SQLITE_OMIT_INCRBLOB
57478   sqlite3VdbeMemGrow(pMem, n, 0);
57479   if( pMem->z ){
57480     pMem->n = n;
57481     memset(pMem->z, 0, n);
57482   }
57483 #endif
57484 }
57485
57486 /*
57487 ** Delete any previous value and set the value stored in *pMem to val,
57488 ** manifest type INTEGER.
57489 */
57490 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
57491   sqlite3VdbeMemRelease(pMem);
57492   pMem->u.i = val;
57493   pMem->flags = MEM_Int;
57494   pMem->type = SQLITE_INTEGER;
57495 }
57496
57497 #ifndef SQLITE_OMIT_FLOATING_POINT
57498 /*
57499 ** Delete any previous value and set the value stored in *pMem to val,
57500 ** manifest type REAL.
57501 */
57502 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
57503   if( sqlite3IsNaN(val) ){
57504     sqlite3VdbeMemSetNull(pMem);
57505   }else{
57506     sqlite3VdbeMemRelease(pMem);
57507     pMem->r = val;
57508     pMem->flags = MEM_Real;
57509     pMem->type = SQLITE_FLOAT;
57510   }
57511 }
57512 #endif
57513
57514 /*
57515 ** Delete any previous value and set the value of pMem to be an
57516 ** empty boolean index.
57517 */
57518 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
57519   sqlite3 *db = pMem->db;
57520   assert( db!=0 );
57521   assert( (pMem->flags & MEM_RowSet)==0 );
57522   sqlite3VdbeMemRelease(pMem);
57523   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
57524   if( db->mallocFailed ){
57525     pMem->flags = MEM_Null;
57526   }else{
57527     assert( pMem->zMalloc );
57528     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
57529                                        sqlite3DbMallocSize(db, pMem->zMalloc));
57530     assert( pMem->u.pRowSet!=0 );
57531     pMem->flags = MEM_RowSet;
57532   }
57533 }
57534
57535 /*
57536 ** Return true if the Mem object contains a TEXT or BLOB that is
57537 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
57538 */
57539 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
57540   assert( p->db!=0 );
57541   if( p->flags & (MEM_Str|MEM_Blob) ){
57542     int n = p->n;
57543     if( p->flags & MEM_Zero ){
57544       n += p->u.nZero;
57545     }
57546     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
57547   }
57548   return 0; 
57549 }
57550
57551 #ifdef SQLITE_DEBUG
57552 /*
57553 ** This routine prepares a memory cell for modication by breaking
57554 ** its link to a shallow copy and by marking any current shallow
57555 ** copies of this cell as invalid.
57556 **
57557 ** This is used for testing and debugging only - to make sure shallow
57558 ** copies are not misused.
57559 */
57560 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
57561   int i;
57562   Mem *pX;
57563   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
57564     if( pX->pScopyFrom==pMem ){
57565       pX->flags |= MEM_Invalid;
57566       pX->pScopyFrom = 0;
57567     }
57568   }
57569   pMem->pScopyFrom = 0;
57570 }
57571 #endif /* SQLITE_DEBUG */
57572
57573 /*
57574 ** Size of struct Mem not including the Mem.zMalloc member.
57575 */
57576 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
57577
57578 /*
57579 ** Make an shallow copy of pFrom into pTo.  Prior contents of
57580 ** pTo are freed.  The pFrom->z field is not duplicated.  If
57581 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
57582 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
57583 */
57584 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
57585   assert( (pFrom->flags & MEM_RowSet)==0 );
57586   VdbeMemRelease(pTo);
57587   memcpy(pTo, pFrom, MEMCELLSIZE);
57588   pTo->xDel = 0;
57589   if( (pFrom->flags&MEM_Static)==0 ){
57590     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
57591     assert( srcType==MEM_Ephem || srcType==MEM_Static );
57592     pTo->flags |= srcType;
57593   }
57594 }
57595
57596 /*
57597 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
57598 ** freed before the copy is made.
57599 */
57600 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
57601   int rc = SQLITE_OK;
57602
57603   assert( (pFrom->flags & MEM_RowSet)==0 );
57604   VdbeMemRelease(pTo);
57605   memcpy(pTo, pFrom, MEMCELLSIZE);
57606   pTo->flags &= ~MEM_Dyn;
57607
57608   if( pTo->flags&(MEM_Str|MEM_Blob) ){
57609     if( 0==(pFrom->flags&MEM_Static) ){
57610       pTo->flags |= MEM_Ephem;
57611       rc = sqlite3VdbeMemMakeWriteable(pTo);
57612     }
57613   }
57614
57615   return rc;
57616 }
57617
57618 /*
57619 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
57620 ** freed. If pFrom contains ephemeral data, a copy is made.
57621 **
57622 ** pFrom contains an SQL NULL when this routine returns.
57623 */
57624 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
57625   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
57626   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
57627   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
57628
57629   sqlite3VdbeMemRelease(pTo);
57630   memcpy(pTo, pFrom, sizeof(Mem));
57631   pFrom->flags = MEM_Null;
57632   pFrom->xDel = 0;
57633   pFrom->zMalloc = 0;
57634 }
57635
57636 /*
57637 ** Change the value of a Mem to be a string or a BLOB.
57638 **
57639 ** The memory management strategy depends on the value of the xDel
57640 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
57641 ** string is copied into a (possibly existing) buffer managed by the 
57642 ** Mem structure. Otherwise, any existing buffer is freed and the
57643 ** pointer copied.
57644 **
57645 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
57646 ** size limit) then no memory allocation occurs.  If the string can be
57647 ** stored without allocating memory, then it is.  If a memory allocation
57648 ** is required to store the string, then value of pMem is unchanged.  In
57649 ** either case, SQLITE_TOOBIG is returned.
57650 */
57651 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
57652   Mem *pMem,          /* Memory cell to set to string value */
57653   const char *z,      /* String pointer */
57654   int n,              /* Bytes in string, or negative */
57655   u8 enc,             /* Encoding of z.  0 for BLOBs */
57656   void (*xDel)(void*) /* Destructor function */
57657 ){
57658   int nByte = n;      /* New value for pMem->n */
57659   int iLimit;         /* Maximum allowed string or blob size */
57660   u16 flags = 0;      /* New value for pMem->flags */
57661
57662   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57663   assert( (pMem->flags & MEM_RowSet)==0 );
57664
57665   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
57666   if( !z ){
57667     sqlite3VdbeMemSetNull(pMem);
57668     return SQLITE_OK;
57669   }
57670
57671   if( pMem->db ){
57672     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
57673   }else{
57674     iLimit = SQLITE_MAX_LENGTH;
57675   }
57676   flags = (enc==0?MEM_Blob:MEM_Str);
57677   if( nByte<0 ){
57678     assert( enc!=0 );
57679     if( enc==SQLITE_UTF8 ){
57680       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
57681     }else{
57682       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
57683     }
57684     flags |= MEM_Term;
57685   }
57686
57687   /* The following block sets the new values of Mem.z and Mem.xDel. It
57688   ** also sets a flag in local variable "flags" to indicate the memory
57689   ** management (one of MEM_Dyn or MEM_Static).
57690   */
57691   if( xDel==SQLITE_TRANSIENT ){
57692     int nAlloc = nByte;
57693     if( flags&MEM_Term ){
57694       nAlloc += (enc==SQLITE_UTF8?1:2);
57695     }
57696     if( nByte>iLimit ){
57697       return SQLITE_TOOBIG;
57698     }
57699     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
57700       return SQLITE_NOMEM;
57701     }
57702     memcpy(pMem->z, z, nAlloc);
57703   }else if( xDel==SQLITE_DYNAMIC ){
57704     sqlite3VdbeMemRelease(pMem);
57705     pMem->zMalloc = pMem->z = (char *)z;
57706     pMem->xDel = 0;
57707   }else{
57708     sqlite3VdbeMemRelease(pMem);
57709     pMem->z = (char *)z;
57710     pMem->xDel = xDel;
57711     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
57712   }
57713
57714   pMem->n = nByte;
57715   pMem->flags = flags;
57716   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
57717   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
57718
57719 #ifndef SQLITE_OMIT_UTF16
57720   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
57721     return SQLITE_NOMEM;
57722   }
57723 #endif
57724
57725   if( nByte>iLimit ){
57726     return SQLITE_TOOBIG;
57727   }
57728
57729   return SQLITE_OK;
57730 }
57731
57732 /*
57733 ** Compare the values contained by the two memory cells, returning
57734 ** negative, zero or positive if pMem1 is less than, equal to, or greater
57735 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
57736 ** and reals) sorted numerically, followed by text ordered by the collating
57737 ** sequence pColl and finally blob's ordered by memcmp().
57738 **
57739 ** Two NULL values are considered equal by this function.
57740 */
57741 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
57742   int rc;
57743   int f1, f2;
57744   int combined_flags;
57745
57746   f1 = pMem1->flags;
57747   f2 = pMem2->flags;
57748   combined_flags = f1|f2;
57749   assert( (combined_flags & MEM_RowSet)==0 );
57750  
57751   /* If one value is NULL, it is less than the other. If both values
57752   ** are NULL, return 0.
57753   */
57754   if( combined_flags&MEM_Null ){
57755     return (f2&MEM_Null) - (f1&MEM_Null);
57756   }
57757
57758   /* If one value is a number and the other is not, the number is less.
57759   ** If both are numbers, compare as reals if one is a real, or as integers
57760   ** if both values are integers.
57761   */
57762   if( combined_flags&(MEM_Int|MEM_Real) ){
57763     if( !(f1&(MEM_Int|MEM_Real)) ){
57764       return 1;
57765     }
57766     if( !(f2&(MEM_Int|MEM_Real)) ){
57767       return -1;
57768     }
57769     if( (f1 & f2 & MEM_Int)==0 ){
57770       double r1, r2;
57771       if( (f1&MEM_Real)==0 ){
57772         r1 = (double)pMem1->u.i;
57773       }else{
57774         r1 = pMem1->r;
57775       }
57776       if( (f2&MEM_Real)==0 ){
57777         r2 = (double)pMem2->u.i;
57778       }else{
57779         r2 = pMem2->r;
57780       }
57781       if( r1<r2 ) return -1;
57782       if( r1>r2 ) return 1;
57783       return 0;
57784     }else{
57785       assert( f1&MEM_Int );
57786       assert( f2&MEM_Int );
57787       if( pMem1->u.i < pMem2->u.i ) return -1;
57788       if( pMem1->u.i > pMem2->u.i ) return 1;
57789       return 0;
57790     }
57791   }
57792
57793   /* If one value is a string and the other is a blob, the string is less.
57794   ** If both are strings, compare using the collating functions.
57795   */
57796   if( combined_flags&MEM_Str ){
57797     if( (f1 & MEM_Str)==0 ){
57798       return 1;
57799     }
57800     if( (f2 & MEM_Str)==0 ){
57801       return -1;
57802     }
57803
57804     assert( pMem1->enc==pMem2->enc );
57805     assert( pMem1->enc==SQLITE_UTF8 || 
57806             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
57807
57808     /* The collation sequence must be defined at this point, even if
57809     ** the user deletes the collation sequence after the vdbe program is
57810     ** compiled (this was not always the case).
57811     */
57812     assert( !pColl || pColl->xCmp );
57813
57814     if( pColl ){
57815       if( pMem1->enc==pColl->enc ){
57816         /* The strings are already in the correct encoding.  Call the
57817         ** comparison function directly */
57818         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
57819       }else{
57820         const void *v1, *v2;
57821         int n1, n2;
57822         Mem c1;
57823         Mem c2;
57824         memset(&c1, 0, sizeof(c1));
57825         memset(&c2, 0, sizeof(c2));
57826         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
57827         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
57828         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
57829         n1 = v1==0 ? 0 : c1.n;
57830         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
57831         n2 = v2==0 ? 0 : c2.n;
57832         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
57833         sqlite3VdbeMemRelease(&c1);
57834         sqlite3VdbeMemRelease(&c2);
57835         return rc;
57836       }
57837     }
57838     /* If a NULL pointer was passed as the collate function, fall through
57839     ** to the blob case and use memcmp().  */
57840   }
57841  
57842   /* Both values must be blobs.  Compare using memcmp().  */
57843   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
57844   if( rc==0 ){
57845     rc = pMem1->n - pMem2->n;
57846   }
57847   return rc;
57848 }
57849
57850 /*
57851 ** Move data out of a btree key or data field and into a Mem structure.
57852 ** The data or key is taken from the entry that pCur is currently pointing
57853 ** to.  offset and amt determine what portion of the data or key to retrieve.
57854 ** key is true to get the key or false to get data.  The result is written
57855 ** into the pMem element.
57856 **
57857 ** The pMem structure is assumed to be uninitialized.  Any prior content
57858 ** is overwritten without being freed.
57859 **
57860 ** If this routine fails for any reason (malloc returns NULL or unable
57861 ** to read from the disk) then the pMem is left in an inconsistent state.
57862 */
57863 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
57864   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
57865   int offset,       /* Offset from the start of data to return bytes from. */
57866   int amt,          /* Number of bytes to return. */
57867   int key,          /* If true, retrieve from the btree key, not data. */
57868   Mem *pMem         /* OUT: Return data in this Mem structure. */
57869 ){
57870   char *zData;        /* Data from the btree layer */
57871   int available = 0;  /* Number of bytes available on the local btree page */
57872   int rc = SQLITE_OK; /* Return code */
57873
57874   assert( sqlite3BtreeCursorIsValid(pCur) );
57875
57876   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
57877   ** that both the BtShared and database handle mutexes are held. */
57878   assert( (pMem->flags & MEM_RowSet)==0 );
57879   if( key ){
57880     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
57881   }else{
57882     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
57883   }
57884   assert( zData!=0 );
57885
57886   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
57887     sqlite3VdbeMemRelease(pMem);
57888     pMem->z = &zData[offset];
57889     pMem->flags = MEM_Blob|MEM_Ephem;
57890   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
57891     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
57892     pMem->enc = 0;
57893     pMem->type = SQLITE_BLOB;
57894     if( key ){
57895       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
57896     }else{
57897       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
57898     }
57899     pMem->z[amt] = 0;
57900     pMem->z[amt+1] = 0;
57901     if( rc!=SQLITE_OK ){
57902       sqlite3VdbeMemRelease(pMem);
57903     }
57904   }
57905   pMem->n = amt;
57906
57907   return rc;
57908 }
57909
57910 /* This function is only available internally, it is not part of the
57911 ** external API. It works in a similar way to sqlite3_value_text(),
57912 ** except the data returned is in the encoding specified by the second
57913 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
57914 ** SQLITE_UTF8.
57915 **
57916 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
57917 ** If that is the case, then the result must be aligned on an even byte
57918 ** boundary.
57919 */
57920 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
57921   if( !pVal ) return 0;
57922
57923   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
57924   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
57925   assert( (pVal->flags & MEM_RowSet)==0 );
57926
57927   if( pVal->flags&MEM_Null ){
57928     return 0;
57929   }
57930   assert( (MEM_Blob>>3) == MEM_Str );
57931   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
57932   ExpandBlob(pVal);
57933   if( pVal->flags&MEM_Str ){
57934     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
57935     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
57936       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
57937       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
57938         return 0;
57939       }
57940     }
57941     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
57942   }else{
57943     assert( (pVal->flags&MEM_Blob)==0 );
57944     sqlite3VdbeMemStringify(pVal, enc);
57945     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
57946   }
57947   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
57948               || pVal->db->mallocFailed );
57949   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
57950     return pVal->z;
57951   }else{
57952     return 0;
57953   }
57954 }
57955
57956 /*
57957 ** Create a new sqlite3_value object.
57958 */
57959 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
57960   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
57961   if( p ){
57962     p->flags = MEM_Null;
57963     p->type = SQLITE_NULL;
57964     p->db = db;
57965   }
57966   return p;
57967 }
57968
57969 /*
57970 ** Create a new sqlite3_value object, containing the value of pExpr.
57971 **
57972 ** This only works for very simple expressions that consist of one constant
57973 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
57974 ** be converted directly into a value, then the value is allocated and
57975 ** a pointer written to *ppVal. The caller is responsible for deallocating
57976 ** the value by passing it to sqlite3ValueFree() later on. If the expression
57977 ** cannot be converted to a value, then *ppVal is set to NULL.
57978 */
57979 SQLITE_PRIVATE int sqlite3ValueFromExpr(
57980   sqlite3 *db,              /* The database connection */
57981   Expr *pExpr,              /* The expression to evaluate */
57982   u8 enc,                   /* Encoding to use */
57983   u8 affinity,              /* Affinity to use */
57984   sqlite3_value **ppVal     /* Write the new value here */
57985 ){
57986   int op;
57987   char *zVal = 0;
57988   sqlite3_value *pVal = 0;
57989   int negInt = 1;
57990   const char *zNeg = "";
57991
57992   if( !pExpr ){
57993     *ppVal = 0;
57994     return SQLITE_OK;
57995   }
57996   op = pExpr->op;
57997
57998   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
57999   ** The ifdef here is to enable us to achieve 100% branch test coverage even
58000   ** when SQLITE_ENABLE_STAT3 is omitted.
58001   */
58002 #ifdef SQLITE_ENABLE_STAT3
58003   if( op==TK_REGISTER ) op = pExpr->op2;
58004 #else
58005   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58006 #endif
58007
58008   /* Handle negative integers in a single step.  This is needed in the
58009   ** case when the value is -9223372036854775808.
58010   */
58011   if( op==TK_UMINUS
58012    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58013     pExpr = pExpr->pLeft;
58014     op = pExpr->op;
58015     negInt = -1;
58016     zNeg = "-";
58017   }
58018
58019   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58020     pVal = sqlite3ValueNew(db);
58021     if( pVal==0 ) goto no_mem;
58022     if( ExprHasProperty(pExpr, EP_IntValue) ){
58023       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58024     }else{
58025       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58026       if( zVal==0 ) goto no_mem;
58027       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58028       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58029     }
58030     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58031       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58032     }else{
58033       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58034     }
58035     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58036     if( enc!=SQLITE_UTF8 ){
58037       sqlite3VdbeChangeEncoding(pVal, enc);
58038     }
58039   }else if( op==TK_UMINUS ) {
58040     /* This branch happens for multiple negative signs.  Ex: -(-5) */
58041     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58042       sqlite3VdbeMemNumerify(pVal);
58043       if( pVal->u.i==SMALLEST_INT64 ){
58044         pVal->flags &= MEM_Int;
58045         pVal->flags |= MEM_Real;
58046         pVal->r = (double)LARGEST_INT64;
58047       }else{
58048         pVal->u.i = -pVal->u.i;
58049       }
58050       pVal->r = -pVal->r;
58051       sqlite3ValueApplyAffinity(pVal, affinity, enc);
58052     }
58053   }else if( op==TK_NULL ){
58054     pVal = sqlite3ValueNew(db);
58055     if( pVal==0 ) goto no_mem;
58056   }
58057 #ifndef SQLITE_OMIT_BLOB_LITERAL
58058   else if( op==TK_BLOB ){
58059     int nVal;
58060     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58061     assert( pExpr->u.zToken[1]=='\'' );
58062     pVal = sqlite3ValueNew(db);
58063     if( !pVal ) goto no_mem;
58064     zVal = &pExpr->u.zToken[2];
58065     nVal = sqlite3Strlen30(zVal)-1;
58066     assert( zVal[nVal]=='\'' );
58067     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58068                          0, SQLITE_DYNAMIC);
58069   }
58070 #endif
58071
58072   if( pVal ){
58073     sqlite3VdbeMemStoreType(pVal);
58074   }
58075   *ppVal = pVal;
58076   return SQLITE_OK;
58077
58078 no_mem:
58079   db->mallocFailed = 1;
58080   sqlite3DbFree(db, zVal);
58081   sqlite3ValueFree(pVal);
58082   *ppVal = 0;
58083   return SQLITE_NOMEM;
58084 }
58085
58086 /*
58087 ** Change the string value of an sqlite3_value object
58088 */
58089 SQLITE_PRIVATE void sqlite3ValueSetStr(
58090   sqlite3_value *v,     /* Value to be set */
58091   int n,                /* Length of string z */
58092   const void *z,        /* Text of the new string */
58093   u8 enc,               /* Encoding to use */
58094   void (*xDel)(void*)   /* Destructor for the string */
58095 ){
58096   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58097 }
58098
58099 /*
58100 ** Free an sqlite3_value object
58101 */
58102 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58103   if( !v ) return;
58104   sqlite3VdbeMemRelease((Mem *)v);
58105   sqlite3DbFree(((Mem*)v)->db, v);
58106 }
58107
58108 /*
58109 ** Return the number of bytes in the sqlite3_value object assuming
58110 ** that it uses the encoding "enc"
58111 */
58112 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58113   Mem *p = (Mem*)pVal;
58114   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58115     if( p->flags & MEM_Zero ){
58116       return p->n + p->u.nZero;
58117     }else{
58118       return p->n;
58119     }
58120   }
58121   return 0;
58122 }
58123
58124 /************** End of vdbemem.c *********************************************/
58125 /************** Begin file vdbeaux.c *****************************************/
58126 /*
58127 ** 2003 September 6
58128 **
58129 ** The author disclaims copyright to this source code.  In place of
58130 ** a legal notice, here is a blessing:
58131 **
58132 **    May you do good and not evil.
58133 **    May you find forgiveness for yourself and forgive others.
58134 **    May you share freely, never taking more than you give.
58135 **
58136 *************************************************************************
58137 ** This file contains code used for creating, destroying, and populating
58138 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
58139 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58140 ** But that file was getting too big so this subroutines were split out.
58141 */
58142
58143
58144
58145 /*
58146 ** When debugging the code generator in a symbolic debugger, one can
58147 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
58148 ** as they are added to the instruction stream.
58149 */
58150 #ifdef SQLITE_DEBUG
58151 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
58152 #endif
58153
58154
58155 /*
58156 ** Create a new virtual database engine.
58157 */
58158 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58159   Vdbe *p;
58160   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58161   if( p==0 ) return 0;
58162   p->db = db;
58163   if( db->pVdbe ){
58164     db->pVdbe->pPrev = p;
58165   }
58166   p->pNext = db->pVdbe;
58167   p->pPrev = 0;
58168   db->pVdbe = p;
58169   p->magic = VDBE_MAGIC_INIT;
58170   return p;
58171 }
58172
58173 /*
58174 ** Remember the SQL string for a prepared statement.
58175 */
58176 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58177   assert( isPrepareV2==1 || isPrepareV2==0 );
58178   if( p==0 ) return;
58179 #ifdef SQLITE_OMIT_TRACE
58180   if( !isPrepareV2 ) return;
58181 #endif
58182   assert( p->zSql==0 );
58183   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58184   p->isPrepareV2 = (u8)isPrepareV2;
58185 }
58186
58187 /*
58188 ** Return the SQL associated with a prepared statement
58189 */
58190 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58191   Vdbe *p = (Vdbe *)pStmt;
58192   return (p && p->isPrepareV2) ? p->zSql : 0;
58193 }
58194
58195 /*
58196 ** Swap all content between two VDBE structures.
58197 */
58198 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58199   Vdbe tmp, *pTmp;
58200   char *zTmp;
58201   tmp = *pA;
58202   *pA = *pB;
58203   *pB = tmp;
58204   pTmp = pA->pNext;
58205   pA->pNext = pB->pNext;
58206   pB->pNext = pTmp;
58207   pTmp = pA->pPrev;
58208   pA->pPrev = pB->pPrev;
58209   pB->pPrev = pTmp;
58210   zTmp = pA->zSql;
58211   pA->zSql = pB->zSql;
58212   pB->zSql = zTmp;
58213   pB->isPrepareV2 = pA->isPrepareV2;
58214 }
58215
58216 #ifdef SQLITE_DEBUG
58217 /*
58218 ** Turn tracing on or off
58219 */
58220 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58221   p->trace = trace;
58222 }
58223 #endif
58224
58225 /*
58226 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
58227 ** it was.
58228 **
58229 ** If an out-of-memory error occurs while resizing the array, return
58230 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
58231 ** unchanged (this is so that any opcodes already allocated can be 
58232 ** correctly deallocated along with the rest of the Vdbe).
58233 */
58234 static int growOpArray(Vdbe *p){
58235   VdbeOp *pNew;
58236   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58237   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58238   if( pNew ){
58239     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58240     p->aOp = pNew;
58241   }
58242   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58243 }
58244
58245 /*
58246 ** Add a new instruction to the list of instructions current in the
58247 ** VDBE.  Return the address of the new instruction.
58248 **
58249 ** Parameters:
58250 **
58251 **    p               Pointer to the VDBE
58252 **
58253 **    op              The opcode for this instruction
58254 **
58255 **    p1, p2, p3      Operands
58256 **
58257 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58258 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58259 ** operand.
58260 */
58261 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58262   int i;
58263   VdbeOp *pOp;
58264
58265   i = p->nOp;
58266   assert( p->magic==VDBE_MAGIC_INIT );
58267   assert( op>0 && op<0xff );
58268   if( p->nOpAlloc<=i ){
58269     if( growOpArray(p) ){
58270       return 1;
58271     }
58272   }
58273   p->nOp++;
58274   pOp = &p->aOp[i];
58275   pOp->opcode = (u8)op;
58276   pOp->p5 = 0;
58277   pOp->p1 = p1;
58278   pOp->p2 = p2;
58279   pOp->p3 = p3;
58280   pOp->p4.p = 0;
58281   pOp->p4type = P4_NOTUSED;
58282 #ifdef SQLITE_DEBUG
58283   pOp->zComment = 0;
58284   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58285 #endif
58286 #ifdef VDBE_PROFILE
58287   pOp->cycles = 0;
58288   pOp->cnt = 0;
58289 #endif
58290   return i;
58291 }
58292 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58293   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58294 }
58295 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58296   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58297 }
58298 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58299   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58300 }
58301
58302
58303 /*
58304 ** Add an opcode that includes the p4 value as a pointer.
58305 */
58306 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58307   Vdbe *p,            /* Add the opcode to this VM */
58308   int op,             /* The new opcode */
58309   int p1,             /* The P1 operand */
58310   int p2,             /* The P2 operand */
58311   int p3,             /* The P3 operand */
58312   const char *zP4,    /* The P4 operand */
58313   int p4type          /* P4 operand type */
58314 ){
58315   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58316   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58317   return addr;
58318 }
58319
58320 /*
58321 ** Add an OP_ParseSchema opcode.  This routine is broken out from
58322 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
58323 ** as having been used.
58324 **
58325 ** The zWhere string must have been obtained from sqlite3_malloc().
58326 ** This routine will take ownership of the allocated memory.
58327 */
58328 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58329   int j;
58330   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58331   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58332   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58333 }
58334
58335 /*
58336 ** Add an opcode that includes the p4 value as an integer.
58337 */
58338 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58339   Vdbe *p,            /* Add the opcode to this VM */
58340   int op,             /* The new opcode */
58341   int p1,             /* The P1 operand */
58342   int p2,             /* The P2 operand */
58343   int p3,             /* The P3 operand */
58344   int p4              /* The P4 operand as an integer */
58345 ){
58346   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58347   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58348   return addr;
58349 }
58350
58351 /*
58352 ** Create a new symbolic label for an instruction that has yet to be
58353 ** coded.  The symbolic label is really just a negative number.  The
58354 ** label can be used as the P2 value of an operation.  Later, when
58355 ** the label is resolved to a specific address, the VDBE will scan
58356 ** through its operation list and change all values of P2 which match
58357 ** the label into the resolved address.
58358 **
58359 ** The VDBE knows that a P2 value is a label because labels are
58360 ** always negative and P2 values are suppose to be non-negative.
58361 ** Hence, a negative P2 value is a label that has yet to be resolved.
58362 **
58363 ** Zero is returned if a malloc() fails.
58364 */
58365 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58366   int i = p->nLabel++;
58367   assert( p->magic==VDBE_MAGIC_INIT );
58368   if( (i & (i-1))==0 ){
58369     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
58370                                        (i*2+1)*sizeof(p->aLabel[0]));
58371   }
58372   if( p->aLabel ){
58373     p->aLabel[i] = -1;
58374   }
58375   return -1-i;
58376 }
58377
58378 /*
58379 ** Resolve label "x" to be the address of the next instruction to
58380 ** be inserted.  The parameter "x" must have been obtained from
58381 ** a prior call to sqlite3VdbeMakeLabel().
58382 */
58383 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58384   int j = -1-x;
58385   assert( p->magic==VDBE_MAGIC_INIT );
58386   assert( j>=0 && j<p->nLabel );
58387   if( p->aLabel ){
58388     p->aLabel[j] = p->nOp;
58389   }
58390 }
58391
58392 /*
58393 ** Mark the VDBE as one that can only be run one time.
58394 */
58395 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
58396   p->runOnlyOnce = 1;
58397 }
58398
58399 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
58400
58401 /*
58402 ** The following type and function are used to iterate through all opcodes
58403 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
58404 ** invoke directly or indirectly. It should be used as follows:
58405 **
58406 **   Op *pOp;
58407 **   VdbeOpIter sIter;
58408 **
58409 **   memset(&sIter, 0, sizeof(sIter));
58410 **   sIter.v = v;                            // v is of type Vdbe* 
58411 **   while( (pOp = opIterNext(&sIter)) ){
58412 **     // Do something with pOp
58413 **   }
58414 **   sqlite3DbFree(v->db, sIter.apSub);
58415 ** 
58416 */
58417 typedef struct VdbeOpIter VdbeOpIter;
58418 struct VdbeOpIter {
58419   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
58420   SubProgram **apSub;        /* Array of subprograms */
58421   int nSub;                  /* Number of entries in apSub */
58422   int iAddr;                 /* Address of next instruction to return */
58423   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
58424 };
58425 static Op *opIterNext(VdbeOpIter *p){
58426   Vdbe *v = p->v;
58427   Op *pRet = 0;
58428   Op *aOp;
58429   int nOp;
58430
58431   if( p->iSub<=p->nSub ){
58432
58433     if( p->iSub==0 ){
58434       aOp = v->aOp;
58435       nOp = v->nOp;
58436     }else{
58437       aOp = p->apSub[p->iSub-1]->aOp;
58438       nOp = p->apSub[p->iSub-1]->nOp;
58439     }
58440     assert( p->iAddr<nOp );
58441
58442     pRet = &aOp[p->iAddr];
58443     p->iAddr++;
58444     if( p->iAddr==nOp ){
58445       p->iSub++;
58446       p->iAddr = 0;
58447     }
58448   
58449     if( pRet->p4type==P4_SUBPROGRAM ){
58450       int nByte = (p->nSub+1)*sizeof(SubProgram*);
58451       int j;
58452       for(j=0; j<p->nSub; j++){
58453         if( p->apSub[j]==pRet->p4.pProgram ) break;
58454       }
58455       if( j==p->nSub ){
58456         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
58457         if( !p->apSub ){
58458           pRet = 0;
58459         }else{
58460           p->apSub[p->nSub++] = pRet->p4.pProgram;
58461         }
58462       }
58463     }
58464   }
58465
58466   return pRet;
58467 }
58468
58469 /*
58470 ** Check if the program stored in the VM associated with pParse may
58471 ** throw an ABORT exception (causing the statement, but not entire transaction
58472 ** to be rolled back). This condition is true if the main program or any
58473 ** sub-programs contains any of the following:
58474 **
58475 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58476 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58477 **   *  OP_Destroy
58478 **   *  OP_VUpdate
58479 **   *  OP_VRename
58480 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
58481 **
58482 ** Then check that the value of Parse.mayAbort is true if an
58483 ** ABORT may be thrown, or false otherwise. Return true if it does
58484 ** match, or false otherwise. This function is intended to be used as
58485 ** part of an assert statement in the compiler. Similar to:
58486 **
58487 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
58488 */
58489 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
58490   int hasAbort = 0;
58491   Op *pOp;
58492   VdbeOpIter sIter;
58493   memset(&sIter, 0, sizeof(sIter));
58494   sIter.v = v;
58495
58496   while( (pOp = opIterNext(&sIter))!=0 ){
58497     int opcode = pOp->opcode;
58498     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
58499 #ifndef SQLITE_OMIT_FOREIGN_KEY
58500      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
58501 #endif
58502      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
58503       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
58504     ){
58505       hasAbort = 1;
58506       break;
58507     }
58508   }
58509   sqlite3DbFree(v->db, sIter.apSub);
58510
58511   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
58512   ** If malloc failed, then the while() loop above may not have iterated
58513   ** through all opcodes and hasAbort may be set incorrectly. Return
58514   ** true for this case to prevent the assert() in the callers frame
58515   ** from failing.  */
58516   return ( v->db->mallocFailed || hasAbort==mayAbort );
58517 }
58518 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
58519
58520 /*
58521 ** Loop through the program looking for P2 values that are negative
58522 ** on jump instructions.  Each such value is a label.  Resolve the
58523 ** label by setting the P2 value to its correct non-zero value.
58524 **
58525 ** This routine is called once after all opcodes have been inserted.
58526 **
58527 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
58528 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
58529 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
58530 **
58531 ** The Op.opflags field is set on all opcodes.
58532 */
58533 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
58534   int i;
58535   int nMaxArgs = *pMaxFuncArgs;
58536   Op *pOp;
58537   int *aLabel = p->aLabel;
58538   p->readOnly = 1;
58539   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
58540     u8 opcode = pOp->opcode;
58541
58542     pOp->opflags = sqlite3OpcodeProperty[opcode];
58543     if( opcode==OP_Function || opcode==OP_AggStep ){
58544       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
58545     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
58546       p->readOnly = 0;
58547 #ifndef SQLITE_OMIT_VIRTUALTABLE
58548     }else if( opcode==OP_VUpdate ){
58549       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
58550     }else if( opcode==OP_VFilter ){
58551       int n;
58552       assert( p->nOp - i >= 3 );
58553       assert( pOp[-1].opcode==OP_Integer );
58554       n = pOp[-1].p1;
58555       if( n>nMaxArgs ) nMaxArgs = n;
58556 #endif
58557     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
58558       pOp->p4.xAdvance = sqlite3BtreeNext;
58559       pOp->p4type = P4_ADVANCE;
58560     }else if( opcode==OP_Prev ){
58561       pOp->p4.xAdvance = sqlite3BtreePrevious;
58562       pOp->p4type = P4_ADVANCE;
58563     }
58564
58565     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
58566       assert( -1-pOp->p2<p->nLabel );
58567       pOp->p2 = aLabel[-1-pOp->p2];
58568     }
58569   }
58570   sqlite3DbFree(p->db, p->aLabel);
58571   p->aLabel = 0;
58572
58573   *pMaxFuncArgs = nMaxArgs;
58574 }
58575
58576 /*
58577 ** Return the address of the next instruction to be inserted.
58578 */
58579 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
58580   assert( p->magic==VDBE_MAGIC_INIT );
58581   return p->nOp;
58582 }
58583
58584 /*
58585 ** This function returns a pointer to the array of opcodes associated with
58586 ** the Vdbe passed as the first argument. It is the callers responsibility
58587 ** to arrange for the returned array to be eventually freed using the 
58588 ** vdbeFreeOpArray() function.
58589 **
58590 ** Before returning, *pnOp is set to the number of entries in the returned
58591 ** array. Also, *pnMaxArg is set to the larger of its current value and 
58592 ** the number of entries in the Vdbe.apArg[] array required to execute the 
58593 ** returned program.
58594 */
58595 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
58596   VdbeOp *aOp = p->aOp;
58597   assert( aOp && !p->db->mallocFailed );
58598
58599   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
58600   assert( p->btreeMask==0 );
58601
58602   resolveP2Values(p, pnMaxArg);
58603   *pnOp = p->nOp;
58604   p->aOp = 0;
58605   return aOp;
58606 }
58607
58608 /*
58609 ** Add a whole list of operations to the operation stack.  Return the
58610 ** address of the first operation added.
58611 */
58612 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
58613   int addr;
58614   assert( p->magic==VDBE_MAGIC_INIT );
58615   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
58616     return 0;
58617   }
58618   addr = p->nOp;
58619   if( ALWAYS(nOp>0) ){
58620     int i;
58621     VdbeOpList const *pIn = aOp;
58622     for(i=0; i<nOp; i++, pIn++){
58623       int p2 = pIn->p2;
58624       VdbeOp *pOut = &p->aOp[i+addr];
58625       pOut->opcode = pIn->opcode;
58626       pOut->p1 = pIn->p1;
58627       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
58628         pOut->p2 = addr + ADDR(p2);
58629       }else{
58630         pOut->p2 = p2;
58631       }
58632       pOut->p3 = pIn->p3;
58633       pOut->p4type = P4_NOTUSED;
58634       pOut->p4.p = 0;
58635       pOut->p5 = 0;
58636 #ifdef SQLITE_DEBUG
58637       pOut->zComment = 0;
58638       if( sqlite3VdbeAddopTrace ){
58639         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
58640       }
58641 #endif
58642     }
58643     p->nOp += nOp;
58644   }
58645   return addr;
58646 }
58647
58648 /*
58649 ** Change the value of the P1 operand for a specific instruction.
58650 ** This routine is useful when a large program is loaded from a
58651 ** static array using sqlite3VdbeAddOpList but we want to make a
58652 ** few minor changes to the program.
58653 */
58654 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
58655   assert( p!=0 );
58656   if( ((u32)p->nOp)>addr ){
58657     p->aOp[addr].p1 = val;
58658   }
58659 }
58660
58661 /*
58662 ** Change the value of the P2 operand for a specific instruction.
58663 ** This routine is useful for setting a jump destination.
58664 */
58665 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
58666   assert( p!=0 );
58667   if( ((u32)p->nOp)>addr ){
58668     p->aOp[addr].p2 = val;
58669   }
58670 }
58671
58672 /*
58673 ** Change the value of the P3 operand for a specific instruction.
58674 */
58675 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
58676   assert( p!=0 );
58677   if( ((u32)p->nOp)>addr ){
58678     p->aOp[addr].p3 = val;
58679   }
58680 }
58681
58682 /*
58683 ** Change the value of the P5 operand for the most recently
58684 ** added operation.
58685 */
58686 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
58687   assert( p!=0 );
58688   if( p->aOp ){
58689     assert( p->nOp>0 );
58690     p->aOp[p->nOp-1].p5 = val;
58691   }
58692 }
58693
58694 /*
58695 ** Change the P2 operand of instruction addr so that it points to
58696 ** the address of the next instruction to be coded.
58697 */
58698 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
58699   assert( addr>=0 || p->db->mallocFailed );
58700   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
58701 }
58702
58703
58704 /*
58705 ** If the input FuncDef structure is ephemeral, then free it.  If
58706 ** the FuncDef is not ephermal, then do nothing.
58707 */
58708 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
58709   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
58710     sqlite3DbFree(db, pDef);
58711   }
58712 }
58713
58714 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
58715
58716 /*
58717 ** Delete a P4 value if necessary.
58718 */
58719 static void freeP4(sqlite3 *db, int p4type, void *p4){
58720   if( p4 ){
58721     assert( db );
58722     switch( p4type ){
58723       case P4_REAL:
58724       case P4_INT64:
58725       case P4_DYNAMIC:
58726       case P4_KEYINFO:
58727       case P4_INTARRAY:
58728       case P4_KEYINFO_HANDOFF: {
58729         sqlite3DbFree(db, p4);
58730         break;
58731       }
58732       case P4_MPRINTF: {
58733         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
58734         break;
58735       }
58736       case P4_VDBEFUNC: {
58737         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
58738         freeEphemeralFunction(db, pVdbeFunc->pFunc);
58739         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
58740         sqlite3DbFree(db, pVdbeFunc);
58741         break;
58742       }
58743       case P4_FUNCDEF: {
58744         freeEphemeralFunction(db, (FuncDef*)p4);
58745         break;
58746       }
58747       case P4_MEM: {
58748         if( db->pnBytesFreed==0 ){
58749           sqlite3ValueFree((sqlite3_value*)p4);
58750         }else{
58751           Mem *p = (Mem*)p4;
58752           sqlite3DbFree(db, p->zMalloc);
58753           sqlite3DbFree(db, p);
58754         }
58755         break;
58756       }
58757       case P4_VTAB : {
58758         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
58759         break;
58760       }
58761     }
58762   }
58763 }
58764
58765 /*
58766 ** Free the space allocated for aOp and any p4 values allocated for the
58767 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
58768 ** nOp entries. 
58769 */
58770 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
58771   if( aOp ){
58772     Op *pOp;
58773     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
58774       freeP4(db, pOp->p4type, pOp->p4.p);
58775 #ifdef SQLITE_DEBUG
58776       sqlite3DbFree(db, pOp->zComment);
58777 #endif     
58778     }
58779   }
58780   sqlite3DbFree(db, aOp);
58781 }
58782
58783 /*
58784 ** Link the SubProgram object passed as the second argument into the linked
58785 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
58786 ** objects when the VM is no longer required.
58787 */
58788 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
58789   p->pNext = pVdbe->pProgram;
58790   pVdbe->pProgram = p;
58791 }
58792
58793 /*
58794 ** Change the opcode at addr into OP_Noop
58795 */
58796 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
58797   if( p->aOp ){
58798     VdbeOp *pOp = &p->aOp[addr];
58799     sqlite3 *db = p->db;
58800     freeP4(db, pOp->p4type, pOp->p4.p);
58801     memset(pOp, 0, sizeof(pOp[0]));
58802     pOp->opcode = OP_Noop;
58803   }
58804 }
58805
58806 /*
58807 ** Change the value of the P4 operand for a specific instruction.
58808 ** This routine is useful when a large program is loaded from a
58809 ** static array using sqlite3VdbeAddOpList but we want to make a
58810 ** few minor changes to the program.
58811 **
58812 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
58813 ** the string is made into memory obtained from sqlite3_malloc().
58814 ** A value of n==0 means copy bytes of zP4 up to and including the
58815 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
58816 **
58817 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
58818 ** A copy is made of the KeyInfo structure into memory obtained from
58819 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
58820 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
58821 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
58822 ** caller should not free the allocation, it will be freed when the Vdbe is
58823 ** finalized.
58824 ** 
58825 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
58826 ** to a string or structure that is guaranteed to exist for the lifetime of
58827 ** the Vdbe. In these cases we can just copy the pointer.
58828 **
58829 ** If addr<0 then change P4 on the most recently inserted instruction.
58830 */
58831 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
58832   Op *pOp;
58833   sqlite3 *db;
58834   assert( p!=0 );
58835   db = p->db;
58836   assert( p->magic==VDBE_MAGIC_INIT );
58837   if( p->aOp==0 || db->mallocFailed ){
58838     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
58839       freeP4(db, n, (void*)*(char**)&zP4);
58840     }
58841     return;
58842   }
58843   assert( p->nOp>0 );
58844   assert( addr<p->nOp );
58845   if( addr<0 ){
58846     addr = p->nOp - 1;
58847   }
58848   pOp = &p->aOp[addr];
58849   freeP4(db, pOp->p4type, pOp->p4.p);
58850   pOp->p4.p = 0;
58851   if( n==P4_INT32 ){
58852     /* Note: this cast is safe, because the origin data point was an int
58853     ** that was cast to a (const char *). */
58854     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
58855     pOp->p4type = P4_INT32;
58856   }else if( zP4==0 ){
58857     pOp->p4.p = 0;
58858     pOp->p4type = P4_NOTUSED;
58859   }else if( n==P4_KEYINFO ){
58860     KeyInfo *pKeyInfo;
58861     int nField, nByte;
58862
58863     nField = ((KeyInfo*)zP4)->nField;
58864     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
58865     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
58866     pOp->p4.pKeyInfo = pKeyInfo;
58867     if( pKeyInfo ){
58868       u8 *aSortOrder;
58869       memcpy((char*)pKeyInfo, zP4, nByte - nField);
58870       aSortOrder = pKeyInfo->aSortOrder;
58871       if( aSortOrder ){
58872         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
58873         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
58874       }
58875       pOp->p4type = P4_KEYINFO;
58876     }else{
58877       p->db->mallocFailed = 1;
58878       pOp->p4type = P4_NOTUSED;
58879     }
58880   }else if( n==P4_KEYINFO_HANDOFF ){
58881     pOp->p4.p = (void*)zP4;
58882     pOp->p4type = P4_KEYINFO;
58883   }else if( n==P4_VTAB ){
58884     pOp->p4.p = (void*)zP4;
58885     pOp->p4type = P4_VTAB;
58886     sqlite3VtabLock((VTable *)zP4);
58887     assert( ((VTable *)zP4)->db==p->db );
58888   }else if( n<0 ){
58889     pOp->p4.p = (void*)zP4;
58890     pOp->p4type = (signed char)n;
58891   }else{
58892     if( n==0 ) n = sqlite3Strlen30(zP4);
58893     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
58894     pOp->p4type = P4_DYNAMIC;
58895   }
58896 }
58897
58898 #ifndef NDEBUG
58899 /*
58900 ** Change the comment on the most recently coded instruction.  Or
58901 ** insert a No-op and add the comment to that new instruction.  This
58902 ** makes the code easier to read during debugging.  None of this happens
58903 ** in a production build.
58904 */
58905 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
58906   assert( p->nOp>0 || p->aOp==0 );
58907   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58908   if( p->nOp ){
58909     assert( p->aOp );
58910     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
58911     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
58912   }
58913 }
58914 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
58915   va_list ap;
58916   if( p ){
58917     va_start(ap, zFormat);
58918     vdbeVComment(p, zFormat, ap);
58919     va_end(ap);
58920   }
58921 }
58922 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
58923   va_list ap;
58924   if( p ){
58925     sqlite3VdbeAddOp0(p, OP_Noop);
58926     va_start(ap, zFormat);
58927     vdbeVComment(p, zFormat, ap);
58928     va_end(ap);
58929   }
58930 }
58931 #endif  /* NDEBUG */
58932
58933 /*
58934 ** Return the opcode for a given address.  If the address is -1, then
58935 ** return the most recently inserted opcode.
58936 **
58937 ** If a memory allocation error has occurred prior to the calling of this
58938 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
58939 ** is readable but not writable, though it is cast to a writable value.
58940 ** The return of a dummy opcode allows the call to continue functioning
58941 ** after a OOM fault without having to check to see if the return from 
58942 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
58943 ** dummy will never be written to.  This is verified by code inspection and
58944 ** by running with Valgrind.
58945 **
58946 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
58947 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
58948 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
58949 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
58950 ** having to double-check to make sure that the result is non-negative. But
58951 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
58952 ** check the value of p->nOp-1 before continuing.
58953 */
58954 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
58955   /* C89 specifies that the constant "dummy" will be initialized to all
58956   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
58957   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
58958   assert( p->magic==VDBE_MAGIC_INIT );
58959   if( addr<0 ){
58960 #ifdef SQLITE_OMIT_TRACE
58961     if( p->nOp==0 ) return (VdbeOp*)&dummy;
58962 #endif
58963     addr = p->nOp - 1;
58964   }
58965   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
58966   if( p->db->mallocFailed ){
58967     return (VdbeOp*)&dummy;
58968   }else{
58969     return &p->aOp[addr];
58970   }
58971 }
58972
58973 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
58974      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58975 /*
58976 ** Compute a string that describes the P4 parameter for an opcode.
58977 ** Use zTemp for any required temporary buffer space.
58978 */
58979 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
58980   char *zP4 = zTemp;
58981   assert( nTemp>=20 );
58982   switch( pOp->p4type ){
58983     case P4_KEYINFO_STATIC:
58984     case P4_KEYINFO: {
58985       int i, j;
58986       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
58987       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
58988       i = sqlite3Strlen30(zTemp);
58989       for(j=0; j<pKeyInfo->nField; j++){
58990         CollSeq *pColl = pKeyInfo->aColl[j];
58991         if( pColl ){
58992           int n = sqlite3Strlen30(pColl->zName);
58993           if( i+n>nTemp-6 ){
58994             memcpy(&zTemp[i],",...",4);
58995             break;
58996           }
58997           zTemp[i++] = ',';
58998           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
58999             zTemp[i++] = '-';
59000           }
59001           memcpy(&zTemp[i], pColl->zName,n+1);
59002           i += n;
59003         }else if( i+4<nTemp-6 ){
59004           memcpy(&zTemp[i],",nil",4);
59005           i += 4;
59006         }
59007       }
59008       zTemp[i++] = ')';
59009       zTemp[i] = 0;
59010       assert( i<nTemp );
59011       break;
59012     }
59013     case P4_COLLSEQ: {
59014       CollSeq *pColl = pOp->p4.pColl;
59015       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59016       break;
59017     }
59018     case P4_FUNCDEF: {
59019       FuncDef *pDef = pOp->p4.pFunc;
59020       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59021       break;
59022     }
59023     case P4_INT64: {
59024       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59025       break;
59026     }
59027     case P4_INT32: {
59028       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59029       break;
59030     }
59031     case P4_REAL: {
59032       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59033       break;
59034     }
59035     case P4_MEM: {
59036       Mem *pMem = pOp->p4.pMem;
59037       if( pMem->flags & MEM_Str ){
59038         zP4 = pMem->z;
59039       }else if( pMem->flags & MEM_Int ){
59040         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59041       }else if( pMem->flags & MEM_Real ){
59042         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59043       }else if( pMem->flags & MEM_Null ){
59044         sqlite3_snprintf(nTemp, zTemp, "NULL");
59045       }else{
59046         assert( pMem->flags & MEM_Blob );
59047         zP4 = "(blob)";
59048       }
59049       break;
59050     }
59051 #ifndef SQLITE_OMIT_VIRTUALTABLE
59052     case P4_VTAB: {
59053       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59054       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59055       break;
59056     }
59057 #endif
59058     case P4_INTARRAY: {
59059       sqlite3_snprintf(nTemp, zTemp, "intarray");
59060       break;
59061     }
59062     case P4_SUBPROGRAM: {
59063       sqlite3_snprintf(nTemp, zTemp, "program");
59064       break;
59065     }
59066     case P4_ADVANCE: {
59067       zTemp[0] = 0;
59068       break;
59069     }
59070     default: {
59071       zP4 = pOp->p4.z;
59072       if( zP4==0 ){
59073         zP4 = zTemp;
59074         zTemp[0] = 0;
59075       }
59076     }
59077   }
59078   assert( zP4!=0 );
59079   return zP4;
59080 }
59081 #endif
59082
59083 /*
59084 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59085 **
59086 ** The prepared statements need to know in advance the complete set of
59087 ** attached databases that will be use.  A mask of these databases
59088 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
59089 ** p->btreeMask of databases that will require a lock.
59090 */
59091 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59092   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59093   assert( i<(int)sizeof(p->btreeMask)*8 );
59094   p->btreeMask |= ((yDbMask)1)<<i;
59095   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59096     p->lockMask |= ((yDbMask)1)<<i;
59097   }
59098 }
59099
59100 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59101 /*
59102 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59103 ** this routine obtains the mutex associated with each BtShared structure
59104 ** that may be accessed by the VM passed as an argument. In doing so it also
59105 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59106 ** that the correct busy-handler callback is invoked if required.
59107 **
59108 ** If SQLite is not threadsafe but does support shared-cache mode, then
59109 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59110 ** of all of BtShared structures accessible via the database handle 
59111 ** associated with the VM.
59112 **
59113 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59114 ** function is a no-op.
59115 **
59116 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
59117 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
59118 ** corresponding to btrees that use shared cache.  Then the runtime of
59119 ** this routine is N*N.  But as N is rarely more than 1, this should not
59120 ** be a problem.
59121 */
59122 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59123   int i;
59124   yDbMask mask;
59125   sqlite3 *db;
59126   Db *aDb;
59127   int nDb;
59128   if( p->lockMask==0 ) return;  /* The common case */
59129   db = p->db;
59130   aDb = db->aDb;
59131   nDb = db->nDb;
59132   for(i=0, mask=1; i<nDb; i++, mask += mask){
59133     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59134       sqlite3BtreeEnter(aDb[i].pBt);
59135     }
59136   }
59137 }
59138 #endif
59139
59140 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59141 /*
59142 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59143 */
59144 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59145   int i;
59146   yDbMask mask;
59147   sqlite3 *db;
59148   Db *aDb;
59149   int nDb;
59150   if( p->lockMask==0 ) return;  /* The common case */
59151   db = p->db;
59152   aDb = db->aDb;
59153   nDb = db->nDb;
59154   for(i=0, mask=1; i<nDb; i++, mask += mask){
59155     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59156       sqlite3BtreeLeave(aDb[i].pBt);
59157     }
59158   }
59159 }
59160 #endif
59161
59162 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59163 /*
59164 ** Print a single opcode.  This routine is used for debugging only.
59165 */
59166 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59167   char *zP4;
59168   char zPtr[50];
59169   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59170   if( pOut==0 ) pOut = stdout;
59171   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59172   fprintf(pOut, zFormat1, pc, 
59173       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59174 #ifdef SQLITE_DEBUG
59175       pOp->zComment ? pOp->zComment : ""
59176 #else
59177       ""
59178 #endif
59179   );
59180   fflush(pOut);
59181 }
59182 #endif
59183
59184 /*
59185 ** Release an array of N Mem elements
59186 */
59187 static void releaseMemArray(Mem *p, int N){
59188   if( p && N ){
59189     Mem *pEnd;
59190     sqlite3 *db = p->db;
59191     u8 malloc_failed = db->mallocFailed;
59192     if( db->pnBytesFreed ){
59193       for(pEnd=&p[N]; p<pEnd; p++){
59194         sqlite3DbFree(db, p->zMalloc);
59195       }
59196       return;
59197     }
59198     for(pEnd=&p[N]; p<pEnd; p++){
59199       assert( (&p[1])==pEnd || p[0].db==p[1].db );
59200
59201       /* This block is really an inlined version of sqlite3VdbeMemRelease()
59202       ** that takes advantage of the fact that the memory cell value is 
59203       ** being set to NULL after releasing any dynamic resources.
59204       **
59205       ** The justification for duplicating code is that according to 
59206       ** callgrind, this causes a certain test case to hit the CPU 4.7 
59207       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
59208       ** sqlite3MemRelease() were called from here. With -O2, this jumps
59209       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
59210       ** with no indexes using a single prepared INSERT statement, bind() 
59211       ** and reset(). Inserts are grouped into a transaction.
59212       */
59213       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59214         sqlite3VdbeMemRelease(p);
59215       }else if( p->zMalloc ){
59216         sqlite3DbFree(db, p->zMalloc);
59217         p->zMalloc = 0;
59218       }
59219
59220       p->flags = MEM_Invalid;
59221     }
59222     db->mallocFailed = malloc_failed;
59223   }
59224 }
59225
59226 /*
59227 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59228 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59229 */
59230 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59231   int i;
59232   Mem *aMem = VdbeFrameMem(p);
59233   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59234   for(i=0; i<p->nChildCsr; i++){
59235     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59236   }
59237   releaseMemArray(aMem, p->nChildMem);
59238   sqlite3DbFree(p->v->db, p);
59239 }
59240
59241 #ifndef SQLITE_OMIT_EXPLAIN
59242 /*
59243 ** Give a listing of the program in the virtual machine.
59244 **
59245 ** The interface is the same as sqlite3VdbeExec().  But instead of
59246 ** running the code, it invokes the callback once for each instruction.
59247 ** This feature is used to implement "EXPLAIN".
59248 **
59249 ** When p->explain==1, each instruction is listed.  When
59250 ** p->explain==2, only OP_Explain instructions are listed and these
59251 ** are shown in a different format.  p->explain==2 is used to implement
59252 ** EXPLAIN QUERY PLAN.
59253 **
59254 ** When p->explain==1, first the main program is listed, then each of
59255 ** the trigger subprograms are listed one by one.
59256 */
59257 SQLITE_PRIVATE int sqlite3VdbeList(
59258   Vdbe *p                   /* The VDBE */
59259 ){
59260   int nRow;                            /* Stop when row count reaches this */
59261   int nSub = 0;                        /* Number of sub-vdbes seen so far */
59262   SubProgram **apSub = 0;              /* Array of sub-vdbes */
59263   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
59264   sqlite3 *db = p->db;                 /* The database connection */
59265   int i;                               /* Loop counter */
59266   int rc = SQLITE_OK;                  /* Return code */
59267   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
59268
59269   assert( p->explain );
59270   assert( p->magic==VDBE_MAGIC_RUN );
59271   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59272
59273   /* Even though this opcode does not use dynamic strings for
59274   ** the result, result columns may become dynamic if the user calls
59275   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59276   */
59277   releaseMemArray(pMem, 8);
59278   p->pResultSet = 0;
59279
59280   if( p->rc==SQLITE_NOMEM ){
59281     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59282     ** sqlite3_column_text16() failed.  */
59283     db->mallocFailed = 1;
59284     return SQLITE_ERROR;
59285   }
59286
59287   /* When the number of output rows reaches nRow, that means the
59288   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59289   ** nRow is the sum of the number of rows in the main program, plus
59290   ** the sum of the number of rows in all trigger subprograms encountered
59291   ** so far.  The nRow value will increase as new trigger subprograms are
59292   ** encountered, but p->pc will eventually catch up to nRow.
59293   */
59294   nRow = p->nOp;
59295   if( p->explain==1 ){
59296     /* The first 8 memory cells are used for the result set.  So we will
59297     ** commandeer the 9th cell to use as storage for an array of pointers
59298     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
59299     ** cells.  */
59300     assert( p->nMem>9 );
59301     pSub = &p->aMem[9];
59302     if( pSub->flags&MEM_Blob ){
59303       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
59304       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59305       nSub = pSub->n/sizeof(Vdbe*);
59306       apSub = (SubProgram **)pSub->z;
59307     }
59308     for(i=0; i<nSub; i++){
59309       nRow += apSub[i]->nOp;
59310     }
59311   }
59312
59313   do{
59314     i = p->pc++;
59315   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59316   if( i>=nRow ){
59317     p->rc = SQLITE_OK;
59318     rc = SQLITE_DONE;
59319   }else if( db->u1.isInterrupted ){
59320     p->rc = SQLITE_INTERRUPT;
59321     rc = SQLITE_ERROR;
59322     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59323   }else{
59324     char *z;
59325     Op *pOp;
59326     if( i<p->nOp ){
59327       /* The output line number is small enough that we are still in the
59328       ** main program. */
59329       pOp = &p->aOp[i];
59330     }else{
59331       /* We are currently listing subprograms.  Figure out which one and
59332       ** pick up the appropriate opcode. */
59333       int j;
59334       i -= p->nOp;
59335       for(j=0; i>=apSub[j]->nOp; j++){
59336         i -= apSub[j]->nOp;
59337       }
59338       pOp = &apSub[j]->aOp[i];
59339     }
59340     if( p->explain==1 ){
59341       pMem->flags = MEM_Int;
59342       pMem->type = SQLITE_INTEGER;
59343       pMem->u.i = i;                                /* Program counter */
59344       pMem++;
59345   
59346       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59347       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
59348       assert( pMem->z!=0 );
59349       pMem->n = sqlite3Strlen30(pMem->z);
59350       pMem->type = SQLITE_TEXT;
59351       pMem->enc = SQLITE_UTF8;
59352       pMem++;
59353
59354       /* When an OP_Program opcode is encounter (the only opcode that has
59355       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59356       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59357       ** has not already been seen.
59358       */
59359       if( pOp->p4type==P4_SUBPROGRAM ){
59360         int nByte = (nSub+1)*sizeof(SubProgram*);
59361         int j;
59362         for(j=0; j<nSub; j++){
59363           if( apSub[j]==pOp->p4.pProgram ) break;
59364         }
59365         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
59366           apSub = (SubProgram **)pSub->z;
59367           apSub[nSub++] = pOp->p4.pProgram;
59368           pSub->flags |= MEM_Blob;
59369           pSub->n = nSub*sizeof(SubProgram*);
59370         }
59371       }
59372     }
59373
59374     pMem->flags = MEM_Int;
59375     pMem->u.i = pOp->p1;                          /* P1 */
59376     pMem->type = SQLITE_INTEGER;
59377     pMem++;
59378
59379     pMem->flags = MEM_Int;
59380     pMem->u.i = pOp->p2;                          /* P2 */
59381     pMem->type = SQLITE_INTEGER;
59382     pMem++;
59383
59384     pMem->flags = MEM_Int;
59385     pMem->u.i = pOp->p3;                          /* P3 */
59386     pMem->type = SQLITE_INTEGER;
59387     pMem++;
59388
59389     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
59390       assert( p->db->mallocFailed );
59391       return SQLITE_ERROR;
59392     }
59393     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59394     z = displayP4(pOp, pMem->z, 32);
59395     if( z!=pMem->z ){
59396       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59397     }else{
59398       assert( pMem->z!=0 );
59399       pMem->n = sqlite3Strlen30(pMem->z);
59400       pMem->enc = SQLITE_UTF8;
59401     }
59402     pMem->type = SQLITE_TEXT;
59403     pMem++;
59404
59405     if( p->explain==1 ){
59406       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
59407         assert( p->db->mallocFailed );
59408         return SQLITE_ERROR;
59409       }
59410       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59411       pMem->n = 2;
59412       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
59413       pMem->type = SQLITE_TEXT;
59414       pMem->enc = SQLITE_UTF8;
59415       pMem++;
59416   
59417 #ifdef SQLITE_DEBUG
59418       if( pOp->zComment ){
59419         pMem->flags = MEM_Str|MEM_Term;
59420         pMem->z = pOp->zComment;
59421         pMem->n = sqlite3Strlen30(pMem->z);
59422         pMem->enc = SQLITE_UTF8;
59423         pMem->type = SQLITE_TEXT;
59424       }else
59425 #endif
59426       {
59427         pMem->flags = MEM_Null;                       /* Comment */
59428         pMem->type = SQLITE_NULL;
59429       }
59430     }
59431
59432     p->nResColumn = 8 - 4*(p->explain-1);
59433     p->pResultSet = &p->aMem[1];
59434     p->rc = SQLITE_OK;
59435     rc = SQLITE_ROW;
59436   }
59437   return rc;
59438 }
59439 #endif /* SQLITE_OMIT_EXPLAIN */
59440
59441 #ifdef SQLITE_DEBUG
59442 /*
59443 ** Print the SQL that was used to generate a VDBE program.
59444 */
59445 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
59446   int nOp = p->nOp;
59447   VdbeOp *pOp;
59448   if( nOp<1 ) return;
59449   pOp = &p->aOp[0];
59450   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59451     const char *z = pOp->p4.z;
59452     while( sqlite3Isspace(*z) ) z++;
59453     printf("SQL: [%s]\n", z);
59454   }
59455 }
59456 #endif
59457
59458 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
59459 /*
59460 ** Print an IOTRACE message showing SQL content.
59461 */
59462 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
59463   int nOp = p->nOp;
59464   VdbeOp *pOp;
59465   if( sqlite3IoTrace==0 ) return;
59466   if( nOp<1 ) return;
59467   pOp = &p->aOp[0];
59468   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59469     int i, j;
59470     char z[1000];
59471     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
59472     for(i=0; sqlite3Isspace(z[i]); i++){}
59473     for(j=0; z[i]; i++){
59474       if( sqlite3Isspace(z[i]) ){
59475         if( z[i-1]!=' ' ){
59476           z[j++] = ' ';
59477         }
59478       }else{
59479         z[j++] = z[i];
59480       }
59481     }
59482     z[j] = 0;
59483     sqlite3IoTrace("SQL %s\n", z);
59484   }
59485 }
59486 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
59487
59488 /*
59489 ** Allocate space from a fixed size buffer and return a pointer to
59490 ** that space.  If insufficient space is available, return NULL.
59491 **
59492 ** The pBuf parameter is the initial value of a pointer which will
59493 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
59494 ** NULL, it means that memory space has already been allocated and that
59495 ** this routine should not allocate any new memory.  When pBuf is not
59496 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
59497 ** is NULL.
59498 **
59499 ** nByte is the number of bytes of space needed.
59500 **
59501 ** *ppFrom points to available space and pEnd points to the end of the
59502 ** available space.  When space is allocated, *ppFrom is advanced past
59503 ** the end of the allocated space.
59504 **
59505 ** *pnByte is a counter of the number of bytes of space that have failed
59506 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
59507 ** request, then increment *pnByte by the amount of the request.
59508 */
59509 static void *allocSpace(
59510   void *pBuf,          /* Where return pointer will be stored */
59511   int nByte,           /* Number of bytes to allocate */
59512   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
59513   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
59514   int *pnByte          /* If allocation cannot be made, increment *pnByte */
59515 ){
59516   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
59517   if( pBuf ) return pBuf;
59518   nByte = ROUND8(nByte);
59519   if( &(*ppFrom)[nByte] <= pEnd ){
59520     pBuf = (void*)*ppFrom;
59521     *ppFrom += nByte;
59522   }else{
59523     *pnByte += nByte;
59524   }
59525   return pBuf;
59526 }
59527
59528 /*
59529 ** Rewind the VDBE back to the beginning in preparation for
59530 ** running it.
59531 */
59532 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
59533 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
59534   int i;
59535 #endif
59536   assert( p!=0 );
59537   assert( p->magic==VDBE_MAGIC_INIT );
59538
59539   /* There should be at least one opcode.
59540   */
59541   assert( p->nOp>0 );
59542
59543   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
59544   p->magic = VDBE_MAGIC_RUN;
59545
59546 #ifdef SQLITE_DEBUG
59547   for(i=1; i<p->nMem; i++){
59548     assert( p->aMem[i].db==p->db );
59549   }
59550 #endif
59551   p->pc = -1;
59552   p->rc = SQLITE_OK;
59553   p->errorAction = OE_Abort;
59554   p->magic = VDBE_MAGIC_RUN;
59555   p->nChange = 0;
59556   p->cacheCtr = 1;
59557   p->minWriteFileFormat = 255;
59558   p->iStatement = 0;
59559   p->nFkConstraint = 0;
59560 #ifdef VDBE_PROFILE
59561   for(i=0; i<p->nOp; i++){
59562     p->aOp[i].cnt = 0;
59563     p->aOp[i].cycles = 0;
59564   }
59565 #endif
59566 }
59567
59568 /*
59569 ** Prepare a virtual machine for execution for the first time after
59570 ** creating the virtual machine.  This involves things such
59571 ** as allocating stack space and initializing the program counter.
59572 ** After the VDBE has be prepped, it can be executed by one or more
59573 ** calls to sqlite3VdbeExec().  
59574 **
59575 ** This function may be called exact once on a each virtual machine.
59576 ** After this routine is called the VM has been "packaged" and is ready
59577 ** to run.  After this routine is called, futher calls to 
59578 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
59579 ** the Vdbe from the Parse object that helped generate it so that the
59580 ** the Vdbe becomes an independent entity and the Parse object can be
59581 ** destroyed.
59582 **
59583 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
59584 ** to its initial state after it has been run.
59585 */
59586 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
59587   Vdbe *p,                       /* The VDBE */
59588   Parse *pParse                  /* Parsing context */
59589 ){
59590   sqlite3 *db;                   /* The database connection */
59591   int nVar;                      /* Number of parameters */
59592   int nMem;                      /* Number of VM memory registers */
59593   int nCursor;                   /* Number of cursors required */
59594   int nArg;                      /* Number of arguments in subprograms */
59595   int nOnce;                     /* Number of OP_Once instructions */
59596   int n;                         /* Loop counter */
59597   u8 *zCsr;                      /* Memory available for allocation */
59598   u8 *zEnd;                      /* First byte past allocated memory */
59599   int nByte;                     /* How much extra memory is needed */
59600
59601   assert( p!=0 );
59602   assert( p->nOp>0 );
59603   assert( pParse!=0 );
59604   assert( p->magic==VDBE_MAGIC_INIT );
59605   db = p->db;
59606   assert( db->mallocFailed==0 );
59607   nVar = pParse->nVar;
59608   nMem = pParse->nMem;
59609   nCursor = pParse->nTab;
59610   nArg = pParse->nMaxArg;
59611   nOnce = pParse->nOnce;
59612   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
59613   
59614   /* For each cursor required, also allocate a memory cell. Memory
59615   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
59616   ** the vdbe program. Instead they are used to allocate space for
59617   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
59618   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
59619   ** stores the blob of memory associated with cursor 1, etc.
59620   **
59621   ** See also: allocateCursor().
59622   */
59623   nMem += nCursor;
59624
59625   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
59626   ** an array to marshal SQL function arguments in.
59627   */
59628   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
59629   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
59630
59631   resolveP2Values(p, &nArg);
59632   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
59633   if( pParse->explain && nMem<10 ){
59634     nMem = 10;
59635   }
59636   memset(zCsr, 0, zEnd-zCsr);
59637   zCsr += (zCsr - (u8*)0)&7;
59638   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
59639   p->expired = 0;
59640
59641   /* Memory for registers, parameters, cursor, etc, is allocated in two
59642   ** passes.  On the first pass, we try to reuse unused space at the 
59643   ** end of the opcode array.  If we are unable to satisfy all memory
59644   ** requirements by reusing the opcode array tail, then the second
59645   ** pass will fill in the rest using a fresh allocation.  
59646   **
59647   ** This two-pass approach that reuses as much memory as possible from
59648   ** the leftover space at the end of the opcode array can significantly
59649   ** reduce the amount of memory held by a prepared statement.
59650   */
59651   do {
59652     nByte = 0;
59653     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
59654     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
59655     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
59656     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
59657     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
59658                           &zCsr, zEnd, &nByte);
59659     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
59660     if( nByte ){
59661       p->pFree = sqlite3DbMallocZero(db, nByte);
59662     }
59663     zCsr = p->pFree;
59664     zEnd = &zCsr[nByte];
59665   }while( nByte && !db->mallocFailed );
59666
59667   p->nCursor = (u16)nCursor;
59668   p->nOnceFlag = nOnce;
59669   if( p->aVar ){
59670     p->nVar = (ynVar)nVar;
59671     for(n=0; n<nVar; n++){
59672       p->aVar[n].flags = MEM_Null;
59673       p->aVar[n].db = db;
59674     }
59675   }
59676   if( p->azVar ){
59677     p->nzVar = pParse->nzVar;
59678     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
59679     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
59680   }
59681   if( p->aMem ){
59682     p->aMem--;                      /* aMem[] goes from 1..nMem */
59683     p->nMem = nMem;                 /*       not from 0..nMem-1 */
59684     for(n=1; n<=nMem; n++){
59685       p->aMem[n].flags = MEM_Invalid;
59686       p->aMem[n].db = db;
59687     }
59688   }
59689   p->explain = pParse->explain;
59690   sqlite3VdbeRewind(p);
59691 }
59692
59693 /*
59694 ** Close a VDBE cursor and release all the resources that cursor 
59695 ** happens to hold.
59696 */
59697 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
59698   if( pCx==0 ){
59699     return;
59700   }
59701   sqlite3VdbeSorterClose(p->db, pCx);
59702   if( pCx->pBt ){
59703     sqlite3BtreeClose(pCx->pBt);
59704     /* The pCx->pCursor will be close automatically, if it exists, by
59705     ** the call above. */
59706   }else if( pCx->pCursor ){
59707     sqlite3BtreeCloseCursor(pCx->pCursor);
59708   }
59709 #ifndef SQLITE_OMIT_VIRTUALTABLE
59710   if( pCx->pVtabCursor ){
59711     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
59712     const sqlite3_module *pModule = pCx->pModule;
59713     p->inVtabMethod = 1;
59714     pModule->xClose(pVtabCursor);
59715     p->inVtabMethod = 0;
59716   }
59717 #endif
59718 }
59719
59720 /*
59721 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
59722 ** is used, for example, when a trigger sub-program is halted to restore
59723 ** control to the main program.
59724 */
59725 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
59726   Vdbe *v = pFrame->v;
59727   v->aOnceFlag = pFrame->aOnceFlag;
59728   v->nOnceFlag = pFrame->nOnceFlag;
59729   v->aOp = pFrame->aOp;
59730   v->nOp = pFrame->nOp;
59731   v->aMem = pFrame->aMem;
59732   v->nMem = pFrame->nMem;
59733   v->apCsr = pFrame->apCsr;
59734   v->nCursor = pFrame->nCursor;
59735   v->db->lastRowid = pFrame->lastRowid;
59736   v->nChange = pFrame->nChange;
59737   return pFrame->pc;
59738 }
59739
59740 /*
59741 ** Close all cursors.
59742 **
59743 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
59744 ** cell array. This is necessary as the memory cell array may contain
59745 ** pointers to VdbeFrame objects, which may in turn contain pointers to
59746 ** open cursors.
59747 */
59748 static void closeAllCursors(Vdbe *p){
59749   if( p->pFrame ){
59750     VdbeFrame *pFrame;
59751     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
59752     sqlite3VdbeFrameRestore(pFrame);
59753   }
59754   p->pFrame = 0;
59755   p->nFrame = 0;
59756
59757   if( p->apCsr ){
59758     int i;
59759     for(i=0; i<p->nCursor; i++){
59760       VdbeCursor *pC = p->apCsr[i];
59761       if( pC ){
59762         sqlite3VdbeFreeCursor(p, pC);
59763         p->apCsr[i] = 0;
59764       }
59765     }
59766   }
59767   if( p->aMem ){
59768     releaseMemArray(&p->aMem[1], p->nMem);
59769   }
59770   while( p->pDelFrame ){
59771     VdbeFrame *pDel = p->pDelFrame;
59772     p->pDelFrame = pDel->pParent;
59773     sqlite3VdbeFrameDelete(pDel);
59774   }
59775 }
59776
59777 /*
59778 ** Clean up the VM after execution.
59779 **
59780 ** This routine will automatically close any cursors, lists, and/or
59781 ** sorters that were left open.  It also deletes the values of
59782 ** variables in the aVar[] array.
59783 */
59784 static void Cleanup(Vdbe *p){
59785   sqlite3 *db = p->db;
59786
59787 #ifdef SQLITE_DEBUG
59788   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
59789   ** Vdbe.aMem[] arrays have already been cleaned up.  */
59790   int i;
59791   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
59792   if( p->aMem ){
59793     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
59794   }
59795 #endif
59796
59797   sqlite3DbFree(db, p->zErrMsg);
59798   p->zErrMsg = 0;
59799   p->pResultSet = 0;
59800 }
59801
59802 /*
59803 ** Set the number of result columns that will be returned by this SQL
59804 ** statement. This is now set at compile time, rather than during
59805 ** execution of the vdbe program so that sqlite3_column_count() can
59806 ** be called on an SQL statement before sqlite3_step().
59807 */
59808 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
59809   Mem *pColName;
59810   int n;
59811   sqlite3 *db = p->db;
59812
59813   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59814   sqlite3DbFree(db, p->aColName);
59815   n = nResColumn*COLNAME_N;
59816   p->nResColumn = (u16)nResColumn;
59817   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
59818   if( p->aColName==0 ) return;
59819   while( n-- > 0 ){
59820     pColName->flags = MEM_Null;
59821     pColName->db = p->db;
59822     pColName++;
59823   }
59824 }
59825
59826 /*
59827 ** Set the name of the idx'th column to be returned by the SQL statement.
59828 ** zName must be a pointer to a nul terminated string.
59829 **
59830 ** This call must be made after a call to sqlite3VdbeSetNumCols().
59831 **
59832 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
59833 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
59834 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
59835 */
59836 SQLITE_PRIVATE int sqlite3VdbeSetColName(
59837   Vdbe *p,                         /* Vdbe being configured */
59838   int idx,                         /* Index of column zName applies to */
59839   int var,                         /* One of the COLNAME_* constants */
59840   const char *zName,               /* Pointer to buffer containing name */
59841   void (*xDel)(void*)              /* Memory management strategy for zName */
59842 ){
59843   int rc;
59844   Mem *pColName;
59845   assert( idx<p->nResColumn );
59846   assert( var<COLNAME_N );
59847   if( p->db->mallocFailed ){
59848     assert( !zName || xDel!=SQLITE_DYNAMIC );
59849     return SQLITE_NOMEM;
59850   }
59851   assert( p->aColName!=0 );
59852   pColName = &(p->aColName[idx+var*p->nResColumn]);
59853   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
59854   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
59855   return rc;
59856 }
59857
59858 /*
59859 ** A read or write transaction may or may not be active on database handle
59860 ** db. If a transaction is active, commit it. If there is a
59861 ** write-transaction spanning more than one database file, this routine
59862 ** takes care of the master journal trickery.
59863 */
59864 static int vdbeCommit(sqlite3 *db, Vdbe *p){
59865   int i;
59866   int nTrans = 0;  /* Number of databases with an active write-transaction */
59867   int rc = SQLITE_OK;
59868   int needXcommit = 0;
59869
59870 #ifdef SQLITE_OMIT_VIRTUALTABLE
59871   /* With this option, sqlite3VtabSync() is defined to be simply 
59872   ** SQLITE_OK so p is not used. 
59873   */
59874   UNUSED_PARAMETER(p);
59875 #endif
59876
59877   /* Before doing anything else, call the xSync() callback for any
59878   ** virtual module tables written in this transaction. This has to
59879   ** be done before determining whether a master journal file is 
59880   ** required, as an xSync() callback may add an attached database
59881   ** to the transaction.
59882   */
59883   rc = sqlite3VtabSync(db, &p->zErrMsg);
59884
59885   /* This loop determines (a) if the commit hook should be invoked and
59886   ** (b) how many database files have open write transactions, not 
59887   ** including the temp database. (b) is important because if more than 
59888   ** one database file has an open write transaction, a master journal
59889   ** file is required for an atomic commit.
59890   */ 
59891   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
59892     Btree *pBt = db->aDb[i].pBt;
59893     if( sqlite3BtreeIsInTrans(pBt) ){
59894       needXcommit = 1;
59895       if( i!=1 ) nTrans++;
59896       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
59897     }
59898   }
59899   if( rc!=SQLITE_OK ){
59900     return rc;
59901   }
59902
59903   /* If there are any write-transactions at all, invoke the commit hook */
59904   if( needXcommit && db->xCommitCallback ){
59905     rc = db->xCommitCallback(db->pCommitArg);
59906     if( rc ){
59907       return SQLITE_CONSTRAINT;
59908     }
59909   }
59910
59911   /* The simple case - no more than one database file (not counting the
59912   ** TEMP database) has a transaction active.   There is no need for the
59913   ** master-journal.
59914   **
59915   ** If the return value of sqlite3BtreeGetFilename() is a zero length
59916   ** string, it means the main database is :memory: or a temp file.  In 
59917   ** that case we do not support atomic multi-file commits, so use the 
59918   ** simple case then too.
59919   */
59920   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
59921    || nTrans<=1
59922   ){
59923     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59924       Btree *pBt = db->aDb[i].pBt;
59925       if( pBt ){
59926         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
59927       }
59928     }
59929
59930     /* Do the commit only if all databases successfully complete phase 1. 
59931     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
59932     ** IO error while deleting or truncating a journal file. It is unlikely,
59933     ** but could happen. In this case abandon processing and return the error.
59934     */
59935     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59936       Btree *pBt = db->aDb[i].pBt;
59937       if( pBt ){
59938         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
59939       }
59940     }
59941     if( rc==SQLITE_OK ){
59942       sqlite3VtabCommit(db);
59943     }
59944   }
59945
59946   /* The complex case - There is a multi-file write-transaction active.
59947   ** This requires a master journal file to ensure the transaction is
59948   ** committed atomicly.
59949   */
59950 #ifndef SQLITE_OMIT_DISKIO
59951   else{
59952     sqlite3_vfs *pVfs = db->pVfs;
59953     int needSync = 0;
59954     char *zMaster = 0;   /* File-name for the master journal */
59955     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
59956     sqlite3_file *pMaster = 0;
59957     i64 offset = 0;
59958     int res;
59959     int retryCount = 0;
59960     int nMainFile;
59961
59962     /* Select a master journal file name */
59963     nMainFile = sqlite3Strlen30(zMainFile);
59964     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
59965     if( zMaster==0 ) return SQLITE_NOMEM;
59966     do {
59967       u32 iRandom;
59968       if( retryCount ){
59969         if( retryCount>100 ){
59970           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
59971           sqlite3OsDelete(pVfs, zMaster, 0);
59972           break;
59973         }else if( retryCount==1 ){
59974           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
59975         }
59976       }
59977       retryCount++;
59978       sqlite3_randomness(sizeof(iRandom), &iRandom);
59979       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
59980                                (iRandom>>8)&0xffffff, iRandom&0xff);
59981       /* The antipenultimate character of the master journal name must
59982       ** be "9" to avoid name collisions when using 8+3 filenames. */
59983       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
59984       sqlite3FileSuffix3(zMainFile, zMaster);
59985       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
59986     }while( rc==SQLITE_OK && res );
59987     if( rc==SQLITE_OK ){
59988       /* Open the master journal. */
59989       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
59990           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
59991           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
59992       );
59993     }
59994     if( rc!=SQLITE_OK ){
59995       sqlite3DbFree(db, zMaster);
59996       return rc;
59997     }
59998  
59999     /* Write the name of each database file in the transaction into the new
60000     ** master journal file. If an error occurs at this point close
60001     ** and delete the master journal file. All the individual journal files
60002     ** still have 'null' as the master journal pointer, so they will roll
60003     ** back independently if a failure occurs.
60004     */
60005     for(i=0; i<db->nDb; i++){
60006       Btree *pBt = db->aDb[i].pBt;
60007       if( sqlite3BtreeIsInTrans(pBt) ){
60008         char const *zFile = sqlite3BtreeGetJournalname(pBt);
60009         if( zFile==0 ){
60010           continue;  /* Ignore TEMP and :memory: databases */
60011         }
60012         assert( zFile[0]!=0 );
60013         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60014           needSync = 1;
60015         }
60016         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60017         offset += sqlite3Strlen30(zFile)+1;
60018         if( rc!=SQLITE_OK ){
60019           sqlite3OsCloseFree(pMaster);
60020           sqlite3OsDelete(pVfs, zMaster, 0);
60021           sqlite3DbFree(db, zMaster);
60022           return rc;
60023         }
60024       }
60025     }
60026
60027     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60028     ** flag is set this is not required.
60029     */
60030     if( needSync 
60031      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60032      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60033     ){
60034       sqlite3OsCloseFree(pMaster);
60035       sqlite3OsDelete(pVfs, zMaster, 0);
60036       sqlite3DbFree(db, zMaster);
60037       return rc;
60038     }
60039
60040     /* Sync all the db files involved in the transaction. The same call
60041     ** sets the master journal pointer in each individual journal. If
60042     ** an error occurs here, do not delete the master journal file.
60043     **
60044     ** If the error occurs during the first call to
60045     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60046     ** master journal file will be orphaned. But we cannot delete it,
60047     ** in case the master journal file name was written into the journal
60048     ** file before the failure occurred.
60049     */
60050     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
60051       Btree *pBt = db->aDb[i].pBt;
60052       if( pBt ){
60053         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60054       }
60055     }
60056     sqlite3OsCloseFree(pMaster);
60057     assert( rc!=SQLITE_BUSY );
60058     if( rc!=SQLITE_OK ){
60059       sqlite3DbFree(db, zMaster);
60060       return rc;
60061     }
60062
60063     /* Delete the master journal file. This commits the transaction. After
60064     ** doing this the directory is synced again before any individual
60065     ** transaction files are deleted.
60066     */
60067     rc = sqlite3OsDelete(pVfs, zMaster, 1);
60068     sqlite3DbFree(db, zMaster);
60069     zMaster = 0;
60070     if( rc ){
60071       return rc;
60072     }
60073
60074     /* All files and directories have already been synced, so the following
60075     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60076     ** deleting or truncating journals. If something goes wrong while
60077     ** this is happening we don't really care. The integrity of the
60078     ** transaction is already guaranteed, but some stray 'cold' journals
60079     ** may be lying around. Returning an error code won't help matters.
60080     */
60081     disable_simulated_io_errors();
60082     sqlite3BeginBenignMalloc();
60083     for(i=0; i<db->nDb; i++){ 
60084       Btree *pBt = db->aDb[i].pBt;
60085       if( pBt ){
60086         sqlite3BtreeCommitPhaseTwo(pBt, 1);
60087       }
60088     }
60089     sqlite3EndBenignMalloc();
60090     enable_simulated_io_errors();
60091
60092     sqlite3VtabCommit(db);
60093   }
60094 #endif
60095
60096   return rc;
60097 }
60098
60099 /* 
60100 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60101 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60102 ** currently active. An assertion fails if the two counts do not match.
60103 ** This is an internal self-check only - it is not an essential processing
60104 ** step.
60105 **
60106 ** This is a no-op if NDEBUG is defined.
60107 */
60108 #ifndef NDEBUG
60109 static void checkActiveVdbeCnt(sqlite3 *db){
60110   Vdbe *p;
60111   int cnt = 0;
60112   int nWrite = 0;
60113   p = db->pVdbe;
60114   while( p ){
60115     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60116       cnt++;
60117       if( p->readOnly==0 ) nWrite++;
60118     }
60119     p = p->pNext;
60120   }
60121   assert( cnt==db->activeVdbeCnt );
60122   assert( nWrite==db->writeVdbeCnt );
60123 }
60124 #else
60125 #define checkActiveVdbeCnt(x)
60126 #endif
60127
60128 /*
60129 ** If the Vdbe passed as the first argument opened a statement-transaction,
60130 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60131 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60132 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
60133 ** statement transaction is commtted.
60134 **
60135 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
60136 ** Otherwise SQLITE_OK.
60137 */
60138 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60139   sqlite3 *const db = p->db;
60140   int rc = SQLITE_OK;
60141
60142   /* If p->iStatement is greater than zero, then this Vdbe opened a 
60143   ** statement transaction that should be closed here. The only exception
60144   ** is that an IO error may have occured, causing an emergency rollback.
60145   ** In this case (db->nStatement==0), and there is nothing to do.
60146   */
60147   if( db->nStatement && p->iStatement ){
60148     int i;
60149     const int iSavepoint = p->iStatement-1;
60150
60151     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60152     assert( db->nStatement>0 );
60153     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60154
60155     for(i=0; i<db->nDb; i++){ 
60156       int rc2 = SQLITE_OK;
60157       Btree *pBt = db->aDb[i].pBt;
60158       if( pBt ){
60159         if( eOp==SAVEPOINT_ROLLBACK ){
60160           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60161         }
60162         if( rc2==SQLITE_OK ){
60163           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60164         }
60165         if( rc==SQLITE_OK ){
60166           rc = rc2;
60167         }
60168       }
60169     }
60170     db->nStatement--;
60171     p->iStatement = 0;
60172
60173     if( rc==SQLITE_OK ){
60174       if( eOp==SAVEPOINT_ROLLBACK ){
60175         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60176       }
60177       if( rc==SQLITE_OK ){
60178         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60179       }
60180     }
60181
60182     /* If the statement transaction is being rolled back, also restore the 
60183     ** database handles deferred constraint counter to the value it had when 
60184     ** the statement transaction was opened.  */
60185     if( eOp==SAVEPOINT_ROLLBACK ){
60186       db->nDeferredCons = p->nStmtDefCons;
60187     }
60188   }
60189   return rc;
60190 }
60191
60192 /*
60193 ** This function is called when a transaction opened by the database 
60194 ** handle associated with the VM passed as an argument is about to be 
60195 ** committed. If there are outstanding deferred foreign key constraint
60196 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60197 **
60198 ** If there are outstanding FK violations and this function returns 
60199 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
60200 ** an error message to it. Then return SQLITE_ERROR.
60201 */
60202 #ifndef SQLITE_OMIT_FOREIGN_KEY
60203 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60204   sqlite3 *db = p->db;
60205   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60206     p->rc = SQLITE_CONSTRAINT;
60207     p->errorAction = OE_Abort;
60208     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60209     return SQLITE_ERROR;
60210   }
60211   return SQLITE_OK;
60212 }
60213 #endif
60214
60215 /*
60216 ** This routine is called the when a VDBE tries to halt.  If the VDBE
60217 ** has made changes and is in autocommit mode, then commit those
60218 ** changes.  If a rollback is needed, then do the rollback.
60219 **
60220 ** This routine is the only way to move the state of a VM from
60221 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
60222 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60223 **
60224 ** Return an error code.  If the commit could not complete because of
60225 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
60226 ** means the close did not happen and needs to be repeated.
60227 */
60228 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60229   int rc;                         /* Used to store transient return codes */
60230   sqlite3 *db = p->db;
60231
60232   /* This function contains the logic that determines if a statement or
60233   ** transaction will be committed or rolled back as a result of the
60234   ** execution of this virtual machine. 
60235   **
60236   ** If any of the following errors occur:
60237   **
60238   **     SQLITE_NOMEM
60239   **     SQLITE_IOERR
60240   **     SQLITE_FULL
60241   **     SQLITE_INTERRUPT
60242   **
60243   ** Then the internal cache might have been left in an inconsistent
60244   ** state.  We need to rollback the statement transaction, if there is
60245   ** one, or the complete transaction if there is no statement transaction.
60246   */
60247
60248   if( p->db->mallocFailed ){
60249     p->rc = SQLITE_NOMEM;
60250   }
60251   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
60252   closeAllCursors(p);
60253   if( p->magic!=VDBE_MAGIC_RUN ){
60254     return SQLITE_OK;
60255   }
60256   checkActiveVdbeCnt(db);
60257
60258   /* No commit or rollback needed if the program never started */
60259   if( p->pc>=0 ){
60260     int mrc;   /* Primary error code from p->rc */
60261     int eStatementOp = 0;
60262     int isSpecialError;            /* Set to true if a 'special' error */
60263
60264     /* Lock all btrees used by the statement */
60265     sqlite3VdbeEnter(p);
60266
60267     /* Check for one of the special errors */
60268     mrc = p->rc & 0xff;
60269     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
60270     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60271                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60272     if( isSpecialError ){
60273       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
60274       ** no rollback is necessary. Otherwise, at least a savepoint 
60275       ** transaction must be rolled back to restore the database to a 
60276       ** consistent state.
60277       **
60278       ** Even if the statement is read-only, it is important to perform
60279       ** a statement or transaction rollback operation. If the error 
60280       ** occured while writing to the journal, sub-journal or database
60281       ** file as part of an effort to free up cache space (see function
60282       ** pagerStress() in pager.c), the rollback is required to restore 
60283       ** the pager to a consistent state.
60284       */
60285       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60286         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60287           eStatementOp = SAVEPOINT_ROLLBACK;
60288         }else{
60289           /* We are forced to roll back the active transaction. Before doing
60290           ** so, abort any other statements this handle currently has active.
60291           */
60292           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60293           sqlite3CloseSavepoints(db);
60294           db->autoCommit = 1;
60295         }
60296       }
60297     }
60298
60299     /* Check for immediate foreign key violations. */
60300     if( p->rc==SQLITE_OK ){
60301       sqlite3VdbeCheckFk(p, 0);
60302     }
60303   
60304     /* If the auto-commit flag is set and this is the only active writer 
60305     ** VM, then we do either a commit or rollback of the current transaction. 
60306     **
60307     ** Note: This block also runs if one of the special errors handled 
60308     ** above has occurred. 
60309     */
60310     if( !sqlite3VtabInSync(db) 
60311      && db->autoCommit 
60312      && db->writeVdbeCnt==(p->readOnly==0) 
60313     ){
60314       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60315         rc = sqlite3VdbeCheckFk(p, 1);
60316         if( rc!=SQLITE_OK ){
60317           if( NEVER(p->readOnly) ){
60318             sqlite3VdbeLeave(p);
60319             return SQLITE_ERROR;
60320           }
60321           rc = SQLITE_CONSTRAINT;
60322         }else{ 
60323           /* The auto-commit flag is true, the vdbe program was successful 
60324           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60325           ** key constraints to hold up the transaction. This means a commit 
60326           ** is required. */
60327           rc = vdbeCommit(db, p);
60328         }
60329         if( rc==SQLITE_BUSY && p->readOnly ){
60330           sqlite3VdbeLeave(p);
60331           return SQLITE_BUSY;
60332         }else if( rc!=SQLITE_OK ){
60333           p->rc = rc;
60334           sqlite3RollbackAll(db, SQLITE_OK);
60335         }else{
60336           db->nDeferredCons = 0;
60337           sqlite3CommitInternalChanges(db);
60338         }
60339       }else{
60340         sqlite3RollbackAll(db, SQLITE_OK);
60341       }
60342       db->nStatement = 0;
60343     }else if( eStatementOp==0 ){
60344       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60345         eStatementOp = SAVEPOINT_RELEASE;
60346       }else if( p->errorAction==OE_Abort ){
60347         eStatementOp = SAVEPOINT_ROLLBACK;
60348       }else{
60349         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60350         sqlite3CloseSavepoints(db);
60351         db->autoCommit = 1;
60352       }
60353     }
60354   
60355     /* If eStatementOp is non-zero, then a statement transaction needs to
60356     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60357     ** do so. If this operation returns an error, and the current statement
60358     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60359     ** current statement error code.
60360     */
60361     if( eStatementOp ){
60362       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60363       if( rc ){
60364         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
60365           p->rc = rc;
60366           sqlite3DbFree(db, p->zErrMsg);
60367           p->zErrMsg = 0;
60368         }
60369         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60370         sqlite3CloseSavepoints(db);
60371         db->autoCommit = 1;
60372       }
60373     }
60374   
60375     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60376     ** has been rolled back, update the database connection change-counter. 
60377     */
60378     if( p->changeCntOn ){
60379       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60380         sqlite3VdbeSetChanges(db, p->nChange);
60381       }else{
60382         sqlite3VdbeSetChanges(db, 0);
60383       }
60384       p->nChange = 0;
60385     }
60386
60387     /* Release the locks */
60388     sqlite3VdbeLeave(p);
60389   }
60390
60391   /* We have successfully halted and closed the VM.  Record this fact. */
60392   if( p->pc>=0 ){
60393     db->activeVdbeCnt--;
60394     if( !p->readOnly ){
60395       db->writeVdbeCnt--;
60396     }
60397     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
60398   }
60399   p->magic = VDBE_MAGIC_HALT;
60400   checkActiveVdbeCnt(db);
60401   if( p->db->mallocFailed ){
60402     p->rc = SQLITE_NOMEM;
60403   }
60404
60405   /* If the auto-commit flag is set to true, then any locks that were held
60406   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
60407   ** to invoke any required unlock-notify callbacks.
60408   */
60409   if( db->autoCommit ){
60410     sqlite3ConnectionUnlocked(db);
60411   }
60412
60413   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
60414   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
60415 }
60416
60417
60418 /*
60419 ** Each VDBE holds the result of the most recent sqlite3_step() call
60420 ** in p->rc.  This routine sets that result back to SQLITE_OK.
60421 */
60422 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
60423   p->rc = SQLITE_OK;
60424 }
60425
60426 /*
60427 ** Copy the error code and error message belonging to the VDBE passed
60428 ** as the first argument to its database handle (so that they will be 
60429 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
60430 **
60431 ** This function does not clear the VDBE error code or message, just
60432 ** copies them to the database handle.
60433 */
60434 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
60435   sqlite3 *db = p->db;
60436   int rc = p->rc;
60437   if( p->zErrMsg ){
60438     u8 mallocFailed = db->mallocFailed;
60439     sqlite3BeginBenignMalloc();
60440     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60441     sqlite3EndBenignMalloc();
60442     db->mallocFailed = mallocFailed;
60443     db->errCode = rc;
60444   }else{
60445     sqlite3Error(db, rc, 0);
60446   }
60447   return rc;
60448 }
60449
60450 /*
60451 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
60452 ** Write any error messages into *pzErrMsg.  Return the result code.
60453 **
60454 ** After this routine is run, the VDBE should be ready to be executed
60455 ** again.
60456 **
60457 ** To look at it another way, this routine resets the state of the
60458 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
60459 ** VDBE_MAGIC_INIT.
60460 */
60461 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
60462   sqlite3 *db;
60463   db = p->db;
60464
60465   /* If the VM did not run to completion or if it encountered an
60466   ** error, then it might not have been halted properly.  So halt
60467   ** it now.
60468   */
60469   sqlite3VdbeHalt(p);
60470
60471   /* If the VDBE has be run even partially, then transfer the error code
60472   ** and error message from the VDBE into the main database structure.  But
60473   ** if the VDBE has just been set to run but has not actually executed any
60474   ** instructions yet, leave the main database error information unchanged.
60475   */
60476   if( p->pc>=0 ){
60477     sqlite3VdbeTransferError(p);
60478     sqlite3DbFree(db, p->zErrMsg);
60479     p->zErrMsg = 0;
60480     if( p->runOnlyOnce ) p->expired = 1;
60481   }else if( p->rc && p->expired ){
60482     /* The expired flag was set on the VDBE before the first call
60483     ** to sqlite3_step(). For consistency (since sqlite3_step() was
60484     ** called), set the database error in this case as well.
60485     */
60486     sqlite3Error(db, p->rc, 0);
60487     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60488     sqlite3DbFree(db, p->zErrMsg);
60489     p->zErrMsg = 0;
60490   }
60491
60492   /* Reclaim all memory used by the VDBE
60493   */
60494   Cleanup(p);
60495
60496   /* Save profiling information from this VDBE run.
60497   */
60498 #ifdef VDBE_PROFILE
60499   {
60500     FILE *out = fopen("vdbe_profile.out", "a");
60501     if( out ){
60502       int i;
60503       fprintf(out, "---- ");
60504       for(i=0; i<p->nOp; i++){
60505         fprintf(out, "%02x", p->aOp[i].opcode);
60506       }
60507       fprintf(out, "\n");
60508       for(i=0; i<p->nOp; i++){
60509         fprintf(out, "%6d %10lld %8lld ",
60510            p->aOp[i].cnt,
60511            p->aOp[i].cycles,
60512            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
60513         );
60514         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
60515       }
60516       fclose(out);
60517     }
60518   }
60519 #endif
60520   p->magic = VDBE_MAGIC_INIT;
60521   return p->rc & db->errMask;
60522 }
60523  
60524 /*
60525 ** Clean up and delete a VDBE after execution.  Return an integer which is
60526 ** the result code.  Write any error message text into *pzErrMsg.
60527 */
60528 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
60529   int rc = SQLITE_OK;
60530   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
60531     rc = sqlite3VdbeReset(p);
60532     assert( (rc & p->db->errMask)==rc );
60533   }
60534   sqlite3VdbeDelete(p);
60535   return rc;
60536 }
60537
60538 /*
60539 ** Call the destructor for each auxdata entry in pVdbeFunc for which
60540 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
60541 ** are always destroyed.  To destroy all auxdata entries, call this
60542 ** routine with mask==0.
60543 */
60544 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
60545   int i;
60546   for(i=0; i<pVdbeFunc->nAux; i++){
60547     struct AuxData *pAux = &pVdbeFunc->apAux[i];
60548     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
60549       if( pAux->xDelete ){
60550         pAux->xDelete(pAux->pAux);
60551       }
60552       pAux->pAux = 0;
60553     }
60554   }
60555 }
60556
60557 /*
60558 ** Free all memory associated with the Vdbe passed as the second argument.
60559 ** The difference between this function and sqlite3VdbeDelete() is that
60560 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
60561 ** the database connection.
60562 */
60563 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
60564   SubProgram *pSub, *pNext;
60565   int i;
60566   assert( p->db==0 || p->db==db );
60567   releaseMemArray(p->aVar, p->nVar);
60568   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60569   for(pSub=p->pProgram; pSub; pSub=pNext){
60570     pNext = pSub->pNext;
60571     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
60572     sqlite3DbFree(db, pSub);
60573   }
60574   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
60575   vdbeFreeOpArray(db, p->aOp, p->nOp);
60576   sqlite3DbFree(db, p->aLabel);
60577   sqlite3DbFree(db, p->aColName);
60578   sqlite3DbFree(db, p->zSql);
60579   sqlite3DbFree(db, p->pFree);
60580 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
60581   sqlite3DbFree(db, p->zExplain);
60582   sqlite3DbFree(db, p->pExplain);
60583 #endif
60584   sqlite3DbFree(db, p);
60585 }
60586
60587 /*
60588 ** Delete an entire VDBE.
60589 */
60590 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
60591   sqlite3 *db;
60592
60593   if( NEVER(p==0) ) return;
60594   db = p->db;
60595   assert( sqlite3_mutex_held(db->mutex) );
60596   if( p->pPrev ){
60597     p->pPrev->pNext = p->pNext;
60598   }else{
60599     assert( db->pVdbe==p );
60600     db->pVdbe = p->pNext;
60601   }
60602   if( p->pNext ){
60603     p->pNext->pPrev = p->pPrev;
60604   }
60605   p->magic = VDBE_MAGIC_DEAD;
60606   p->db = 0;
60607   sqlite3VdbeDeleteObject(db, p);
60608 }
60609
60610 /*
60611 ** Make sure the cursor p is ready to read or write the row to which it
60612 ** was last positioned.  Return an error code if an OOM fault or I/O error
60613 ** prevents us from positioning the cursor to its correct position.
60614 **
60615 ** If a MoveTo operation is pending on the given cursor, then do that
60616 ** MoveTo now.  If no move is pending, check to see if the row has been
60617 ** deleted out from under the cursor and if it has, mark the row as
60618 ** a NULL row.
60619 **
60620 ** If the cursor is already pointing to the correct row and that row has
60621 ** not been deleted out from under the cursor, then this routine is a no-op.
60622 */
60623 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
60624   if( p->deferredMoveto ){
60625     int res, rc;
60626 #ifdef SQLITE_TEST
60627     extern int sqlite3_search_count;
60628 #endif
60629     assert( p->isTable );
60630     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
60631     if( rc ) return rc;
60632     p->lastRowid = p->movetoTarget;
60633     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
60634     p->rowidIsValid = 1;
60635 #ifdef SQLITE_TEST
60636     sqlite3_search_count++;
60637 #endif
60638     p->deferredMoveto = 0;
60639     p->cacheStatus = CACHE_STALE;
60640   }else if( ALWAYS(p->pCursor) ){
60641     int hasMoved;
60642     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
60643     if( rc ) return rc;
60644     if( hasMoved ){
60645       p->cacheStatus = CACHE_STALE;
60646       p->nullRow = 1;
60647     }
60648   }
60649   return SQLITE_OK;
60650 }
60651
60652 /*
60653 ** The following functions:
60654 **
60655 ** sqlite3VdbeSerialType()
60656 ** sqlite3VdbeSerialTypeLen()
60657 ** sqlite3VdbeSerialLen()
60658 ** sqlite3VdbeSerialPut()
60659 ** sqlite3VdbeSerialGet()
60660 **
60661 ** encapsulate the code that serializes values for storage in SQLite
60662 ** data and index records. Each serialized value consists of a
60663 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
60664 ** integer, stored as a varint.
60665 **
60666 ** In an SQLite index record, the serial type is stored directly before
60667 ** the blob of data that it corresponds to. In a table record, all serial
60668 ** types are stored at the start of the record, and the blobs of data at
60669 ** the end. Hence these functions allow the caller to handle the
60670 ** serial-type and data blob seperately.
60671 **
60672 ** The following table describes the various storage classes for data:
60673 **
60674 **   serial type        bytes of data      type
60675 **   --------------     ---------------    ---------------
60676 **      0                     0            NULL
60677 **      1                     1            signed integer
60678 **      2                     2            signed integer
60679 **      3                     3            signed integer
60680 **      4                     4            signed integer
60681 **      5                     6            signed integer
60682 **      6                     8            signed integer
60683 **      7                     8            IEEE float
60684 **      8                     0            Integer constant 0
60685 **      9                     0            Integer constant 1
60686 **     10,11                               reserved for expansion
60687 **    N>=12 and even       (N-12)/2        BLOB
60688 **    N>=13 and odd        (N-13)/2        text
60689 **
60690 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
60691 ** of SQLite will not understand those serial types.
60692 */
60693
60694 /*
60695 ** Return the serial-type for the value stored in pMem.
60696 */
60697 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
60698   int flags = pMem->flags;
60699   int n;
60700
60701   if( flags&MEM_Null ){
60702     return 0;
60703   }
60704   if( flags&MEM_Int ){
60705     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
60706 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
60707     i64 i = pMem->u.i;
60708     u64 u;
60709     if( file_format>=4 && (i&1)==i ){
60710       return 8+(u32)i;
60711     }
60712     if( i<0 ){
60713       if( i<(-MAX_6BYTE) ) return 6;
60714       /* Previous test prevents:  u = -(-9223372036854775808) */
60715       u = -i;
60716     }else{
60717       u = i;
60718     }
60719     if( u<=127 ) return 1;
60720     if( u<=32767 ) return 2;
60721     if( u<=8388607 ) return 3;
60722     if( u<=2147483647 ) return 4;
60723     if( u<=MAX_6BYTE ) return 5;
60724     return 6;
60725   }
60726   if( flags&MEM_Real ){
60727     return 7;
60728   }
60729   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
60730   n = pMem->n;
60731   if( flags & MEM_Zero ){
60732     n += pMem->u.nZero;
60733   }
60734   assert( n>=0 );
60735   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
60736 }
60737
60738 /*
60739 ** Return the length of the data corresponding to the supplied serial-type.
60740 */
60741 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
60742   if( serial_type>=12 ){
60743     return (serial_type-12)/2;
60744   }else{
60745     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
60746     return aSize[serial_type];
60747   }
60748 }
60749
60750 /*
60751 ** If we are on an architecture with mixed-endian floating 
60752 ** points (ex: ARM7) then swap the lower 4 bytes with the 
60753 ** upper 4 bytes.  Return the result.
60754 **
60755 ** For most architectures, this is a no-op.
60756 **
60757 ** (later):  It is reported to me that the mixed-endian problem
60758 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
60759 ** that early versions of GCC stored the two words of a 64-bit
60760 ** float in the wrong order.  And that error has been propagated
60761 ** ever since.  The blame is not necessarily with GCC, though.
60762 ** GCC might have just copying the problem from a prior compiler.
60763 ** I am also told that newer versions of GCC that follow a different
60764 ** ABI get the byte order right.
60765 **
60766 ** Developers using SQLite on an ARM7 should compile and run their
60767 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
60768 ** enabled, some asserts below will ensure that the byte order of
60769 ** floating point values is correct.
60770 **
60771 ** (2007-08-30)  Frank van Vugt has studied this problem closely
60772 ** and has send his findings to the SQLite developers.  Frank
60773 ** writes that some Linux kernels offer floating point hardware
60774 ** emulation that uses only 32-bit mantissas instead of a full 
60775 ** 48-bits as required by the IEEE standard.  (This is the
60776 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
60777 ** byte swapping becomes very complicated.  To avoid problems,
60778 ** the necessary byte swapping is carried out using a 64-bit integer
60779 ** rather than a 64-bit float.  Frank assures us that the code here
60780 ** works for him.  We, the developers, have no way to independently
60781 ** verify this, but Frank seems to know what he is talking about
60782 ** so we trust him.
60783 */
60784 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
60785 static u64 floatSwap(u64 in){
60786   union {
60787     u64 r;
60788     u32 i[2];
60789   } u;
60790   u32 t;
60791
60792   u.r = in;
60793   t = u.i[0];
60794   u.i[0] = u.i[1];
60795   u.i[1] = t;
60796   return u.r;
60797 }
60798 # define swapMixedEndianFloat(X)  X = floatSwap(X)
60799 #else
60800 # define swapMixedEndianFloat(X)
60801 #endif
60802
60803 /*
60804 ** Write the serialized data blob for the value stored in pMem into 
60805 ** buf. It is assumed that the caller has allocated sufficient space.
60806 ** Return the number of bytes written.
60807 **
60808 ** nBuf is the amount of space left in buf[].  nBuf must always be
60809 ** large enough to hold the entire field.  Except, if the field is
60810 ** a blob with a zero-filled tail, then buf[] might be just the right
60811 ** size to hold everything except for the zero-filled tail.  If buf[]
60812 ** is only big enough to hold the non-zero prefix, then only write that
60813 ** prefix into buf[].  But if buf[] is large enough to hold both the
60814 ** prefix and the tail then write the prefix and set the tail to all
60815 ** zeros.
60816 **
60817 ** Return the number of bytes actually written into buf[].  The number
60818 ** of bytes in the zero-filled tail is included in the return value only
60819 ** if those bytes were zeroed in buf[].
60820 */ 
60821 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
60822   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
60823   u32 len;
60824
60825   /* Integer and Real */
60826   if( serial_type<=7 && serial_type>0 ){
60827     u64 v;
60828     u32 i;
60829     if( serial_type==7 ){
60830       assert( sizeof(v)==sizeof(pMem->r) );
60831       memcpy(&v, &pMem->r, sizeof(v));
60832       swapMixedEndianFloat(v);
60833     }else{
60834       v = pMem->u.i;
60835     }
60836     len = i = sqlite3VdbeSerialTypeLen(serial_type);
60837     assert( len<=(u32)nBuf );
60838     while( i-- ){
60839       buf[i] = (u8)(v&0xFF);
60840       v >>= 8;
60841     }
60842     return len;
60843   }
60844
60845   /* String or blob */
60846   if( serial_type>=12 ){
60847     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
60848              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
60849     assert( pMem->n<=nBuf );
60850     len = pMem->n;
60851     memcpy(buf, pMem->z, len);
60852     if( pMem->flags & MEM_Zero ){
60853       len += pMem->u.nZero;
60854       assert( nBuf>=0 );
60855       if( len > (u32)nBuf ){
60856         len = (u32)nBuf;
60857       }
60858       memset(&buf[pMem->n], 0, len-pMem->n);
60859     }
60860     return len;
60861   }
60862
60863   /* NULL or constants 0 or 1 */
60864   return 0;
60865 }
60866
60867 /*
60868 ** Deserialize the data blob pointed to by buf as serial type serial_type
60869 ** and store the result in pMem.  Return the number of bytes read.
60870 */ 
60871 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
60872   const unsigned char *buf,     /* Buffer to deserialize from */
60873   u32 serial_type,              /* Serial type to deserialize */
60874   Mem *pMem                     /* Memory cell to write value into */
60875 ){
60876   switch( serial_type ){
60877     case 10:   /* Reserved for future use */
60878     case 11:   /* Reserved for future use */
60879     case 0: {  /* NULL */
60880       pMem->flags = MEM_Null;
60881       break;
60882     }
60883     case 1: { /* 1-byte signed integer */
60884       pMem->u.i = (signed char)buf[0];
60885       pMem->flags = MEM_Int;
60886       return 1;
60887     }
60888     case 2: { /* 2-byte signed integer */
60889       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
60890       pMem->flags = MEM_Int;
60891       return 2;
60892     }
60893     case 3: { /* 3-byte signed integer */
60894       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
60895       pMem->flags = MEM_Int;
60896       return 3;
60897     }
60898     case 4: { /* 4-byte signed integer */
60899       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60900       pMem->flags = MEM_Int;
60901       return 4;
60902     }
60903     case 5: { /* 6-byte signed integer */
60904       u64 x = (((signed char)buf[0])<<8) | buf[1];
60905       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
60906       x = (x<<32) | y;
60907       pMem->u.i = *(i64*)&x;
60908       pMem->flags = MEM_Int;
60909       return 6;
60910     }
60911     case 6:   /* 8-byte signed integer */
60912     case 7: { /* IEEE floating point */
60913       u64 x;
60914       u32 y;
60915 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
60916       /* Verify that integers and floating point values use the same
60917       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
60918       ** defined that 64-bit floating point values really are mixed
60919       ** endian.
60920       */
60921       static const u64 t1 = ((u64)0x3ff00000)<<32;
60922       static const double r1 = 1.0;
60923       u64 t2 = t1;
60924       swapMixedEndianFloat(t2);
60925       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
60926 #endif
60927
60928       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60929       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
60930       x = (x<<32) | y;
60931       if( serial_type==6 ){
60932         pMem->u.i = *(i64*)&x;
60933         pMem->flags = MEM_Int;
60934       }else{
60935         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
60936         swapMixedEndianFloat(x);
60937         memcpy(&pMem->r, &x, sizeof(x));
60938         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
60939       }
60940       return 8;
60941     }
60942     case 8:    /* Integer 0 */
60943     case 9: {  /* Integer 1 */
60944       pMem->u.i = serial_type-8;
60945       pMem->flags = MEM_Int;
60946       return 0;
60947     }
60948     default: {
60949       u32 len = (serial_type-12)/2;
60950       pMem->z = (char *)buf;
60951       pMem->n = len;
60952       pMem->xDel = 0;
60953       if( serial_type&0x01 ){
60954         pMem->flags = MEM_Str | MEM_Ephem;
60955       }else{
60956         pMem->flags = MEM_Blob | MEM_Ephem;
60957       }
60958       return len;
60959     }
60960   }
60961   return 0;
60962 }
60963
60964 /*
60965 ** This routine is used to allocate sufficient space for an UnpackedRecord
60966 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
60967 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
60968 **
60969 ** The space is either allocated using sqlite3DbMallocRaw() or from within
60970 ** the unaligned buffer passed via the second and third arguments (presumably
60971 ** stack space). If the former, then *ppFree is set to a pointer that should
60972 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
60973 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
60974 ** before returning.
60975 **
60976 ** If an OOM error occurs, NULL is returned.
60977 */
60978 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
60979   KeyInfo *pKeyInfo,              /* Description of the record */
60980   char *pSpace,                   /* Unaligned space available */
60981   int szSpace,                    /* Size of pSpace[] in bytes */
60982   char **ppFree                   /* OUT: Caller should free this pointer */
60983 ){
60984   UnpackedRecord *p;              /* Unpacked record to return */
60985   int nOff;                       /* Increment pSpace by nOff to align it */
60986   int nByte;                      /* Number of bytes required for *p */
60987
60988   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
60989   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
60990   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
60991   */
60992   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
60993   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
60994   if( nByte>szSpace+nOff ){
60995     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
60996     *ppFree = (char *)p;
60997     if( !p ) return 0;
60998   }else{
60999     p = (UnpackedRecord*)&pSpace[nOff];
61000     *ppFree = 0;
61001   }
61002
61003   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61004   p->pKeyInfo = pKeyInfo;
61005   p->nField = pKeyInfo->nField + 1;
61006   return p;
61007 }
61008
61009 /*
61010 ** Given the nKey-byte encoding of a record in pKey[], populate the 
61011 ** UnpackedRecord structure indicated by the fourth argument with the
61012 ** contents of the decoded record.
61013 */ 
61014 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61015   KeyInfo *pKeyInfo,     /* Information about the record format */
61016   int nKey,              /* Size of the binary record */
61017   const void *pKey,      /* The binary record */
61018   UnpackedRecord *p      /* Populate this structure before returning. */
61019 ){
61020   const unsigned char *aKey = (const unsigned char *)pKey;
61021   int d; 
61022   u32 idx;                        /* Offset in aKey[] to read from */
61023   u16 u;                          /* Unsigned loop counter */
61024   u32 szHdr;
61025   Mem *pMem = p->aMem;
61026
61027   p->flags = 0;
61028   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61029   idx = getVarint32(aKey, szHdr);
61030   d = szHdr;
61031   u = 0;
61032   while( idx<szHdr && u<p->nField && d<=nKey ){
61033     u32 serial_type;
61034
61035     idx += getVarint32(&aKey[idx], serial_type);
61036     pMem->enc = pKeyInfo->enc;
61037     pMem->db = pKeyInfo->db;
61038     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61039     pMem->zMalloc = 0;
61040     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61041     pMem++;
61042     u++;
61043   }
61044   assert( u<=pKeyInfo->nField + 1 );
61045   p->nField = u;
61046 }
61047
61048 /*
61049 ** This function compares the two table rows or index records
61050 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
61051 ** or positive integer if key1 is less than, equal to or 
61052 ** greater than key2.  The {nKey1, pKey1} key must be a blob
61053 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
61054 ** key must be a parsed key such as obtained from
61055 ** sqlite3VdbeParseRecord.
61056 **
61057 ** Key1 and Key2 do not have to contain the same number of fields.
61058 ** The key with fewer fields is usually compares less than the 
61059 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
61060 ** and the common prefixes are equal, then key1 is less than key2.
61061 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61062 ** equal, then the keys are considered to be equal and
61063 ** the parts beyond the common prefix are ignored.
61064 */
61065 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61066   int nKey1, const void *pKey1, /* Left key */
61067   UnpackedRecord *pPKey2        /* Right key */
61068 ){
61069   int d1;            /* Offset into aKey[] of next data element */
61070   u32 idx1;          /* Offset into aKey[] of next header element */
61071   u32 szHdr1;        /* Number of bytes in header */
61072   int i = 0;
61073   int nField;
61074   int rc = 0;
61075   const unsigned char *aKey1 = (const unsigned char *)pKey1;
61076   KeyInfo *pKeyInfo;
61077   Mem mem1;
61078
61079   pKeyInfo = pPKey2->pKeyInfo;
61080   mem1.enc = pKeyInfo->enc;
61081   mem1.db = pKeyInfo->db;
61082   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
61083   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61084
61085   /* Compilers may complain that mem1.u.i is potentially uninitialized.
61086   ** We could initialize it, as shown here, to silence those complaints.
61087   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
61088   ** the unnecessary initialization has a measurable negative performance
61089   ** impact, since this routine is a very high runner.  And so, we choose
61090   ** to ignore the compiler warnings and leave this variable uninitialized.
61091   */
61092   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
61093   
61094   idx1 = getVarint32(aKey1, szHdr1);
61095   d1 = szHdr1;
61096   nField = pKeyInfo->nField;
61097   while( idx1<szHdr1 && i<pPKey2->nField ){
61098     u32 serial_type1;
61099
61100     /* Read the serial types for the next element in each key. */
61101     idx1 += getVarint32( aKey1+idx1, serial_type1 );
61102     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61103
61104     /* Extract the values to be compared.
61105     */
61106     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61107
61108     /* Do the comparison
61109     */
61110     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61111                            i<nField ? pKeyInfo->aColl[i] : 0);
61112     if( rc!=0 ){
61113       assert( mem1.zMalloc==0 );  /* See comment below */
61114
61115       /* Invert the result if we are using DESC sort order. */
61116       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
61117         rc = -rc;
61118       }
61119     
61120       /* If the PREFIX_SEARCH flag is set and all fields except the final
61121       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
61122       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61123       ** This is used by the OP_IsUnique opcode.
61124       */
61125       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61126         assert( idx1==szHdr1 && rc );
61127         assert( mem1.flags & MEM_Int );
61128         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61129         pPKey2->rowid = mem1.u.i;
61130       }
61131     
61132       return rc;
61133     }
61134     i++;
61135   }
61136
61137   /* No memory allocation is ever used on mem1.  Prove this using
61138   ** the following assert().  If the assert() fails, it indicates a
61139   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61140   */
61141   assert( mem1.zMalloc==0 );
61142
61143   /* rc==0 here means that one of the keys ran out of fields and
61144   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61145   ** flag is set, then break the tie by treating key2 as larger.
61146   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61147   ** are considered to be equal.  Otherwise, the longer key is the 
61148   ** larger.  As it happens, the pPKey2 will always be the longer
61149   ** if there is a difference.
61150   */
61151   assert( rc==0 );
61152   if( pPKey2->flags & UNPACKED_INCRKEY ){
61153     rc = -1;
61154   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61155     /* Leave rc==0 */
61156   }else if( idx1<szHdr1 ){
61157     rc = 1;
61158   }
61159   return rc;
61160 }
61161  
61162
61163 /*
61164 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61165 ** Read the rowid (the last field in the record) and store it in *rowid.
61166 ** Return SQLITE_OK if everything works, or an error code otherwise.
61167 **
61168 ** pCur might be pointing to text obtained from a corrupt database file.
61169 ** So the content cannot be trusted.  Do appropriate checks on the content.
61170 */
61171 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61172   i64 nCellKey = 0;
61173   int rc;
61174   u32 szHdr;        /* Size of the header */
61175   u32 typeRowid;    /* Serial type of the rowid */
61176   u32 lenRowid;     /* Size of the rowid */
61177   Mem m, v;
61178
61179   UNUSED_PARAMETER(db);
61180
61181   /* Get the size of the index entry.  Only indices entries of less
61182   ** than 2GiB are support - anything large must be database corruption.
61183   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61184   ** this code can safely assume that nCellKey is 32-bits  
61185   */
61186   assert( sqlite3BtreeCursorIsValid(pCur) );
61187   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61188   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
61189   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61190
61191   /* Read in the complete content of the index entry */
61192   memset(&m, 0, sizeof(m));
61193   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61194   if( rc ){
61195     return rc;
61196   }
61197
61198   /* The index entry must begin with a header size */
61199   (void)getVarint32((u8*)m.z, szHdr);
61200   testcase( szHdr==3 );
61201   testcase( szHdr==m.n );
61202   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61203     goto idx_rowid_corruption;
61204   }
61205
61206   /* The last field of the index should be an integer - the ROWID.
61207   ** Verify that the last entry really is an integer. */
61208   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61209   testcase( typeRowid==1 );
61210   testcase( typeRowid==2 );
61211   testcase( typeRowid==3 );
61212   testcase( typeRowid==4 );
61213   testcase( typeRowid==5 );
61214   testcase( typeRowid==6 );
61215   testcase( typeRowid==8 );
61216   testcase( typeRowid==9 );
61217   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61218     goto idx_rowid_corruption;
61219   }
61220   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61221   testcase( (u32)m.n==szHdr+lenRowid );
61222   if( unlikely((u32)m.n<szHdr+lenRowid) ){
61223     goto idx_rowid_corruption;
61224   }
61225
61226   /* Fetch the integer off the end of the index record */
61227   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61228   *rowid = v.u.i;
61229   sqlite3VdbeMemRelease(&m);
61230   return SQLITE_OK;
61231
61232   /* Jump here if database corruption is detected after m has been
61233   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
61234 idx_rowid_corruption:
61235   testcase( m.zMalloc!=0 );
61236   sqlite3VdbeMemRelease(&m);
61237   return SQLITE_CORRUPT_BKPT;
61238 }
61239
61240 /*
61241 ** Compare the key of the index entry that cursor pC is pointing to against
61242 ** the key string in pUnpacked.  Write into *pRes a number
61243 ** that is negative, zero, or positive if pC is less than, equal to,
61244 ** or greater than pUnpacked.  Return SQLITE_OK on success.
61245 **
61246 ** pUnpacked is either created without a rowid or is truncated so that it
61247 ** omits the rowid at the end.  The rowid at the end of the index entry
61248 ** is ignored as well.  Hence, this routine only compares the prefixes 
61249 ** of the keys prior to the final rowid, not the entire key.
61250 */
61251 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61252   VdbeCursor *pC,             /* The cursor to compare against */
61253   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
61254   int *res                    /* Write the comparison result here */
61255 ){
61256   i64 nCellKey = 0;
61257   int rc;
61258   BtCursor *pCur = pC->pCursor;
61259   Mem m;
61260
61261   assert( sqlite3BtreeCursorIsValid(pCur) );
61262   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61263   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
61264   /* nCellKey will always be between 0 and 0xffffffff because of the say
61265   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61266   if( nCellKey<=0 || nCellKey>0x7fffffff ){
61267     *res = 0;
61268     return SQLITE_CORRUPT_BKPT;
61269   }
61270   memset(&m, 0, sizeof(m));
61271   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61272   if( rc ){
61273     return rc;
61274   }
61275   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
61276   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61277   sqlite3VdbeMemRelease(&m);
61278   return SQLITE_OK;
61279 }
61280
61281 /*
61282 ** This routine sets the value to be returned by subsequent calls to
61283 ** sqlite3_changes() on the database handle 'db'. 
61284 */
61285 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61286   assert( sqlite3_mutex_held(db->mutex) );
61287   db->nChange = nChange;
61288   db->nTotalChange += nChange;
61289 }
61290
61291 /*
61292 ** Set a flag in the vdbe to update the change counter when it is finalised
61293 ** or reset.
61294 */
61295 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61296   v->changeCntOn = 1;
61297 }
61298
61299 /*
61300 ** Mark every prepared statement associated with a database connection
61301 ** as expired.
61302 **
61303 ** An expired statement means that recompilation of the statement is
61304 ** recommend.  Statements expire when things happen that make their
61305 ** programs obsolete.  Removing user-defined functions or collating
61306 ** sequences, or changing an authorization function are the types of
61307 ** things that make prepared statements obsolete.
61308 */
61309 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61310   Vdbe *p;
61311   for(p = db->pVdbe; p; p=p->pNext){
61312     p->expired = 1;
61313   }
61314 }
61315
61316 /*
61317 ** Return the database associated with the Vdbe.
61318 */
61319 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61320   return v->db;
61321 }
61322
61323 /*
61324 ** Return a pointer to an sqlite3_value structure containing the value bound
61325 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
61326 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61327 ** constants) to the value before returning it.
61328 **
61329 ** The returned value must be freed by the caller using sqlite3ValueFree().
61330 */
61331 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61332   assert( iVar>0 );
61333   if( v ){
61334     Mem *pMem = &v->aVar[iVar-1];
61335     if( 0==(pMem->flags & MEM_Null) ){
61336       sqlite3_value *pRet = sqlite3ValueNew(v->db);
61337       if( pRet ){
61338         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61339         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61340         sqlite3VdbeMemStoreType((Mem *)pRet);
61341       }
61342       return pRet;
61343     }
61344   }
61345   return 0;
61346 }
61347
61348 /*
61349 ** Configure SQL variable iVar so that binding a new value to it signals
61350 ** to sqlite3_reoptimize() that re-preparing the statement may result
61351 ** in a better query plan.
61352 */
61353 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61354   assert( iVar>0 );
61355   if( iVar>32 ){
61356     v->expmask = 0xffffffff;
61357   }else{
61358     v->expmask |= ((u32)1 << (iVar-1));
61359   }
61360 }
61361
61362 /************** End of vdbeaux.c *********************************************/
61363 /************** Begin file vdbeapi.c *****************************************/
61364 /*
61365 ** 2004 May 26
61366 **
61367 ** The author disclaims copyright to this source code.  In place of
61368 ** a legal notice, here is a blessing:
61369 **
61370 **    May you do good and not evil.
61371 **    May you find forgiveness for yourself and forgive others.
61372 **    May you share freely, never taking more than you give.
61373 **
61374 *************************************************************************
61375 **
61376 ** This file contains code use to implement APIs that are part of the
61377 ** VDBE.
61378 */
61379
61380 #ifndef SQLITE_OMIT_DEPRECATED
61381 /*
61382 ** Return TRUE (non-zero) of the statement supplied as an argument needs
61383 ** to be recompiled.  A statement needs to be recompiled whenever the
61384 ** execution environment changes in a way that would alter the program
61385 ** that sqlite3_prepare() generates.  For example, if new functions or
61386 ** collating sequences are registered or if an authorizer function is
61387 ** added or changed.
61388 */
61389 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
61390   Vdbe *p = (Vdbe*)pStmt;
61391   return p==0 || p->expired;
61392 }
61393 #endif
61394
61395 /*
61396 ** Check on a Vdbe to make sure it has not been finalized.  Log
61397 ** an error and return true if it has been finalized (or is otherwise
61398 ** invalid).  Return false if it is ok.
61399 */
61400 static int vdbeSafety(Vdbe *p){
61401   if( p->db==0 ){
61402     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
61403     return 1;
61404   }else{
61405     return 0;
61406   }
61407 }
61408 static int vdbeSafetyNotNull(Vdbe *p){
61409   if( p==0 ){
61410     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
61411     return 1;
61412   }else{
61413     return vdbeSafety(p);
61414   }
61415 }
61416
61417 /*
61418 ** The following routine destroys a virtual machine that is created by
61419 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
61420 ** success/failure code that describes the result of executing the virtual
61421 ** machine.
61422 **
61423 ** This routine sets the error code and string returned by
61424 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61425 */
61426 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
61427   int rc;
61428   if( pStmt==0 ){
61429     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
61430     ** pointer is a harmless no-op. */
61431     rc = SQLITE_OK;
61432   }else{
61433     Vdbe *v = (Vdbe*)pStmt;
61434     sqlite3 *db = v->db;
61435     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
61436     sqlite3_mutex_enter(db->mutex);
61437     rc = sqlite3VdbeFinalize(v);
61438     rc = sqlite3ApiExit(db, rc);
61439     sqlite3LeaveMutexAndCloseZombie(db);
61440   }
61441   return rc;
61442 }
61443
61444 /*
61445 ** Terminate the current execution of an SQL statement and reset it
61446 ** back to its starting state so that it can be reused. A success code from
61447 ** the prior execution is returned.
61448 **
61449 ** This routine sets the error code and string returned by
61450 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61451 */
61452 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
61453   int rc;
61454   if( pStmt==0 ){
61455     rc = SQLITE_OK;
61456   }else{
61457     Vdbe *v = (Vdbe*)pStmt;
61458     sqlite3_mutex_enter(v->db->mutex);
61459     rc = sqlite3VdbeReset(v);
61460     sqlite3VdbeRewind(v);
61461     assert( (rc & (v->db->errMask))==rc );
61462     rc = sqlite3ApiExit(v->db, rc);
61463     sqlite3_mutex_leave(v->db->mutex);
61464   }
61465   return rc;
61466 }
61467
61468 /*
61469 ** Set all the parameters in the compiled SQL statement to NULL.
61470 */
61471 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
61472   int i;
61473   int rc = SQLITE_OK;
61474   Vdbe *p = (Vdbe*)pStmt;
61475 #if SQLITE_THREADSAFE
61476   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
61477 #endif
61478   sqlite3_mutex_enter(mutex);
61479   for(i=0; i<p->nVar; i++){
61480     sqlite3VdbeMemRelease(&p->aVar[i]);
61481     p->aVar[i].flags = MEM_Null;
61482   }
61483   if( p->isPrepareV2 && p->expmask ){
61484     p->expired = 1;
61485   }
61486   sqlite3_mutex_leave(mutex);
61487   return rc;
61488 }
61489
61490
61491 /**************************** sqlite3_value_  *******************************
61492 ** The following routines extract information from a Mem or sqlite3_value
61493 ** structure.
61494 */
61495 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
61496   Mem *p = (Mem*)pVal;
61497   if( p->flags & (MEM_Blob|MEM_Str) ){
61498     sqlite3VdbeMemExpandBlob(p);
61499     p->flags &= ~MEM_Str;
61500     p->flags |= MEM_Blob;
61501     return p->n ? p->z : 0;
61502   }else{
61503     return sqlite3_value_text(pVal);
61504   }
61505 }
61506 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
61507   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
61508 }
61509 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
61510   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
61511 }
61512 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
61513   return sqlite3VdbeRealValue((Mem*)pVal);
61514 }
61515 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
61516   return (int)sqlite3VdbeIntValue((Mem*)pVal);
61517 }
61518 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
61519   return sqlite3VdbeIntValue((Mem*)pVal);
61520 }
61521 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
61522   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
61523 }
61524 #ifndef SQLITE_OMIT_UTF16
61525 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
61526   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
61527 }
61528 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
61529   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
61530 }
61531 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
61532   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
61533 }
61534 #endif /* SQLITE_OMIT_UTF16 */
61535 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
61536   return pVal->type;
61537 }
61538
61539 /**************************** sqlite3_result_  *******************************
61540 ** The following routines are used by user-defined functions to specify
61541 ** the function result.
61542 **
61543 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
61544 ** result as a string or blob but if the string or blob is too large, it
61545 ** then sets the error code to SQLITE_TOOBIG
61546 */
61547 static void setResultStrOrError(
61548   sqlite3_context *pCtx,  /* Function context */
61549   const char *z,          /* String pointer */
61550   int n,                  /* Bytes in string, or negative */
61551   u8 enc,                 /* Encoding of z.  0 for BLOBs */
61552   void (*xDel)(void*)     /* Destructor function */
61553 ){
61554   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
61555     sqlite3_result_error_toobig(pCtx);
61556   }
61557 }
61558 SQLITE_API void sqlite3_result_blob(
61559   sqlite3_context *pCtx, 
61560   const void *z, 
61561   int n, 
61562   void (*xDel)(void *)
61563 ){
61564   assert( n>=0 );
61565   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61566   setResultStrOrError(pCtx, z, n, 0, xDel);
61567 }
61568 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
61569   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61570   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
61571 }
61572 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
61573   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61574   pCtx->isError = SQLITE_ERROR;
61575   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
61576 }
61577 #ifndef SQLITE_OMIT_UTF16
61578 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
61579   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61580   pCtx->isError = SQLITE_ERROR;
61581   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
61582 }
61583 #endif
61584 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
61585   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61586   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
61587 }
61588 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
61589   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61590   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
61591 }
61592 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
61593   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61594   sqlite3VdbeMemSetNull(&pCtx->s);
61595 }
61596 SQLITE_API void sqlite3_result_text(
61597   sqlite3_context *pCtx, 
61598   const char *z, 
61599   int n,
61600   void (*xDel)(void *)
61601 ){
61602   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61603   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
61604 }
61605 #ifndef SQLITE_OMIT_UTF16
61606 SQLITE_API void sqlite3_result_text16(
61607   sqlite3_context *pCtx, 
61608   const void *z, 
61609   int n, 
61610   void (*xDel)(void *)
61611 ){
61612   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61613   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
61614 }
61615 SQLITE_API void sqlite3_result_text16be(
61616   sqlite3_context *pCtx, 
61617   const void *z, 
61618   int n, 
61619   void (*xDel)(void *)
61620 ){
61621   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61622   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
61623 }
61624 SQLITE_API void sqlite3_result_text16le(
61625   sqlite3_context *pCtx, 
61626   const void *z, 
61627   int n, 
61628   void (*xDel)(void *)
61629 ){
61630   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61631   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
61632 }
61633 #endif /* SQLITE_OMIT_UTF16 */
61634 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
61635   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61636   sqlite3VdbeMemCopy(&pCtx->s, pValue);
61637 }
61638 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
61639   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61640   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
61641 }
61642 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
61643   pCtx->isError = errCode;
61644   if( pCtx->s.flags & MEM_Null ){
61645     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
61646                          SQLITE_UTF8, SQLITE_STATIC);
61647   }
61648 }
61649
61650 /* Force an SQLITE_TOOBIG error. */
61651 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
61652   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61653   pCtx->isError = SQLITE_TOOBIG;
61654   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
61655                        SQLITE_UTF8, SQLITE_STATIC);
61656 }
61657
61658 /* An SQLITE_NOMEM error. */
61659 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
61660   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61661   sqlite3VdbeMemSetNull(&pCtx->s);
61662   pCtx->isError = SQLITE_NOMEM;
61663   pCtx->s.db->mallocFailed = 1;
61664 }
61665
61666 /*
61667 ** This function is called after a transaction has been committed. It 
61668 ** invokes callbacks registered with sqlite3_wal_hook() as required.
61669 */
61670 static int doWalCallbacks(sqlite3 *db){
61671   int rc = SQLITE_OK;
61672 #ifndef SQLITE_OMIT_WAL
61673   int i;
61674   for(i=0; i<db->nDb; i++){
61675     Btree *pBt = db->aDb[i].pBt;
61676     if( pBt ){
61677       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
61678       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
61679         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
61680       }
61681     }
61682   }
61683 #endif
61684   return rc;
61685 }
61686
61687 /*
61688 ** Execute the statement pStmt, either until a row of data is ready, the
61689 ** statement is completely executed or an error occurs.
61690 **
61691 ** This routine implements the bulk of the logic behind the sqlite_step()
61692 ** API.  The only thing omitted is the automatic recompile if a 
61693 ** schema change has occurred.  That detail is handled by the
61694 ** outer sqlite3_step() wrapper procedure.
61695 */
61696 static int sqlite3Step(Vdbe *p){
61697   sqlite3 *db;
61698   int rc;
61699
61700   assert(p);
61701   if( p->magic!=VDBE_MAGIC_RUN ){
61702     /* We used to require that sqlite3_reset() be called before retrying
61703     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
61704     ** with version 3.7.0, we changed this so that sqlite3_reset() would
61705     ** be called automatically instead of throwing the SQLITE_MISUSE error.
61706     ** This "automatic-reset" change is not technically an incompatibility, 
61707     ** since any application that receives an SQLITE_MISUSE is broken by
61708     ** definition.
61709     **
61710     ** Nevertheless, some published applications that were originally written
61711     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
61712     ** returns, and those were broken by the automatic-reset change.  As a
61713     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
61714     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
61715     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
61716     ** or SQLITE_BUSY error.
61717     */
61718 #ifdef SQLITE_OMIT_AUTORESET
61719     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
61720       sqlite3_reset((sqlite3_stmt*)p);
61721     }else{
61722       return SQLITE_MISUSE_BKPT;
61723     }
61724 #else
61725     sqlite3_reset((sqlite3_stmt*)p);
61726 #endif
61727   }
61728
61729   /* Check that malloc() has not failed. If it has, return early. */
61730   db = p->db;
61731   if( db->mallocFailed ){
61732     p->rc = SQLITE_NOMEM;
61733     return SQLITE_NOMEM;
61734   }
61735
61736   if( p->pc<=0 && p->expired ){
61737     p->rc = SQLITE_SCHEMA;
61738     rc = SQLITE_ERROR;
61739     goto end_of_step;
61740   }
61741   if( p->pc<0 ){
61742     /* If there are no other statements currently running, then
61743     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
61744     ** from interrupting a statement that has not yet started.
61745     */
61746     if( db->activeVdbeCnt==0 ){
61747       db->u1.isInterrupted = 0;
61748     }
61749
61750     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
61751
61752 #ifndef SQLITE_OMIT_TRACE
61753     if( db->xProfile && !db->init.busy ){
61754       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
61755     }
61756 #endif
61757
61758     db->activeVdbeCnt++;
61759     if( p->readOnly==0 ) db->writeVdbeCnt++;
61760     p->pc = 0;
61761   }
61762 #ifndef SQLITE_OMIT_EXPLAIN
61763   if( p->explain ){
61764     rc = sqlite3VdbeList(p);
61765   }else
61766 #endif /* SQLITE_OMIT_EXPLAIN */
61767   {
61768     db->vdbeExecCnt++;
61769     rc = sqlite3VdbeExec(p);
61770     db->vdbeExecCnt--;
61771   }
61772
61773 #ifndef SQLITE_OMIT_TRACE
61774   /* Invoke the profile callback if there is one
61775   */
61776   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
61777     sqlite3_int64 iNow;
61778     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
61779     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
61780   }
61781 #endif
61782
61783   if( rc==SQLITE_DONE ){
61784     assert( p->rc==SQLITE_OK );
61785     p->rc = doWalCallbacks(db);
61786     if( p->rc!=SQLITE_OK ){
61787       rc = SQLITE_ERROR;
61788     }
61789   }
61790
61791   db->errCode = rc;
61792   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
61793     p->rc = SQLITE_NOMEM;
61794   }
61795 end_of_step:
61796   /* At this point local variable rc holds the value that should be 
61797   ** returned if this statement was compiled using the legacy 
61798   ** sqlite3_prepare() interface. According to the docs, this can only
61799   ** be one of the values in the first assert() below. Variable p->rc 
61800   ** contains the value that would be returned if sqlite3_finalize() 
61801   ** were called on statement p.
61802   */
61803   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
61804        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
61805   );
61806   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
61807   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
61808     /* If this statement was prepared using sqlite3_prepare_v2(), and an
61809     ** error has occured, then return the error code in p->rc to the
61810     ** caller. Set the error code in the database handle to the same value.
61811     */ 
61812     rc = sqlite3VdbeTransferError(p);
61813   }
61814   return (rc&db->errMask);
61815 }
61816
61817 /*
61818 ** The maximum number of times that a statement will try to reparse
61819 ** itself before giving up and returning SQLITE_SCHEMA.
61820 */
61821 #ifndef SQLITE_MAX_SCHEMA_RETRY
61822 # define SQLITE_MAX_SCHEMA_RETRY 5
61823 #endif
61824
61825 /*
61826 ** This is the top-level implementation of sqlite3_step().  Call
61827 ** sqlite3Step() to do most of the work.  If a schema error occurs,
61828 ** call sqlite3Reprepare() and try again.
61829 */
61830 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
61831   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
61832   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
61833   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
61834   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
61835   sqlite3 *db;             /* The database connection */
61836
61837   if( vdbeSafetyNotNull(v) ){
61838     return SQLITE_MISUSE_BKPT;
61839   }
61840   db = v->db;
61841   sqlite3_mutex_enter(db->mutex);
61842   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
61843          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
61844          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
61845     sqlite3_reset(pStmt);
61846     assert( v->expired==0 );
61847   }
61848   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
61849     /* This case occurs after failing to recompile an sql statement. 
61850     ** The error message from the SQL compiler has already been loaded 
61851     ** into the database handle. This block copies the error message 
61852     ** from the database handle into the statement and sets the statement
61853     ** program counter to 0 to ensure that when the statement is 
61854     ** finalized or reset the parser error message is available via
61855     ** sqlite3_errmsg() and sqlite3_errcode().
61856     */
61857     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
61858     sqlite3DbFree(db, v->zErrMsg);
61859     if( !db->mallocFailed ){
61860       v->zErrMsg = sqlite3DbStrDup(db, zErr);
61861       v->rc = rc2;
61862     } else {
61863       v->zErrMsg = 0;
61864       v->rc = rc = SQLITE_NOMEM;
61865     }
61866   }
61867   rc = sqlite3ApiExit(db, rc);
61868   sqlite3_mutex_leave(db->mutex);
61869   return rc;
61870 }
61871
61872 /*
61873 ** Extract the user data from a sqlite3_context structure and return a
61874 ** pointer to it.
61875 */
61876 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
61877   assert( p && p->pFunc );
61878   return p->pFunc->pUserData;
61879 }
61880
61881 /*
61882 ** Extract the user data from a sqlite3_context structure and return a
61883 ** pointer to it.
61884 **
61885 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
61886 ** returns a copy of the pointer to the database connection (the 1st
61887 ** parameter) of the sqlite3_create_function() and
61888 ** sqlite3_create_function16() routines that originally registered the
61889 ** application defined function.
61890 */
61891 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
61892   assert( p && p->pFunc );
61893   return p->s.db;
61894 }
61895
61896 /*
61897 ** The following is the implementation of an SQL function that always
61898 ** fails with an error message stating that the function is used in the
61899 ** wrong context.  The sqlite3_overload_function() API might construct
61900 ** SQL function that use this routine so that the functions will exist
61901 ** for name resolution but are actually overloaded by the xFindFunction
61902 ** method of virtual tables.
61903 */
61904 SQLITE_PRIVATE void sqlite3InvalidFunction(
61905   sqlite3_context *context,  /* The function calling context */
61906   int NotUsed,               /* Number of arguments to the function */
61907   sqlite3_value **NotUsed2   /* Value of each argument */
61908 ){
61909   const char *zName = context->pFunc->zName;
61910   char *zErr;
61911   UNUSED_PARAMETER2(NotUsed, NotUsed2);
61912   zErr = sqlite3_mprintf(
61913       "unable to use function %s in the requested context", zName);
61914   sqlite3_result_error(context, zErr, -1);
61915   sqlite3_free(zErr);
61916 }
61917
61918 /*
61919 ** Allocate or return the aggregate context for a user function.  A new
61920 ** context is allocated on the first call.  Subsequent calls return the
61921 ** same context that was returned on prior calls.
61922 */
61923 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
61924   Mem *pMem;
61925   assert( p && p->pFunc && p->pFunc->xStep );
61926   assert( sqlite3_mutex_held(p->s.db->mutex) );
61927   pMem = p->pMem;
61928   testcase( nByte<0 );
61929   if( (pMem->flags & MEM_Agg)==0 ){
61930     if( nByte<=0 ){
61931       sqlite3VdbeMemReleaseExternal(pMem);
61932       pMem->flags = MEM_Null;
61933       pMem->z = 0;
61934     }else{
61935       sqlite3VdbeMemGrow(pMem, nByte, 0);
61936       pMem->flags = MEM_Agg;
61937       pMem->u.pDef = p->pFunc;
61938       if( pMem->z ){
61939         memset(pMem->z, 0, nByte);
61940       }
61941     }
61942   }
61943   return (void*)pMem->z;
61944 }
61945
61946 /*
61947 ** Return the auxilary data pointer, if any, for the iArg'th argument to
61948 ** the user-function defined by pCtx.
61949 */
61950 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
61951   VdbeFunc *pVdbeFunc;
61952
61953   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61954   pVdbeFunc = pCtx->pVdbeFunc;
61955   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
61956     return 0;
61957   }
61958   return pVdbeFunc->apAux[iArg].pAux;
61959 }
61960
61961 /*
61962 ** Set the auxilary data pointer and delete function, for the iArg'th
61963 ** argument to the user-function defined by pCtx. Any previous value is
61964 ** deleted by calling the delete function specified when it was set.
61965 */
61966 SQLITE_API void sqlite3_set_auxdata(
61967   sqlite3_context *pCtx, 
61968   int iArg, 
61969   void *pAux, 
61970   void (*xDelete)(void*)
61971 ){
61972   struct AuxData *pAuxData;
61973   VdbeFunc *pVdbeFunc;
61974   if( iArg<0 ) goto failed;
61975
61976   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61977   pVdbeFunc = pCtx->pVdbeFunc;
61978   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
61979     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
61980     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
61981     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
61982     if( !pVdbeFunc ){
61983       goto failed;
61984     }
61985     pCtx->pVdbeFunc = pVdbeFunc;
61986     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
61987     pVdbeFunc->nAux = iArg+1;
61988     pVdbeFunc->pFunc = pCtx->pFunc;
61989   }
61990
61991   pAuxData = &pVdbeFunc->apAux[iArg];
61992   if( pAuxData->pAux && pAuxData->xDelete ){
61993     pAuxData->xDelete(pAuxData->pAux);
61994   }
61995   pAuxData->pAux = pAux;
61996   pAuxData->xDelete = xDelete;
61997   return;
61998
61999 failed:
62000   if( xDelete ){
62001     xDelete(pAux);
62002   }
62003 }
62004
62005 #ifndef SQLITE_OMIT_DEPRECATED
62006 /*
62007 ** Return the number of times the Step function of a aggregate has been 
62008 ** called.
62009 **
62010 ** This function is deprecated.  Do not use it for new code.  It is
62011 ** provide only to avoid breaking legacy code.  New aggregate function
62012 ** implementations should keep their own counts within their aggregate
62013 ** context.
62014 */
62015 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62016   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62017   return p->pMem->n;
62018 }
62019 #endif
62020
62021 /*
62022 ** Return the number of columns in the result set for the statement pStmt.
62023 */
62024 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62025   Vdbe *pVm = (Vdbe *)pStmt;
62026   return pVm ? pVm->nResColumn : 0;
62027 }
62028
62029 /*
62030 ** Return the number of values available from the current row of the
62031 ** currently executing statement pStmt.
62032 */
62033 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62034   Vdbe *pVm = (Vdbe *)pStmt;
62035   if( pVm==0 || pVm->pResultSet==0 ) return 0;
62036   return pVm->nResColumn;
62037 }
62038
62039
62040 /*
62041 ** Check to see if column iCol of the given statement is valid.  If
62042 ** it is, return a pointer to the Mem for the value of that column.
62043 ** If iCol is not valid, return a pointer to a Mem which has a value
62044 ** of NULL.
62045 */
62046 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62047   Vdbe *pVm;
62048   Mem *pOut;
62049
62050   pVm = (Vdbe *)pStmt;
62051   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62052     sqlite3_mutex_enter(pVm->db->mutex);
62053     pOut = &pVm->pResultSet[i];
62054   }else{
62055     /* If the value passed as the second argument is out of range, return
62056     ** a pointer to the following static Mem object which contains the
62057     ** value SQL NULL. Even though the Mem structure contains an element
62058     ** of type i64, on certain architectures (x86) with certain compiler
62059     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62060     ** instead of an 8-byte one. This all works fine, except that when
62061     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62062     ** that a Mem structure is located on an 8-byte boundary. To prevent
62063     ** these assert()s from failing, when building with SQLITE_DEBUG defined
62064     ** using gcc, we force nullMem to be 8-byte aligned using the magical
62065     ** __attribute__((aligned(8))) macro.  */
62066     static const Mem nullMem 
62067 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62068       __attribute__((aligned(8))) 
62069 #endif
62070       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62071 #ifdef SQLITE_DEBUG
62072          0, 0,  /* pScopyFrom, pFiller */
62073 #endif
62074          0, 0 };
62075
62076     if( pVm && ALWAYS(pVm->db) ){
62077       sqlite3_mutex_enter(pVm->db->mutex);
62078       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62079     }
62080     pOut = (Mem*)&nullMem;
62081   }
62082   return pOut;
62083 }
62084
62085 /*
62086 ** This function is called after invoking an sqlite3_value_XXX function on a 
62087 ** column value (i.e. a value returned by evaluating an SQL expression in the
62088 ** select list of a SELECT statement) that may cause a malloc() failure. If 
62089 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62090 ** code of statement pStmt set to SQLITE_NOMEM.
62091 **
62092 ** Specifically, this is called from within:
62093 **
62094 **     sqlite3_column_int()
62095 **     sqlite3_column_int64()
62096 **     sqlite3_column_text()
62097 **     sqlite3_column_text16()
62098 **     sqlite3_column_real()
62099 **     sqlite3_column_bytes()
62100 **     sqlite3_column_bytes16()
62101 **     sqiite3_column_blob()
62102 */
62103 static void columnMallocFailure(sqlite3_stmt *pStmt)
62104 {
62105   /* If malloc() failed during an encoding conversion within an
62106   ** sqlite3_column_XXX API, then set the return code of the statement to
62107   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62108   ** and _finalize() will return NOMEM.
62109   */
62110   Vdbe *p = (Vdbe *)pStmt;
62111   if( p ){
62112     p->rc = sqlite3ApiExit(p->db, p->rc);
62113     sqlite3_mutex_leave(p->db->mutex);
62114   }
62115 }
62116
62117 /**************************** sqlite3_column_  *******************************
62118 ** The following routines are used to access elements of the current row
62119 ** in the result set.
62120 */
62121 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62122   const void *val;
62123   val = sqlite3_value_blob( columnMem(pStmt,i) );
62124   /* Even though there is no encoding conversion, value_blob() might
62125   ** need to call malloc() to expand the result of a zeroblob() 
62126   ** expression. 
62127   */
62128   columnMallocFailure(pStmt);
62129   return val;
62130 }
62131 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62132   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62133   columnMallocFailure(pStmt);
62134   return val;
62135 }
62136 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62137   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62138   columnMallocFailure(pStmt);
62139   return val;
62140 }
62141 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62142   double val = sqlite3_value_double( columnMem(pStmt,i) );
62143   columnMallocFailure(pStmt);
62144   return val;
62145 }
62146 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62147   int val = sqlite3_value_int( columnMem(pStmt,i) );
62148   columnMallocFailure(pStmt);
62149   return val;
62150 }
62151 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62152   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62153   columnMallocFailure(pStmt);
62154   return val;
62155 }
62156 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62157   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62158   columnMallocFailure(pStmt);
62159   return val;
62160 }
62161 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62162   Mem *pOut = columnMem(pStmt, i);
62163   if( pOut->flags&MEM_Static ){
62164     pOut->flags &= ~MEM_Static;
62165     pOut->flags |= MEM_Ephem;
62166   }
62167   columnMallocFailure(pStmt);
62168   return (sqlite3_value *)pOut;
62169 }
62170 #ifndef SQLITE_OMIT_UTF16
62171 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62172   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62173   columnMallocFailure(pStmt);
62174   return val;
62175 }
62176 #endif /* SQLITE_OMIT_UTF16 */
62177 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62178   int iType = sqlite3_value_type( columnMem(pStmt,i) );
62179   columnMallocFailure(pStmt);
62180   return iType;
62181 }
62182
62183 /* The following function is experimental and subject to change or
62184 ** removal */
62185 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62186 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62187 **}
62188 */
62189
62190 /*
62191 ** Convert the N-th element of pStmt->pColName[] into a string using
62192 ** xFunc() then return that string.  If N is out of range, return 0.
62193 **
62194 ** There are up to 5 names for each column.  useType determines which
62195 ** name is returned.  Here are the names:
62196 **
62197 **    0      The column name as it should be displayed for output
62198 **    1      The datatype name for the column
62199 **    2      The name of the database that the column derives from
62200 **    3      The name of the table that the column derives from
62201 **    4      The name of the table column that the result column derives from
62202 **
62203 ** If the result is not a simple column reference (if it is an expression
62204 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62205 */
62206 static const void *columnName(
62207   sqlite3_stmt *pStmt,
62208   int N,
62209   const void *(*xFunc)(Mem*),
62210   int useType
62211 ){
62212   const void *ret = 0;
62213   Vdbe *p = (Vdbe *)pStmt;
62214   int n;
62215   sqlite3 *db = p->db;
62216   
62217   assert( db!=0 );
62218   n = sqlite3_column_count(pStmt);
62219   if( N<n && N>=0 ){
62220     N += useType*n;
62221     sqlite3_mutex_enter(db->mutex);
62222     assert( db->mallocFailed==0 );
62223     ret = xFunc(&p->aColName[N]);
62224      /* A malloc may have failed inside of the xFunc() call. If this
62225     ** is the case, clear the mallocFailed flag and return NULL.
62226     */
62227     if( db->mallocFailed ){
62228       db->mallocFailed = 0;
62229       ret = 0;
62230     }
62231     sqlite3_mutex_leave(db->mutex);
62232   }
62233   return ret;
62234 }
62235
62236 /*
62237 ** Return the name of the Nth column of the result set returned by SQL
62238 ** statement pStmt.
62239 */
62240 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62241   return columnName(
62242       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62243 }
62244 #ifndef SQLITE_OMIT_UTF16
62245 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62246   return columnName(
62247       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62248 }
62249 #endif
62250
62251 /*
62252 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
62253 ** not define OMIT_DECLTYPE.
62254 */
62255 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62256 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62257          and SQLITE_ENABLE_COLUMN_METADATA"
62258 #endif
62259
62260 #ifndef SQLITE_OMIT_DECLTYPE
62261 /*
62262 ** Return the column declaration type (if applicable) of the 'i'th column
62263 ** of the result set of SQL statement pStmt.
62264 */
62265 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62266   return columnName(
62267       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62268 }
62269 #ifndef SQLITE_OMIT_UTF16
62270 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62271   return columnName(
62272       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62273 }
62274 #endif /* SQLITE_OMIT_UTF16 */
62275 #endif /* SQLITE_OMIT_DECLTYPE */
62276
62277 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62278 /*
62279 ** Return the name of the database from which a result column derives.
62280 ** NULL is returned if the result column is an expression or constant or
62281 ** anything else which is not an unabiguous reference to a database column.
62282 */
62283 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62284   return columnName(
62285       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62286 }
62287 #ifndef SQLITE_OMIT_UTF16
62288 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62289   return columnName(
62290       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62291 }
62292 #endif /* SQLITE_OMIT_UTF16 */
62293
62294 /*
62295 ** Return the name of the table from which a result column derives.
62296 ** NULL is returned if the result column is an expression or constant or
62297 ** anything else which is not an unabiguous reference to a database column.
62298 */
62299 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62300   return columnName(
62301       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62302 }
62303 #ifndef SQLITE_OMIT_UTF16
62304 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62305   return columnName(
62306       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62307 }
62308 #endif /* SQLITE_OMIT_UTF16 */
62309
62310 /*
62311 ** Return the name of the table column from which a result column derives.
62312 ** NULL is returned if the result column is an expression or constant or
62313 ** anything else which is not an unabiguous reference to a database column.
62314 */
62315 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62316   return columnName(
62317       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62318 }
62319 #ifndef SQLITE_OMIT_UTF16
62320 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62321   return columnName(
62322       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62323 }
62324 #endif /* SQLITE_OMIT_UTF16 */
62325 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62326
62327
62328 /******************************* sqlite3_bind_  ***************************
62329 ** 
62330 ** Routines used to attach values to wildcards in a compiled SQL statement.
62331 */
62332 /*
62333 ** Unbind the value bound to variable i in virtual machine p. This is the 
62334 ** the same as binding a NULL value to the column. If the "i" parameter is
62335 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62336 **
62337 ** A successful evaluation of this routine acquires the mutex on p.
62338 ** the mutex is released if any kind of error occurs.
62339 **
62340 ** The error code stored in database p->db is overwritten with the return
62341 ** value in any case.
62342 */
62343 static int vdbeUnbind(Vdbe *p, int i){
62344   Mem *pVar;
62345   if( vdbeSafetyNotNull(p) ){
62346     return SQLITE_MISUSE_BKPT;
62347   }
62348   sqlite3_mutex_enter(p->db->mutex);
62349   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62350     sqlite3Error(p->db, SQLITE_MISUSE, 0);
62351     sqlite3_mutex_leave(p->db->mutex);
62352     sqlite3_log(SQLITE_MISUSE, 
62353         "bind on a busy prepared statement: [%s]", p->zSql);
62354     return SQLITE_MISUSE_BKPT;
62355   }
62356   if( i<1 || i>p->nVar ){
62357     sqlite3Error(p->db, SQLITE_RANGE, 0);
62358     sqlite3_mutex_leave(p->db->mutex);
62359     return SQLITE_RANGE;
62360   }
62361   i--;
62362   pVar = &p->aVar[i];
62363   sqlite3VdbeMemRelease(pVar);
62364   pVar->flags = MEM_Null;
62365   sqlite3Error(p->db, SQLITE_OK, 0);
62366
62367   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
62368   ** binding a new value to this variable invalidates the current query plan.
62369   **
62370   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
62371   ** parameter in the WHERE clause might influence the choice of query plan
62372   ** for a statement, then the statement will be automatically recompiled,
62373   ** as if there had been a schema change, on the first sqlite3_step() call
62374   ** following any change to the bindings of that parameter.
62375   */
62376   if( p->isPrepareV2 &&
62377      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
62378   ){
62379     p->expired = 1;
62380   }
62381   return SQLITE_OK;
62382 }
62383
62384 /*
62385 ** Bind a text or BLOB value.
62386 */
62387 static int bindText(
62388   sqlite3_stmt *pStmt,   /* The statement to bind against */
62389   int i,                 /* Index of the parameter to bind */
62390   const void *zData,     /* Pointer to the data to be bound */
62391   int nData,             /* Number of bytes of data to be bound */
62392   void (*xDel)(void*),   /* Destructor for the data */
62393   u8 encoding            /* Encoding for the data */
62394 ){
62395   Vdbe *p = (Vdbe *)pStmt;
62396   Mem *pVar;
62397   int rc;
62398
62399   rc = vdbeUnbind(p, i);
62400   if( rc==SQLITE_OK ){
62401     if( zData!=0 ){
62402       pVar = &p->aVar[i-1];
62403       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
62404       if( rc==SQLITE_OK && encoding!=0 ){
62405         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
62406       }
62407       sqlite3Error(p->db, rc, 0);
62408       rc = sqlite3ApiExit(p->db, rc);
62409     }
62410     sqlite3_mutex_leave(p->db->mutex);
62411   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
62412     xDel((void*)zData);
62413   }
62414   return rc;
62415 }
62416
62417
62418 /*
62419 ** Bind a blob value to an SQL statement variable.
62420 */
62421 SQLITE_API int sqlite3_bind_blob(
62422   sqlite3_stmt *pStmt, 
62423   int i, 
62424   const void *zData, 
62425   int nData, 
62426   void (*xDel)(void*)
62427 ){
62428   return bindText(pStmt, i, zData, nData, xDel, 0);
62429 }
62430 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
62431   int rc;
62432   Vdbe *p = (Vdbe *)pStmt;
62433   rc = vdbeUnbind(p, i);
62434   if( rc==SQLITE_OK ){
62435     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
62436     sqlite3_mutex_leave(p->db->mutex);
62437   }
62438   return rc;
62439 }
62440 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
62441   return sqlite3_bind_int64(p, i, (i64)iValue);
62442 }
62443 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
62444   int rc;
62445   Vdbe *p = (Vdbe *)pStmt;
62446   rc = vdbeUnbind(p, i);
62447   if( rc==SQLITE_OK ){
62448     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
62449     sqlite3_mutex_leave(p->db->mutex);
62450   }
62451   return rc;
62452 }
62453 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
62454   int rc;
62455   Vdbe *p = (Vdbe*)pStmt;
62456   rc = vdbeUnbind(p, i);
62457   if( rc==SQLITE_OK ){
62458     sqlite3_mutex_leave(p->db->mutex);
62459   }
62460   return rc;
62461 }
62462 SQLITE_API int sqlite3_bind_text( 
62463   sqlite3_stmt *pStmt, 
62464   int i, 
62465   const char *zData, 
62466   int nData, 
62467   void (*xDel)(void*)
62468 ){
62469   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
62470 }
62471 #ifndef SQLITE_OMIT_UTF16
62472 SQLITE_API int sqlite3_bind_text16(
62473   sqlite3_stmt *pStmt, 
62474   int i, 
62475   const void *zData, 
62476   int nData, 
62477   void (*xDel)(void*)
62478 ){
62479   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
62480 }
62481 #endif /* SQLITE_OMIT_UTF16 */
62482 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
62483   int rc;
62484   switch( pValue->type ){
62485     case SQLITE_INTEGER: {
62486       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
62487       break;
62488     }
62489     case SQLITE_FLOAT: {
62490       rc = sqlite3_bind_double(pStmt, i, pValue->r);
62491       break;
62492     }
62493     case SQLITE_BLOB: {
62494       if( pValue->flags & MEM_Zero ){
62495         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
62496       }else{
62497         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
62498       }
62499       break;
62500     }
62501     case SQLITE_TEXT: {
62502       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
62503                               pValue->enc);
62504       break;
62505     }
62506     default: {
62507       rc = sqlite3_bind_null(pStmt, i);
62508       break;
62509     }
62510   }
62511   return rc;
62512 }
62513 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
62514   int rc;
62515   Vdbe *p = (Vdbe *)pStmt;
62516   rc = vdbeUnbind(p, i);
62517   if( rc==SQLITE_OK ){
62518     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
62519     sqlite3_mutex_leave(p->db->mutex);
62520   }
62521   return rc;
62522 }
62523
62524 /*
62525 ** Return the number of wildcards that can be potentially bound to.
62526 ** This routine is added to support DBD::SQLite.  
62527 */
62528 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
62529   Vdbe *p = (Vdbe*)pStmt;
62530   return p ? p->nVar : 0;
62531 }
62532
62533 /*
62534 ** Return the name of a wildcard parameter.  Return NULL if the index
62535 ** is out of range or if the wildcard is unnamed.
62536 **
62537 ** The result is always UTF-8.
62538 */
62539 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
62540   Vdbe *p = (Vdbe*)pStmt;
62541   if( p==0 || i<1 || i>p->nzVar ){
62542     return 0;
62543   }
62544   return p->azVar[i-1];
62545 }
62546
62547 /*
62548 ** Given a wildcard parameter name, return the index of the variable
62549 ** with that name.  If there is no variable with the given name,
62550 ** return 0.
62551 */
62552 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
62553   int i;
62554   if( p==0 ){
62555     return 0;
62556   }
62557   if( zName ){
62558     for(i=0; i<p->nzVar; i++){
62559       const char *z = p->azVar[i];
62560       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
62561         return i+1;
62562       }
62563     }
62564   }
62565   return 0;
62566 }
62567 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
62568   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
62569 }
62570
62571 /*
62572 ** Transfer all bindings from the first statement over to the second.
62573 */
62574 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62575   Vdbe *pFrom = (Vdbe*)pFromStmt;
62576   Vdbe *pTo = (Vdbe*)pToStmt;
62577   int i;
62578   assert( pTo->db==pFrom->db );
62579   assert( pTo->nVar==pFrom->nVar );
62580   sqlite3_mutex_enter(pTo->db->mutex);
62581   for(i=0; i<pFrom->nVar; i++){
62582     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
62583   }
62584   sqlite3_mutex_leave(pTo->db->mutex);
62585   return SQLITE_OK;
62586 }
62587
62588 #ifndef SQLITE_OMIT_DEPRECATED
62589 /*
62590 ** Deprecated external interface.  Internal/core SQLite code
62591 ** should call sqlite3TransferBindings.
62592 **
62593 ** Is is misuse to call this routine with statements from different
62594 ** database connections.  But as this is a deprecated interface, we
62595 ** will not bother to check for that condition.
62596 **
62597 ** If the two statements contain a different number of bindings, then
62598 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
62599 ** SQLITE_OK is returned.
62600 */
62601 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62602   Vdbe *pFrom = (Vdbe*)pFromStmt;
62603   Vdbe *pTo = (Vdbe*)pToStmt;
62604   if( pFrom->nVar!=pTo->nVar ){
62605     return SQLITE_ERROR;
62606   }
62607   if( pTo->isPrepareV2 && pTo->expmask ){
62608     pTo->expired = 1;
62609   }
62610   if( pFrom->isPrepareV2 && pFrom->expmask ){
62611     pFrom->expired = 1;
62612   }
62613   return sqlite3TransferBindings(pFromStmt, pToStmt);
62614 }
62615 #endif
62616
62617 /*
62618 ** Return the sqlite3* database handle to which the prepared statement given
62619 ** in the argument belongs.  This is the same database handle that was
62620 ** the first argument to the sqlite3_prepare() that was used to create
62621 ** the statement in the first place.
62622 */
62623 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
62624   return pStmt ? ((Vdbe*)pStmt)->db : 0;
62625 }
62626
62627 /*
62628 ** Return true if the prepared statement is guaranteed to not modify the
62629 ** database.
62630 */
62631 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
62632   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
62633 }
62634
62635 /*
62636 ** Return true if the prepared statement is in need of being reset.
62637 */
62638 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
62639   Vdbe *v = (Vdbe*)pStmt;
62640   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
62641 }
62642
62643 /*
62644 ** Return a pointer to the next prepared statement after pStmt associated
62645 ** with database connection pDb.  If pStmt is NULL, return the first
62646 ** prepared statement for the database connection.  Return NULL if there
62647 ** are no more.
62648 */
62649 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
62650   sqlite3_stmt *pNext;
62651   sqlite3_mutex_enter(pDb->mutex);
62652   if( pStmt==0 ){
62653     pNext = (sqlite3_stmt*)pDb->pVdbe;
62654   }else{
62655     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
62656   }
62657   sqlite3_mutex_leave(pDb->mutex);
62658   return pNext;
62659 }
62660
62661 /*
62662 ** Return the value of a status counter for a prepared statement
62663 */
62664 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
62665   Vdbe *pVdbe = (Vdbe*)pStmt;
62666   int v = pVdbe->aCounter[op-1];
62667   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
62668   return v;
62669 }
62670
62671 /************** End of vdbeapi.c *********************************************/
62672 /************** Begin file vdbetrace.c ***************************************/
62673 /*
62674 ** 2009 November 25
62675 **
62676 ** The author disclaims copyright to this source code.  In place of
62677 ** a legal notice, here is a blessing:
62678 **
62679 **    May you do good and not evil.
62680 **    May you find forgiveness for yourself and forgive others.
62681 **    May you share freely, never taking more than you give.
62682 **
62683 *************************************************************************
62684 **
62685 ** This file contains code used to insert the values of host parameters
62686 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
62687 **
62688 ** The Vdbe parse-tree explainer is also found here.
62689 */
62690
62691 #ifndef SQLITE_OMIT_TRACE
62692
62693 /*
62694 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
62695 ** bytes in this text up to but excluding the first character in
62696 ** a host parameter.  If the text contains no host parameters, return
62697 ** the total number of bytes in the text.
62698 */
62699 static int findNextHostParameter(const char *zSql, int *pnToken){
62700   int tokenType;
62701   int nTotal = 0;
62702   int n;
62703
62704   *pnToken = 0;
62705   while( zSql[0] ){
62706     n = sqlite3GetToken((u8*)zSql, &tokenType);
62707     assert( n>0 && tokenType!=TK_ILLEGAL );
62708     if( tokenType==TK_VARIABLE ){
62709       *pnToken = n;
62710       break;
62711     }
62712     nTotal += n;
62713     zSql += n;
62714   }
62715   return nTotal;
62716 }
62717
62718 /*
62719 ** This function returns a pointer to a nul-terminated string in memory
62720 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
62721 ** string contains a copy of zRawSql but with host parameters expanded to 
62722 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
62723 ** then the returned string holds a copy of zRawSql with "-- " prepended
62724 ** to each line of text.
62725 **
62726 ** The calling function is responsible for making sure the memory returned
62727 ** is eventually freed.
62728 **
62729 ** ALGORITHM:  Scan the input string looking for host parameters in any of
62730 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
62731 ** string literals, quoted identifier names, and comments.  For text forms,
62732 ** the host parameter index is found by scanning the perpared
62733 ** statement for the corresponding OP_Variable opcode.  Once the host
62734 ** parameter index is known, locate the value in p->aVar[].  Then render
62735 ** the value as a literal in place of the host parameter name.
62736 */
62737 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
62738   Vdbe *p,                 /* The prepared statement being evaluated */
62739   const char *zRawSql      /* Raw text of the SQL statement */
62740 ){
62741   sqlite3 *db;             /* The database connection */
62742   int idx = 0;             /* Index of a host parameter */
62743   int nextIndex = 1;       /* Index of next ? host parameter */
62744   int n;                   /* Length of a token prefix */
62745   int nToken;              /* Length of the parameter token */
62746   int i;                   /* Loop counter */
62747   Mem *pVar;               /* Value of a host parameter */
62748   StrAccum out;            /* Accumulate the output here */
62749   char zBase[100];         /* Initial working space */
62750
62751   db = p->db;
62752   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
62753                       db->aLimit[SQLITE_LIMIT_LENGTH]);
62754   out.db = db;
62755   if( db->vdbeExecCnt>1 ){
62756     while( *zRawSql ){
62757       const char *zStart = zRawSql;
62758       while( *(zRawSql++)!='\n' && *zRawSql );
62759       sqlite3StrAccumAppend(&out, "-- ", 3);
62760       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
62761     }
62762   }else{
62763     while( zRawSql[0] ){
62764       n = findNextHostParameter(zRawSql, &nToken);
62765       assert( n>0 );
62766       sqlite3StrAccumAppend(&out, zRawSql, n);
62767       zRawSql += n;
62768       assert( zRawSql[0] || nToken==0 );
62769       if( nToken==0 ) break;
62770       if( zRawSql[0]=='?' ){
62771         if( nToken>1 ){
62772           assert( sqlite3Isdigit(zRawSql[1]) );
62773           sqlite3GetInt32(&zRawSql[1], &idx);
62774         }else{
62775           idx = nextIndex;
62776         }
62777       }else{
62778         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
62779         testcase( zRawSql[0]==':' );
62780         testcase( zRawSql[0]=='$' );
62781         testcase( zRawSql[0]=='@' );
62782         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
62783         assert( idx>0 );
62784       }
62785       zRawSql += nToken;
62786       nextIndex = idx + 1;
62787       assert( idx>0 && idx<=p->nVar );
62788       pVar = &p->aVar[idx-1];
62789       if( pVar->flags & MEM_Null ){
62790         sqlite3StrAccumAppend(&out, "NULL", 4);
62791       }else if( pVar->flags & MEM_Int ){
62792         sqlite3XPrintf(&out, "%lld", pVar->u.i);
62793       }else if( pVar->flags & MEM_Real ){
62794         sqlite3XPrintf(&out, "%!.15g", pVar->r);
62795       }else if( pVar->flags & MEM_Str ){
62796 #ifndef SQLITE_OMIT_UTF16
62797         u8 enc = ENC(db);
62798         if( enc!=SQLITE_UTF8 ){
62799           Mem utf8;
62800           memset(&utf8, 0, sizeof(utf8));
62801           utf8.db = db;
62802           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
62803           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
62804           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
62805           sqlite3VdbeMemRelease(&utf8);
62806         }else
62807 #endif
62808         {
62809           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
62810         }
62811       }else if( pVar->flags & MEM_Zero ){
62812         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
62813       }else{
62814         assert( pVar->flags & MEM_Blob );
62815         sqlite3StrAccumAppend(&out, "x'", 2);
62816         for(i=0; i<pVar->n; i++){
62817           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
62818         }
62819         sqlite3StrAccumAppend(&out, "'", 1);
62820       }
62821     }
62822   }
62823   return sqlite3StrAccumFinish(&out);
62824 }
62825
62826 #endif /* #ifndef SQLITE_OMIT_TRACE */
62827
62828 /*****************************************************************************
62829 ** The following code implements the data-structure explaining logic
62830 ** for the Vdbe.
62831 */
62832
62833 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62834
62835 /*
62836 ** Allocate a new Explain object
62837 */
62838 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
62839   if( pVdbe ){
62840     Explain *p;
62841     sqlite3BeginBenignMalloc();
62842     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
62843     if( p ){
62844       p->pVdbe = pVdbe;
62845       sqlite3_free(pVdbe->pExplain);
62846       pVdbe->pExplain = p;
62847       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
62848                           SQLITE_MAX_LENGTH);
62849       p->str.useMalloc = 2;
62850     }else{
62851       sqlite3EndBenignMalloc();
62852     }
62853   }
62854 }
62855
62856 /*
62857 ** Return true if the Explain ends with a new-line.
62858 */
62859 static int endsWithNL(Explain *p){
62860   return p && p->str.zText && p->str.nChar
62861            && p->str.zText[p->str.nChar-1]=='\n';
62862 }
62863     
62864 /*
62865 ** Append text to the indentation
62866 */
62867 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
62868   Explain *p;
62869   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
62870     va_list ap;
62871     if( p->nIndent && endsWithNL(p) ){
62872       int n = p->nIndent;
62873       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
62874       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
62875     }   
62876     va_start(ap, zFormat);
62877     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
62878     va_end(ap);
62879   }
62880 }
62881
62882 /*
62883 ** Append a '\n' if there is not already one.
62884 */
62885 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
62886   Explain *p;
62887   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
62888     sqlite3StrAccumAppend(&p->str, "\n", 1);
62889   }
62890 }
62891
62892 /*
62893 ** Push a new indentation level.  Subsequent lines will be indented
62894 ** so that they begin at the current cursor position.
62895 */
62896 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
62897   Explain *p;
62898   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
62899     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
62900       const char *z = p->str.zText;
62901       int i = p->str.nChar-1;
62902       int x;
62903       while( i>=0 && z[i]!='\n' ){ i--; }
62904       x = (p->str.nChar - 1) - i;
62905       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
62906         x = p->aIndent[p->nIndent-1];
62907       }
62908       p->aIndent[p->nIndent] = x;
62909     }
62910     p->nIndent++;
62911   }
62912 }
62913
62914 /*
62915 ** Pop the indentation stack by one level.
62916 */
62917 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
62918   if( p && p->pExplain ) p->pExplain->nIndent--;
62919 }
62920
62921 /*
62922 ** Free the indentation structure
62923 */
62924 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
62925   if( pVdbe && pVdbe->pExplain ){
62926     sqlite3_free(pVdbe->zExplain);
62927     sqlite3ExplainNL(pVdbe);
62928     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
62929     sqlite3_free(pVdbe->pExplain);
62930     pVdbe->pExplain = 0;
62931     sqlite3EndBenignMalloc();
62932   }
62933 }
62934
62935 /*
62936 ** Return the explanation of a virtual machine.
62937 */
62938 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
62939   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
62940 }
62941 #endif /* defined(SQLITE_DEBUG) */
62942
62943 /************** End of vdbetrace.c *******************************************/
62944 /************** Begin file vdbe.c ********************************************/
62945 /*
62946 ** 2001 September 15
62947 **
62948 ** The author disclaims copyright to this source code.  In place of
62949 ** a legal notice, here is a blessing:
62950 **
62951 **    May you do good and not evil.
62952 **    May you find forgiveness for yourself and forgive others.
62953 **    May you share freely, never taking more than you give.
62954 **
62955 *************************************************************************
62956 ** The code in this file implements execution method of the 
62957 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
62958 ** handles housekeeping details such as creating and deleting
62959 ** VDBE instances.  This file is solely interested in executing
62960 ** the VDBE program.
62961 **
62962 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
62963 ** to a VDBE.
62964 **
62965 ** The SQL parser generates a program which is then executed by
62966 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
62967 ** similar in form to assembly language.  The program consists of
62968 ** a linear sequence of operations.  Each operation has an opcode 
62969 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
62970 ** is a null-terminated string.  Operand P5 is an unsigned character.
62971 ** Few opcodes use all 5 operands.
62972 **
62973 ** Computation results are stored on a set of registers numbered beginning
62974 ** with 1 and going up to Vdbe.nMem.  Each register can store
62975 ** either an integer, a null-terminated string, a floating point
62976 ** number, or the SQL "NULL" value.  An implicit conversion from one
62977 ** type to the other occurs as necessary.
62978 ** 
62979 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
62980 ** function which does the work of interpreting a VDBE program.
62981 ** But other routines are also provided to help in building up
62982 ** a program instruction by instruction.
62983 **
62984 ** Various scripts scan this source file in order to generate HTML
62985 ** documentation, headers files, or other derived files.  The formatting
62986 ** of the code in this file is, therefore, important.  See other comments
62987 ** in this file for details.  If in doubt, do not deviate from existing
62988 ** commenting and indentation practices when changing or adding code.
62989 */
62990
62991 /*
62992 ** Invoke this macro on memory cells just prior to changing the
62993 ** value of the cell.  This macro verifies that shallow copies are
62994 ** not misused.
62995 */
62996 #ifdef SQLITE_DEBUG
62997 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
62998 #else
62999 # define memAboutToChange(P,M)
63000 #endif
63001
63002 /*
63003 ** The following global variable is incremented every time a cursor
63004 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
63005 ** procedures use this information to make sure that indices are
63006 ** working correctly.  This variable has no function other than to
63007 ** help verify the correct operation of the library.
63008 */
63009 #ifdef SQLITE_TEST
63010 SQLITE_API int sqlite3_search_count = 0;
63011 #endif
63012
63013 /*
63014 ** When this global variable is positive, it gets decremented once before
63015 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
63016 ** field of the sqlite3 structure is set in order to simulate an interrupt.
63017 **
63018 ** This facility is used for testing purposes only.  It does not function
63019 ** in an ordinary build.
63020 */
63021 #ifdef SQLITE_TEST
63022 SQLITE_API int sqlite3_interrupt_count = 0;
63023 #endif
63024
63025 /*
63026 ** The next global variable is incremented each type the OP_Sort opcode
63027 ** is executed.  The test procedures use this information to make sure that
63028 ** sorting is occurring or not occurring at appropriate times.   This variable
63029 ** has no function other than to help verify the correct operation of the
63030 ** library.
63031 */
63032 #ifdef SQLITE_TEST
63033 SQLITE_API int sqlite3_sort_count = 0;
63034 #endif
63035
63036 /*
63037 ** The next global variable records the size of the largest MEM_Blob
63038 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
63039 ** use this information to make sure that the zero-blob functionality
63040 ** is working correctly.   This variable has no function other than to
63041 ** help verify the correct operation of the library.
63042 */
63043 #ifdef SQLITE_TEST
63044 SQLITE_API int sqlite3_max_blobsize = 0;
63045 static void updateMaxBlobsize(Mem *p){
63046   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
63047     sqlite3_max_blobsize = p->n;
63048   }
63049 }
63050 #endif
63051
63052 /*
63053 ** The next global variable is incremented each type the OP_Found opcode
63054 ** is executed. This is used to test whether or not the foreign key
63055 ** operation implemented using OP_FkIsZero is working. This variable
63056 ** has no function other than to help verify the correct operation of the
63057 ** library.
63058 */
63059 #ifdef SQLITE_TEST
63060 SQLITE_API int sqlite3_found_count = 0;
63061 #endif
63062
63063 /*
63064 ** Test a register to see if it exceeds the current maximum blob size.
63065 ** If it does, record the new maximum blob size.
63066 */
63067 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63068 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
63069 #else
63070 # define UPDATE_MAX_BLOBSIZE(P)
63071 #endif
63072
63073 /*
63074 ** Convert the given register into a string if it isn't one
63075 ** already. Return non-zero if a malloc() fails.
63076 */
63077 #define Stringify(P, enc) \
63078    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63079      { goto no_mem; }
63080
63081 /*
63082 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63083 ** a pointer to a dynamically allocated string where some other entity
63084 ** is responsible for deallocating that string.  Because the register
63085 ** does not control the string, it might be deleted without the register
63086 ** knowing it.
63087 **
63088 ** This routine converts an ephemeral string into a dynamically allocated
63089 ** string that the register itself controls.  In other words, it
63090 ** converts an MEM_Ephem string into an MEM_Dyn string.
63091 */
63092 #define Deephemeralize(P) \
63093    if( ((P)->flags&MEM_Ephem)!=0 \
63094        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63095
63096 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63097 #ifdef SQLITE_OMIT_MERGE_SORT
63098 # define isSorter(x) 0
63099 #else
63100 # define isSorter(x) ((x)->pSorter!=0)
63101 #endif
63102
63103 /*
63104 ** Argument pMem points at a register that will be passed to a
63105 ** user-defined function or returned to the user as the result of a query.
63106 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
63107 ** routines.
63108 */
63109 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63110   int flags = pMem->flags;
63111   if( flags & MEM_Null ){
63112     pMem->type = SQLITE_NULL;
63113   }
63114   else if( flags & MEM_Int ){
63115     pMem->type = SQLITE_INTEGER;
63116   }
63117   else if( flags & MEM_Real ){
63118     pMem->type = SQLITE_FLOAT;
63119   }
63120   else if( flags & MEM_Str ){
63121     pMem->type = SQLITE_TEXT;
63122   }else{
63123     pMem->type = SQLITE_BLOB;
63124   }
63125 }
63126
63127 /*
63128 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
63129 ** if we run out of memory.
63130 */
63131 static VdbeCursor *allocateCursor(
63132   Vdbe *p,              /* The virtual machine */
63133   int iCur,             /* Index of the new VdbeCursor */
63134   int nField,           /* Number of fields in the table or index */
63135   int iDb,              /* Database the cursor belongs to, or -1 */
63136   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
63137 ){
63138   /* Find the memory cell that will be used to store the blob of memory
63139   ** required for this VdbeCursor structure. It is convenient to use a 
63140   ** vdbe memory cell to manage the memory allocation required for a
63141   ** VdbeCursor structure for the following reasons:
63142   **
63143   **   * Sometimes cursor numbers are used for a couple of different
63144   **     purposes in a vdbe program. The different uses might require
63145   **     different sized allocations. Memory cells provide growable
63146   **     allocations.
63147   **
63148   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63149   **     be freed lazily via the sqlite3_release_memory() API. This
63150   **     minimizes the number of malloc calls made by the system.
63151   **
63152   ** Memory cells for cursors are allocated at the top of the address
63153   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63154   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63155   */
63156   Mem *pMem = &p->aMem[p->nMem-iCur];
63157
63158   int nByte;
63159   VdbeCursor *pCx = 0;
63160   nByte = 
63161       ROUND8(sizeof(VdbeCursor)) + 
63162       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
63163       2*nField*sizeof(u32);
63164
63165   assert( iCur<p->nCursor );
63166   if( p->apCsr[iCur] ){
63167     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63168     p->apCsr[iCur] = 0;
63169   }
63170   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63171     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63172     memset(pCx, 0, sizeof(VdbeCursor));
63173     pCx->iDb = iDb;
63174     pCx->nField = nField;
63175     if( nField ){
63176       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63177     }
63178     if( isBtreeCursor ){
63179       pCx->pCursor = (BtCursor*)
63180           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63181       sqlite3BtreeCursorZero(pCx->pCursor);
63182     }
63183   }
63184   return pCx;
63185 }
63186
63187 /*
63188 ** Try to convert a value into a numeric representation if we can
63189 ** do so without loss of information.  In other words, if the string
63190 ** looks like a number, convert it into a number.  If it does not
63191 ** look like a number, leave it alone.
63192 */
63193 static void applyNumericAffinity(Mem *pRec){
63194   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63195     double rValue;
63196     i64 iValue;
63197     u8 enc = pRec->enc;
63198     if( (pRec->flags&MEM_Str)==0 ) return;
63199     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63200     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63201       pRec->u.i = iValue;
63202       pRec->flags |= MEM_Int;
63203     }else{
63204       pRec->r = rValue;
63205       pRec->flags |= MEM_Real;
63206     }
63207   }
63208 }
63209
63210 /*
63211 ** Processing is determine by the affinity parameter:
63212 **
63213 ** SQLITE_AFF_INTEGER:
63214 ** SQLITE_AFF_REAL:
63215 ** SQLITE_AFF_NUMERIC:
63216 **    Try to convert pRec to an integer representation or a 
63217 **    floating-point representation if an integer representation
63218 **    is not possible.  Note that the integer representation is
63219 **    always preferred, even if the affinity is REAL, because
63220 **    an integer representation is more space efficient on disk.
63221 **
63222 ** SQLITE_AFF_TEXT:
63223 **    Convert pRec to a text representation.
63224 **
63225 ** SQLITE_AFF_NONE:
63226 **    No-op.  pRec is unchanged.
63227 */
63228 static void applyAffinity(
63229   Mem *pRec,          /* The value to apply affinity to */
63230   char affinity,      /* The affinity to be applied */
63231   u8 enc              /* Use this text encoding */
63232 ){
63233   if( affinity==SQLITE_AFF_TEXT ){
63234     /* Only attempt the conversion to TEXT if there is an integer or real
63235     ** representation (blob and NULL do not get converted) but no string
63236     ** representation.
63237     */
63238     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63239       sqlite3VdbeMemStringify(pRec, enc);
63240     }
63241     pRec->flags &= ~(MEM_Real|MEM_Int);
63242   }else if( affinity!=SQLITE_AFF_NONE ){
63243     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63244              || affinity==SQLITE_AFF_NUMERIC );
63245     applyNumericAffinity(pRec);
63246     if( pRec->flags & MEM_Real ){
63247       sqlite3VdbeIntegerAffinity(pRec);
63248     }
63249   }
63250 }
63251
63252 /*
63253 ** Try to convert the type of a function argument or a result column
63254 ** into a numeric representation.  Use either INTEGER or REAL whichever
63255 ** is appropriate.  But only do the conversion if it is possible without
63256 ** loss of information and return the revised type of the argument.
63257 */
63258 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63259   Mem *pMem = (Mem*)pVal;
63260   if( pMem->type==SQLITE_TEXT ){
63261     applyNumericAffinity(pMem);
63262     sqlite3VdbeMemStoreType(pMem);
63263   }
63264   return pMem->type;
63265 }
63266
63267 /*
63268 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
63269 ** not the internal Mem* type.
63270 */
63271 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63272   sqlite3_value *pVal, 
63273   u8 affinity, 
63274   u8 enc
63275 ){
63276   applyAffinity((Mem *)pVal, affinity, enc);
63277 }
63278
63279 #ifdef SQLITE_DEBUG
63280 /*
63281 ** Write a nice string representation of the contents of cell pMem
63282 ** into buffer zBuf, length nBuf.
63283 */
63284 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63285   char *zCsr = zBuf;
63286   int f = pMem->flags;
63287
63288   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63289
63290   if( f&MEM_Blob ){
63291     int i;
63292     char c;
63293     if( f & MEM_Dyn ){
63294       c = 'z';
63295       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63296     }else if( f & MEM_Static ){
63297       c = 't';
63298       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63299     }else if( f & MEM_Ephem ){
63300       c = 'e';
63301       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63302     }else{
63303       c = 's';
63304     }
63305
63306     sqlite3_snprintf(100, zCsr, "%c", c);
63307     zCsr += sqlite3Strlen30(zCsr);
63308     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63309     zCsr += sqlite3Strlen30(zCsr);
63310     for(i=0; i<16 && i<pMem->n; i++){
63311       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63312       zCsr += sqlite3Strlen30(zCsr);
63313     }
63314     for(i=0; i<16 && i<pMem->n; i++){
63315       char z = pMem->z[i];
63316       if( z<32 || z>126 ) *zCsr++ = '.';
63317       else *zCsr++ = z;
63318     }
63319
63320     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63321     zCsr += sqlite3Strlen30(zCsr);
63322     if( f & MEM_Zero ){
63323       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63324       zCsr += sqlite3Strlen30(zCsr);
63325     }
63326     *zCsr = '\0';
63327   }else if( f & MEM_Str ){
63328     int j, k;
63329     zBuf[0] = ' ';
63330     if( f & MEM_Dyn ){
63331       zBuf[1] = 'z';
63332       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63333     }else if( f & MEM_Static ){
63334       zBuf[1] = 't';
63335       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63336     }else if( f & MEM_Ephem ){
63337       zBuf[1] = 'e';
63338       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63339     }else{
63340       zBuf[1] = 's';
63341     }
63342     k = 2;
63343     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63344     k += sqlite3Strlen30(&zBuf[k]);
63345     zBuf[k++] = '[';
63346     for(j=0; j<15 && j<pMem->n; j++){
63347       u8 c = pMem->z[j];
63348       if( c>=0x20 && c<0x7f ){
63349         zBuf[k++] = c;
63350       }else{
63351         zBuf[k++] = '.';
63352       }
63353     }
63354     zBuf[k++] = ']';
63355     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63356     k += sqlite3Strlen30(&zBuf[k]);
63357     zBuf[k++] = 0;
63358   }
63359 }
63360 #endif
63361
63362 #ifdef SQLITE_DEBUG
63363 /*
63364 ** Print the value of a register for tracing purposes:
63365 */
63366 static void memTracePrint(FILE *out, Mem *p){
63367   if( p->flags & MEM_Null ){
63368     fprintf(out, " NULL");
63369   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63370     fprintf(out, " si:%lld", p->u.i);
63371   }else if( p->flags & MEM_Int ){
63372     fprintf(out, " i:%lld", p->u.i);
63373 #ifndef SQLITE_OMIT_FLOATING_POINT
63374   }else if( p->flags & MEM_Real ){
63375     fprintf(out, " r:%g", p->r);
63376 #endif
63377   }else if( p->flags & MEM_RowSet ){
63378     fprintf(out, " (rowset)");
63379   }else{
63380     char zBuf[200];
63381     sqlite3VdbeMemPrettyPrint(p, zBuf);
63382     fprintf(out, " ");
63383     fprintf(out, "%s", zBuf);
63384   }
63385 }
63386 static void registerTrace(FILE *out, int iReg, Mem *p){
63387   fprintf(out, "REG[%d] = ", iReg);
63388   memTracePrint(out, p);
63389   fprintf(out, "\n");
63390 }
63391 #endif
63392
63393 #ifdef SQLITE_DEBUG
63394 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
63395 #else
63396 #  define REGISTER_TRACE(R,M)
63397 #endif
63398
63399
63400 #ifdef VDBE_PROFILE
63401
63402 /* 
63403 ** hwtime.h contains inline assembler code for implementing 
63404 ** high-performance timing routines.
63405 */
63406 /************** Include hwtime.h in the middle of vdbe.c *********************/
63407 /************** Begin file hwtime.h ******************************************/
63408 /*
63409 ** 2008 May 27
63410 **
63411 ** The author disclaims copyright to this source code.  In place of
63412 ** a legal notice, here is a blessing:
63413 **
63414 **    May you do good and not evil.
63415 **    May you find forgiveness for yourself and forgive others.
63416 **    May you share freely, never taking more than you give.
63417 **
63418 ******************************************************************************
63419 **
63420 ** This file contains inline asm code for retrieving "high-performance"
63421 ** counters for x86 class CPUs.
63422 */
63423 #ifndef _HWTIME_H_
63424 #define _HWTIME_H_
63425
63426 /*
63427 ** The following routine only works on pentium-class (or newer) processors.
63428 ** It uses the RDTSC opcode to read the cycle count value out of the
63429 ** processor and returns that value.  This can be used for high-res
63430 ** profiling.
63431 */
63432 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
63433       (defined(i386) || defined(__i386__) || defined(_M_IX86))
63434
63435   #if defined(__GNUC__)
63436
63437   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63438      unsigned int lo, hi;
63439      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
63440      return (sqlite_uint64)hi << 32 | lo;
63441   }
63442
63443   #elif defined(_MSC_VER)
63444
63445   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
63446      __asm {
63447         rdtsc
63448         ret       ; return value at EDX:EAX
63449      }
63450   }
63451
63452   #endif
63453
63454 #elif (defined(__GNUC__) && defined(__x86_64__))
63455
63456   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63457       unsigned long val;
63458       __asm__ __volatile__ ("rdtsc" : "=A" (val));
63459       return val;
63460   }
63461  
63462 #elif (defined(__GNUC__) && defined(__ppc__))
63463
63464   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63465       unsigned long long retval;
63466       unsigned long junk;
63467       __asm__ __volatile__ ("\n\
63468           1:      mftbu   %1\n\
63469                   mftb    %L0\n\
63470                   mftbu   %0\n\
63471                   cmpw    %0,%1\n\
63472                   bne     1b"
63473                   : "=r" (retval), "=r" (junk));
63474       return retval;
63475   }
63476
63477 #else
63478
63479   #error Need implementation of sqlite3Hwtime() for your platform.
63480
63481   /*
63482   ** To compile without implementing sqlite3Hwtime() for your platform,
63483   ** you can remove the above #error and use the following
63484   ** stub function.  You will lose timing support for many
63485   ** of the debugging and testing utilities, but it should at
63486   ** least compile and run.
63487   */
63488 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
63489
63490 #endif
63491
63492 #endif /* !defined(_HWTIME_H_) */
63493
63494 /************** End of hwtime.h **********************************************/
63495 /************** Continuing where we left off in vdbe.c ***********************/
63496
63497 #endif
63498
63499 /*
63500 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
63501 ** sqlite3_interrupt() routine has been called.  If it has been, then
63502 ** processing of the VDBE program is interrupted.
63503 **
63504 ** This macro added to every instruction that does a jump in order to
63505 ** implement a loop.  This test used to be on every single instruction,
63506 ** but that meant we more testing than we needed.  By only testing the
63507 ** flag on jump instructions, we get a (small) speed improvement.
63508 */
63509 #define CHECK_FOR_INTERRUPT \
63510    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
63511
63512
63513 #ifndef NDEBUG
63514 /*
63515 ** This function is only called from within an assert() expression. It
63516 ** checks that the sqlite3.nTransaction variable is correctly set to
63517 ** the number of non-transaction savepoints currently in the 
63518 ** linked list starting at sqlite3.pSavepoint.
63519 ** 
63520 ** Usage:
63521 **
63522 **     assert( checkSavepointCount(db) );
63523 */
63524 static int checkSavepointCount(sqlite3 *db){
63525   int n = 0;
63526   Savepoint *p;
63527   for(p=db->pSavepoint; p; p=p->pNext) n++;
63528   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
63529   return 1;
63530 }
63531 #endif
63532
63533 /*
63534 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
63535 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
63536 ** in memory obtained from sqlite3DbMalloc).
63537 */
63538 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
63539   sqlite3 *db = p->db;
63540   sqlite3DbFree(db, p->zErrMsg);
63541   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
63542   sqlite3_free(pVtab->zErrMsg);
63543   pVtab->zErrMsg = 0;
63544 }
63545
63546
63547 /*
63548 ** Execute as much of a VDBE program as we can then return.
63549 **
63550 ** sqlite3VdbeMakeReady() must be called before this routine in order to
63551 ** close the program with a final OP_Halt and to set up the callbacks
63552 ** and the error message pointer.
63553 **
63554 ** Whenever a row or result data is available, this routine will either
63555 ** invoke the result callback (if there is one) or return with
63556 ** SQLITE_ROW.
63557 **
63558 ** If an attempt is made to open a locked database, then this routine
63559 ** will either invoke the busy callback (if there is one) or it will
63560 ** return SQLITE_BUSY.
63561 **
63562 ** If an error occurs, an error message is written to memory obtained
63563 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
63564 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
63565 **
63566 ** If the callback ever returns non-zero, then the program exits
63567 ** immediately.  There will be no error message but the p->rc field is
63568 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
63569 **
63570 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
63571 ** routine to return SQLITE_ERROR.
63572 **
63573 ** Other fatal errors return SQLITE_ERROR.
63574 **
63575 ** After this routine has finished, sqlite3VdbeFinalize() should be
63576 ** used to clean up the mess that was left behind.
63577 */
63578 SQLITE_PRIVATE int sqlite3VdbeExec(
63579   Vdbe *p                    /* The VDBE */
63580 ){
63581   int pc=0;                  /* The program counter */
63582   Op *aOp = p->aOp;          /* Copy of p->aOp */
63583   Op *pOp;                   /* Current operation */
63584   int rc = SQLITE_OK;        /* Value to return */
63585   sqlite3 *db = p->db;       /* The database */
63586   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
63587   u8 encoding = ENC(db);     /* The database encoding */
63588 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63589   int checkProgress;         /* True if progress callbacks are enabled */
63590   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
63591 #endif
63592   Mem *aMem = p->aMem;       /* Copy of p->aMem */
63593   Mem *pIn1 = 0;             /* 1st input operand */
63594   Mem *pIn2 = 0;             /* 2nd input operand */
63595   Mem *pIn3 = 0;             /* 3rd input operand */
63596   Mem *pOut = 0;             /* Output operand */
63597   int iCompare = 0;          /* Result of last OP_Compare operation */
63598   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
63599   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
63600 #ifdef VDBE_PROFILE
63601   u64 start;                 /* CPU clock count at start of opcode */
63602   int origPc;                /* Program counter at start of opcode */
63603 #endif
63604   /********************************************************************
63605   ** Automatically generated code
63606   **
63607   ** The following union is automatically generated by the
63608   ** vdbe-compress.tcl script.  The purpose of this union is to
63609   ** reduce the amount of stack space required by this function.
63610   ** See comments in the vdbe-compress.tcl script for details.
63611   */
63612   union vdbeExecUnion {
63613     struct OP_Yield_stack_vars {
63614       int pcDest;
63615     } aa;
63616     struct OP_Null_stack_vars {
63617       int cnt;
63618     } ab;
63619     struct OP_Variable_stack_vars {
63620       Mem *pVar;       /* Value being transferred */
63621     } ac;
63622     struct OP_Move_stack_vars {
63623       char *zMalloc;   /* Holding variable for allocated memory */
63624       int n;           /* Number of registers left to copy */
63625       int p1;          /* Register to copy from */
63626       int p2;          /* Register to copy to */
63627     } ad;
63628     struct OP_ResultRow_stack_vars {
63629       Mem *pMem;
63630       int i;
63631     } ae;
63632     struct OP_Concat_stack_vars {
63633       i64 nByte;
63634     } af;
63635     struct OP_Remainder_stack_vars {
63636       int flags;      /* Combined MEM_* flags from both inputs */
63637       i64 iA;         /* Integer value of left operand */
63638       i64 iB;         /* Integer value of right operand */
63639       double rA;      /* Real value of left operand */
63640       double rB;      /* Real value of right operand */
63641     } ag;
63642     struct OP_Function_stack_vars {
63643       int i;
63644       Mem *pArg;
63645       sqlite3_context ctx;
63646       sqlite3_value **apVal;
63647       int n;
63648     } ah;
63649     struct OP_ShiftRight_stack_vars {
63650       i64 iA;
63651       u64 uA;
63652       i64 iB;
63653       u8 op;
63654     } ai;
63655     struct OP_Ge_stack_vars {
63656       int res;            /* Result of the comparison of pIn1 against pIn3 */
63657       char affinity;      /* Affinity to use for comparison */
63658       u16 flags1;         /* Copy of initial value of pIn1->flags */
63659       u16 flags3;         /* Copy of initial value of pIn3->flags */
63660     } aj;
63661     struct OP_Compare_stack_vars {
63662       int n;
63663       int i;
63664       int p1;
63665       int p2;
63666       const KeyInfo *pKeyInfo;
63667       int idx;
63668       CollSeq *pColl;    /* Collating sequence to use on this term */
63669       int bRev;          /* True for DESCENDING sort order */
63670     } ak;
63671     struct OP_Or_stack_vars {
63672       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63673       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63674     } al;
63675     struct OP_IfNot_stack_vars {
63676       int c;
63677     } am;
63678     struct OP_Column_stack_vars {
63679       u32 payloadSize;   /* Number of bytes in the record */
63680       i64 payloadSize64; /* Number of bytes in the record */
63681       int p1;            /* P1 value of the opcode */
63682       int p2;            /* column number to retrieve */
63683       VdbeCursor *pC;    /* The VDBE cursor */
63684       char *zRec;        /* Pointer to complete record-data */
63685       BtCursor *pCrsr;   /* The BTree cursor */
63686       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
63687       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
63688       int nField;        /* number of fields in the record */
63689       int len;           /* The length of the serialized data for the column */
63690       int i;             /* Loop counter */
63691       char *zData;       /* Part of the record being decoded */
63692       Mem *pDest;        /* Where to write the extracted value */
63693       Mem sMem;          /* For storing the record being decoded */
63694       u8 *zIdx;          /* Index into header */
63695       u8 *zEndHdr;       /* Pointer to first byte after the header */
63696       u32 offset;        /* Offset into the data */
63697       u32 szField;       /* Number of bytes in the content of a field */
63698       int szHdr;         /* Size of the header size field at start of record */
63699       int avail;         /* Number of bytes of available data */
63700       u32 t;             /* A type code from the record header */
63701       Mem *pReg;         /* PseudoTable input register */
63702     } an;
63703     struct OP_Affinity_stack_vars {
63704       const char *zAffinity;   /* The affinity to be applied */
63705       char cAff;               /* A single character of affinity */
63706     } ao;
63707     struct OP_MakeRecord_stack_vars {
63708       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
63709       Mem *pRec;             /* The new record */
63710       u64 nData;             /* Number of bytes of data space */
63711       int nHdr;              /* Number of bytes of header space */
63712       i64 nByte;             /* Data space required for this record */
63713       int nZero;             /* Number of zero bytes at the end of the record */
63714       int nVarint;           /* Number of bytes in a varint */
63715       u32 serial_type;       /* Type field */
63716       Mem *pData0;           /* First field to be combined into the record */
63717       Mem *pLast;            /* Last field of the record */
63718       int nField;            /* Number of fields in the record */
63719       char *zAffinity;       /* The affinity string for the record */
63720       int file_format;       /* File format to use for encoding */
63721       int i;                 /* Space used in zNewRecord[] */
63722       int len;               /* Length of a field */
63723     } ap;
63724     struct OP_Count_stack_vars {
63725       i64 nEntry;
63726       BtCursor *pCrsr;
63727     } aq;
63728     struct OP_Savepoint_stack_vars {
63729       int p1;                         /* Value of P1 operand */
63730       char *zName;                    /* Name of savepoint */
63731       int nName;
63732       Savepoint *pNew;
63733       Savepoint *pSavepoint;
63734       Savepoint *pTmp;
63735       int iSavepoint;
63736       int ii;
63737     } ar;
63738     struct OP_AutoCommit_stack_vars {
63739       int desiredAutoCommit;
63740       int iRollback;
63741       int turnOnAC;
63742     } as;
63743     struct OP_Transaction_stack_vars {
63744       Btree *pBt;
63745     } at;
63746     struct OP_ReadCookie_stack_vars {
63747       int iMeta;
63748       int iDb;
63749       int iCookie;
63750     } au;
63751     struct OP_SetCookie_stack_vars {
63752       Db *pDb;
63753     } av;
63754     struct OP_VerifyCookie_stack_vars {
63755       int iMeta;
63756       int iGen;
63757       Btree *pBt;
63758     } aw;
63759     struct OP_OpenWrite_stack_vars {
63760       int nField;
63761       KeyInfo *pKeyInfo;
63762       int p2;
63763       int iDb;
63764       int wrFlag;
63765       Btree *pX;
63766       VdbeCursor *pCur;
63767       Db *pDb;
63768     } ax;
63769     struct OP_OpenEphemeral_stack_vars {
63770       VdbeCursor *pCx;
63771     } ay;
63772     struct OP_SorterOpen_stack_vars {
63773       VdbeCursor *pCx;
63774     } az;
63775     struct OP_OpenPseudo_stack_vars {
63776       VdbeCursor *pCx;
63777     } ba;
63778     struct OP_SeekGt_stack_vars {
63779       int res;
63780       int oc;
63781       VdbeCursor *pC;
63782       UnpackedRecord r;
63783       int nField;
63784       i64 iKey;      /* The rowid we are to seek to */
63785     } bb;
63786     struct OP_Seek_stack_vars {
63787       VdbeCursor *pC;
63788     } bc;
63789     struct OP_Found_stack_vars {
63790       int alreadyExists;
63791       VdbeCursor *pC;
63792       int res;
63793       char *pFree;
63794       UnpackedRecord *pIdxKey;
63795       UnpackedRecord r;
63796       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63797     } bd;
63798     struct OP_IsUnique_stack_vars {
63799       u16 ii;
63800       VdbeCursor *pCx;
63801       BtCursor *pCrsr;
63802       u16 nField;
63803       Mem *aMx;
63804       UnpackedRecord r;                  /* B-Tree index search key */
63805       i64 R;                             /* Rowid stored in register P3 */
63806     } be;
63807     struct OP_NotExists_stack_vars {
63808       VdbeCursor *pC;
63809       BtCursor *pCrsr;
63810       int res;
63811       u64 iKey;
63812     } bf;
63813     struct OP_NewRowid_stack_vars {
63814       i64 v;                 /* The new rowid */
63815       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63816       int res;               /* Result of an sqlite3BtreeLast() */
63817       int cnt;               /* Counter to limit the number of searches */
63818       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63819       VdbeFrame *pFrame;     /* Root frame of VDBE */
63820     } bg;
63821     struct OP_InsertInt_stack_vars {
63822       Mem *pData;       /* MEM cell holding data for the record to be inserted */
63823       Mem *pKey;        /* MEM cell holding key  for the record */
63824       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
63825       VdbeCursor *pC;   /* Cursor to table into which insert is written */
63826       int nZero;        /* Number of zero-bytes to append */
63827       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
63828       const char *zDb;  /* database name - used by the update hook */
63829       const char *zTbl; /* Table name - used by the opdate hook */
63830       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63831     } bh;
63832     struct OP_Delete_stack_vars {
63833       i64 iKey;
63834       VdbeCursor *pC;
63835     } bi;
63836     struct OP_SorterCompare_stack_vars {
63837       VdbeCursor *pC;
63838       int res;
63839     } bj;
63840     struct OP_SorterData_stack_vars {
63841       VdbeCursor *pC;
63842     } bk;
63843     struct OP_RowData_stack_vars {
63844       VdbeCursor *pC;
63845       BtCursor *pCrsr;
63846       u32 n;
63847       i64 n64;
63848     } bl;
63849     struct OP_Rowid_stack_vars {
63850       VdbeCursor *pC;
63851       i64 v;
63852       sqlite3_vtab *pVtab;
63853       const sqlite3_module *pModule;
63854     } bm;
63855     struct OP_NullRow_stack_vars {
63856       VdbeCursor *pC;
63857     } bn;
63858     struct OP_Last_stack_vars {
63859       VdbeCursor *pC;
63860       BtCursor *pCrsr;
63861       int res;
63862     } bo;
63863     struct OP_Rewind_stack_vars {
63864       VdbeCursor *pC;
63865       BtCursor *pCrsr;
63866       int res;
63867     } bp;
63868     struct OP_Next_stack_vars {
63869       VdbeCursor *pC;
63870       int res;
63871     } bq;
63872     struct OP_IdxInsert_stack_vars {
63873       VdbeCursor *pC;
63874       BtCursor *pCrsr;
63875       int nKey;
63876       const char *zKey;
63877     } br;
63878     struct OP_IdxDelete_stack_vars {
63879       VdbeCursor *pC;
63880       BtCursor *pCrsr;
63881       int res;
63882       UnpackedRecord r;
63883     } bs;
63884     struct OP_IdxRowid_stack_vars {
63885       BtCursor *pCrsr;
63886       VdbeCursor *pC;
63887       i64 rowid;
63888     } bt;
63889     struct OP_IdxGE_stack_vars {
63890       VdbeCursor *pC;
63891       int res;
63892       UnpackedRecord r;
63893     } bu;
63894     struct OP_Destroy_stack_vars {
63895       int iMoved;
63896       int iCnt;
63897       Vdbe *pVdbe;
63898       int iDb;
63899     } bv;
63900     struct OP_Clear_stack_vars {
63901       int nChange;
63902     } bw;
63903     struct OP_CreateTable_stack_vars {
63904       int pgno;
63905       int flags;
63906       Db *pDb;
63907     } bx;
63908     struct OP_ParseSchema_stack_vars {
63909       int iDb;
63910       const char *zMaster;
63911       char *zSql;
63912       InitData initData;
63913     } by;
63914     struct OP_IntegrityCk_stack_vars {
63915       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
63916       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
63917       int j;          /* Loop counter */
63918       int nErr;       /* Number of errors reported */
63919       char *z;        /* Text of the error report */
63920       Mem *pnErr;     /* Register keeping track of errors remaining */
63921     } bz;
63922     struct OP_RowSetRead_stack_vars {
63923       i64 val;
63924     } ca;
63925     struct OP_RowSetTest_stack_vars {
63926       int iSet;
63927       int exists;
63928     } cb;
63929     struct OP_Program_stack_vars {
63930       int nMem;               /* Number of memory registers for sub-program */
63931       int nByte;              /* Bytes of runtime space required for sub-program */
63932       Mem *pRt;               /* Register to allocate runtime space */
63933       Mem *pMem;              /* Used to iterate through memory cells */
63934       Mem *pEnd;              /* Last memory cell in new array */
63935       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
63936       SubProgram *pProgram;   /* Sub-program to execute */
63937       void *t;                /* Token identifying trigger */
63938     } cc;
63939     struct OP_Param_stack_vars {
63940       VdbeFrame *pFrame;
63941       Mem *pIn;
63942     } cd;
63943     struct OP_MemMax_stack_vars {
63944       Mem *pIn1;
63945       VdbeFrame *pFrame;
63946     } ce;
63947     struct OP_AggStep_stack_vars {
63948       int n;
63949       int i;
63950       Mem *pMem;
63951       Mem *pRec;
63952       sqlite3_context ctx;
63953       sqlite3_value **apVal;
63954     } cf;
63955     struct OP_AggFinal_stack_vars {
63956       Mem *pMem;
63957     } cg;
63958     struct OP_Checkpoint_stack_vars {
63959       int i;                          /* Loop counter */
63960       int aRes[3];                    /* Results */
63961       Mem *pMem;                      /* Write results here */
63962     } ch;
63963     struct OP_JournalMode_stack_vars {
63964       Btree *pBt;                     /* Btree to change journal mode of */
63965       Pager *pPager;                  /* Pager associated with pBt */
63966       int eNew;                       /* New journal mode */
63967       int eOld;                       /* The old journal mode */
63968       const char *zFilename;          /* Name of database file for pPager */
63969     } ci;
63970     struct OP_IncrVacuum_stack_vars {
63971       Btree *pBt;
63972     } cj;
63973     struct OP_VBegin_stack_vars {
63974       VTable *pVTab;
63975     } ck;
63976     struct OP_VOpen_stack_vars {
63977       VdbeCursor *pCur;
63978       sqlite3_vtab_cursor *pVtabCursor;
63979       sqlite3_vtab *pVtab;
63980       sqlite3_module *pModule;
63981     } cl;
63982     struct OP_VFilter_stack_vars {
63983       int nArg;
63984       int iQuery;
63985       const sqlite3_module *pModule;
63986       Mem *pQuery;
63987       Mem *pArgc;
63988       sqlite3_vtab_cursor *pVtabCursor;
63989       sqlite3_vtab *pVtab;
63990       VdbeCursor *pCur;
63991       int res;
63992       int i;
63993       Mem **apArg;
63994     } cm;
63995     struct OP_VColumn_stack_vars {
63996       sqlite3_vtab *pVtab;
63997       const sqlite3_module *pModule;
63998       Mem *pDest;
63999       sqlite3_context sContext;
64000     } cn;
64001     struct OP_VNext_stack_vars {
64002       sqlite3_vtab *pVtab;
64003       const sqlite3_module *pModule;
64004       int res;
64005       VdbeCursor *pCur;
64006     } co;
64007     struct OP_VRename_stack_vars {
64008       sqlite3_vtab *pVtab;
64009       Mem *pName;
64010     } cp;
64011     struct OP_VUpdate_stack_vars {
64012       sqlite3_vtab *pVtab;
64013       sqlite3_module *pModule;
64014       int nArg;
64015       int i;
64016       sqlite_int64 rowid;
64017       Mem **apArg;
64018       Mem *pX;
64019     } cq;
64020     struct OP_Trace_stack_vars {
64021       char *zTrace;
64022       char *z;
64023     } cr;
64024   } u;
64025   /* End automatically generated code
64026   ********************************************************************/
64027
64028   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
64029   sqlite3VdbeEnter(p);
64030   if( p->rc==SQLITE_NOMEM ){
64031     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64032     ** sqlite3_column_text16() failed.  */
64033     goto no_mem;
64034   }
64035   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
64036   p->rc = SQLITE_OK;
64037   assert( p->explain==0 );
64038   p->pResultSet = 0;
64039   db->busyHandler.nBusy = 0;
64040   CHECK_FOR_INTERRUPT;
64041   sqlite3VdbeIOTraceSql(p);
64042 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64043   checkProgress = db->xProgress!=0;
64044 #endif
64045 #ifdef SQLITE_DEBUG
64046   sqlite3BeginBenignMalloc();
64047   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64048     int i;
64049     printf("VDBE Program Listing:\n");
64050     sqlite3VdbePrintSql(p);
64051     for(i=0; i<p->nOp; i++){
64052       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64053     }
64054   }
64055   sqlite3EndBenignMalloc();
64056 #endif
64057   for(pc=p->pc; rc==SQLITE_OK; pc++){
64058     assert( pc>=0 && pc<p->nOp );
64059     if( db->mallocFailed ) goto no_mem;
64060 #ifdef VDBE_PROFILE
64061     origPc = pc;
64062     start = sqlite3Hwtime();
64063 #endif
64064     pOp = &aOp[pc];
64065
64066     /* Only allow tracing if SQLITE_DEBUG is defined.
64067     */
64068 #ifdef SQLITE_DEBUG
64069     if( p->trace ){
64070       if( pc==0 ){
64071         printf("VDBE Execution Trace:\n");
64072         sqlite3VdbePrintSql(p);
64073       }
64074       sqlite3VdbePrintOp(p->trace, pc, pOp);
64075     }
64076 #endif
64077       
64078
64079     /* Check to see if we need to simulate an interrupt.  This only happens
64080     ** if we have a special test build.
64081     */
64082 #ifdef SQLITE_TEST
64083     if( sqlite3_interrupt_count>0 ){
64084       sqlite3_interrupt_count--;
64085       if( sqlite3_interrupt_count==0 ){
64086         sqlite3_interrupt(db);
64087       }
64088     }
64089 #endif
64090
64091 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64092     /* Call the progress callback if it is configured and the required number
64093     ** of VDBE ops have been executed (either since this invocation of
64094     ** sqlite3VdbeExec() or since last time the progress callback was called).
64095     ** If the progress callback returns non-zero, exit the virtual machine with
64096     ** a return code SQLITE_ABORT.
64097     */
64098     if( checkProgress ){
64099       if( db->nProgressOps==nProgressOps ){
64100         int prc;
64101         prc = db->xProgress(db->pProgressArg);
64102         if( prc!=0 ){
64103           rc = SQLITE_INTERRUPT;
64104           goto vdbe_error_halt;
64105         }
64106         nProgressOps = 0;
64107       }
64108       nProgressOps++;
64109     }
64110 #endif
64111
64112     /* On any opcode with the "out2-prerelease" tag, free any
64113     ** external allocations out of mem[p2] and set mem[p2] to be
64114     ** an undefined integer.  Opcodes will either fill in the integer
64115     ** value or convert mem[p2] to a different type.
64116     */
64117     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64118     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64119       assert( pOp->p2>0 );
64120       assert( pOp->p2<=p->nMem );
64121       pOut = &aMem[pOp->p2];
64122       memAboutToChange(p, pOut);
64123       VdbeMemRelease(pOut);
64124       pOut->flags = MEM_Int;
64125     }
64126
64127     /* Sanity checking on other operands */
64128 #ifdef SQLITE_DEBUG
64129     if( (pOp->opflags & OPFLG_IN1)!=0 ){
64130       assert( pOp->p1>0 );
64131       assert( pOp->p1<=p->nMem );
64132       assert( memIsValid(&aMem[pOp->p1]) );
64133       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64134     }
64135     if( (pOp->opflags & OPFLG_IN2)!=0 ){
64136       assert( pOp->p2>0 );
64137       assert( pOp->p2<=p->nMem );
64138       assert( memIsValid(&aMem[pOp->p2]) );
64139       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64140     }
64141     if( (pOp->opflags & OPFLG_IN3)!=0 ){
64142       assert( pOp->p3>0 );
64143       assert( pOp->p3<=p->nMem );
64144       assert( memIsValid(&aMem[pOp->p3]) );
64145       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64146     }
64147     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64148       assert( pOp->p2>0 );
64149       assert( pOp->p2<=p->nMem );
64150       memAboutToChange(p, &aMem[pOp->p2]);
64151     }
64152     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64153       assert( pOp->p3>0 );
64154       assert( pOp->p3<=p->nMem );
64155       memAboutToChange(p, &aMem[pOp->p3]);
64156     }
64157 #endif
64158   
64159     switch( pOp->opcode ){
64160
64161 /*****************************************************************************
64162 ** What follows is a massive switch statement where each case implements a
64163 ** separate instruction in the virtual machine.  If we follow the usual
64164 ** indentation conventions, each case should be indented by 6 spaces.  But
64165 ** that is a lot of wasted space on the left margin.  So the code within
64166 ** the switch statement will break with convention and be flush-left. Another
64167 ** big comment (similar to this one) will mark the point in the code where
64168 ** we transition back to normal indentation.
64169 **
64170 ** The formatting of each case is important.  The makefile for SQLite
64171 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64172 ** file looking for lines that begin with "case OP_".  The opcodes.h files
64173 ** will be filled with #defines that give unique integer values to each
64174 ** opcode and the opcodes.c file is filled with an array of strings where
64175 ** each string is the symbolic name for the corresponding opcode.  If the
64176 ** case statement is followed by a comment of the form "/# same as ... #/"
64177 ** that comment is used to determine the particular value of the opcode.
64178 **
64179 ** Other keywords in the comment that follows each case are used to
64180 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64181 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
64182 ** the mkopcodeh.awk script for additional information.
64183 **
64184 ** Documentation about VDBE opcodes is generated by scanning this file
64185 ** for lines of that contain "Opcode:".  That line and all subsequent
64186 ** comment lines are used in the generation of the opcode.html documentation
64187 ** file.
64188 **
64189 ** SUMMARY:
64190 **
64191 **     Formatting is important to scripts that scan this file.
64192 **     Do not deviate from the formatting style currently in use.
64193 **
64194 *****************************************************************************/
64195
64196 /* Opcode:  Goto * P2 * * *
64197 **
64198 ** An unconditional jump to address P2.
64199 ** The next instruction executed will be 
64200 ** the one at index P2 from the beginning of
64201 ** the program.
64202 */
64203 case OP_Goto: {             /* jump */
64204   CHECK_FOR_INTERRUPT;
64205   pc = pOp->p2 - 1;
64206   break;
64207 }
64208
64209 /* Opcode:  Gosub P1 P2 * * *
64210 **
64211 ** Write the current address onto register P1
64212 ** and then jump to address P2.
64213 */
64214 case OP_Gosub: {            /* jump */
64215   assert( pOp->p1>0 && pOp->p1<=p->nMem );
64216   pIn1 = &aMem[pOp->p1];
64217   assert( (pIn1->flags & MEM_Dyn)==0 );
64218   memAboutToChange(p, pIn1);
64219   pIn1->flags = MEM_Int;
64220   pIn1->u.i = pc;
64221   REGISTER_TRACE(pOp->p1, pIn1);
64222   pc = pOp->p2 - 1;
64223   break;
64224 }
64225
64226 /* Opcode:  Return P1 * * * *
64227 **
64228 ** Jump to the next instruction after the address in register P1.
64229 */
64230 case OP_Return: {           /* in1 */
64231   pIn1 = &aMem[pOp->p1];
64232   assert( pIn1->flags & MEM_Int );
64233   pc = (int)pIn1->u.i;
64234   break;
64235 }
64236
64237 /* Opcode:  Yield P1 * * * *
64238 **
64239 ** Swap the program counter with the value in register P1.
64240 */
64241 case OP_Yield: {            /* in1 */
64242 #if 0  /* local variables moved into u.aa */
64243   int pcDest;
64244 #endif /* local variables moved into u.aa */
64245   pIn1 = &aMem[pOp->p1];
64246   assert( (pIn1->flags & MEM_Dyn)==0 );
64247   pIn1->flags = MEM_Int;
64248   u.aa.pcDest = (int)pIn1->u.i;
64249   pIn1->u.i = pc;
64250   REGISTER_TRACE(pOp->p1, pIn1);
64251   pc = u.aa.pcDest;
64252   break;
64253 }
64254
64255 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
64256 **
64257 ** Check the value in register P3.  If it is NULL then Halt using
64258 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
64259 ** value in register P3 is not NULL, then this routine is a no-op.
64260 */
64261 case OP_HaltIfNull: {      /* in3 */
64262   pIn3 = &aMem[pOp->p3];
64263   if( (pIn3->flags & MEM_Null)==0 ) break;
64264   /* Fall through into OP_Halt */
64265 }
64266
64267 /* Opcode:  Halt P1 P2 * P4 *
64268 **
64269 ** Exit immediately.  All open cursors, etc are closed
64270 ** automatically.
64271 **
64272 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64273 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
64274 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
64275 ** whether or not to rollback the current transaction.  Do not rollback
64276 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
64277 ** then back out all changes that have occurred during this execution of the
64278 ** VDBE, but do not rollback the transaction. 
64279 **
64280 ** If P4 is not null then it is an error message string.
64281 **
64282 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64283 ** every program.  So a jump past the last instruction of the program
64284 ** is the same as executing Halt.
64285 */
64286 case OP_Halt: {
64287   if( pOp->p1==SQLITE_OK && p->pFrame ){
64288     /* Halt the sub-program. Return control to the parent frame. */
64289     VdbeFrame *pFrame = p->pFrame;
64290     p->pFrame = pFrame->pParent;
64291     p->nFrame--;
64292     sqlite3VdbeSetChanges(db, p->nChange);
64293     pc = sqlite3VdbeFrameRestore(pFrame);
64294     lastRowid = db->lastRowid;
64295     if( pOp->p2==OE_Ignore ){
64296       /* Instruction pc is the OP_Program that invoked the sub-program 
64297       ** currently being halted. If the p2 instruction of this OP_Halt
64298       ** instruction is set to OE_Ignore, then the sub-program is throwing
64299       ** an IGNORE exception. In this case jump to the address specified
64300       ** as the p2 of the calling OP_Program.  */
64301       pc = p->aOp[pc].p2-1;
64302     }
64303     aOp = p->aOp;
64304     aMem = p->aMem;
64305     break;
64306   }
64307
64308   p->rc = pOp->p1;
64309   p->errorAction = (u8)pOp->p2;
64310   p->pc = pc;
64311   if( pOp->p4.z ){
64312     assert( p->rc!=SQLITE_OK );
64313     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64314     testcase( sqlite3GlobalConfig.xLog!=0 );
64315     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64316   }else if( p->rc ){
64317     testcase( sqlite3GlobalConfig.xLog!=0 );
64318     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64319   }
64320   rc = sqlite3VdbeHalt(p);
64321   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64322   if( rc==SQLITE_BUSY ){
64323     p->rc = rc = SQLITE_BUSY;
64324   }else{
64325     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
64326     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64327     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64328   }
64329   goto vdbe_return;
64330 }
64331
64332 /* Opcode: Integer P1 P2 * * *
64333 **
64334 ** The 32-bit integer value P1 is written into register P2.
64335 */
64336 case OP_Integer: {         /* out2-prerelease */
64337   pOut->u.i = pOp->p1;
64338   break;
64339 }
64340
64341 /* Opcode: Int64 * P2 * P4 *
64342 **
64343 ** P4 is a pointer to a 64-bit integer value.
64344 ** Write that value into register P2.
64345 */
64346 case OP_Int64: {           /* out2-prerelease */
64347   assert( pOp->p4.pI64!=0 );
64348   pOut->u.i = *pOp->p4.pI64;
64349   break;
64350 }
64351
64352 #ifndef SQLITE_OMIT_FLOATING_POINT
64353 /* Opcode: Real * P2 * P4 *
64354 **
64355 ** P4 is a pointer to a 64-bit floating point value.
64356 ** Write that value into register P2.
64357 */
64358 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
64359   pOut->flags = MEM_Real;
64360   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64361   pOut->r = *pOp->p4.pReal;
64362   break;
64363 }
64364 #endif
64365
64366 /* Opcode: String8 * P2 * P4 *
64367 **
64368 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
64369 ** into an OP_String before it is executed for the first time.
64370 */
64371 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
64372   assert( pOp->p4.z!=0 );
64373   pOp->opcode = OP_String;
64374   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
64375
64376 #ifndef SQLITE_OMIT_UTF16
64377   if( encoding!=SQLITE_UTF8 ){
64378     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
64379     if( rc==SQLITE_TOOBIG ) goto too_big;
64380     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
64381     assert( pOut->zMalloc==pOut->z );
64382     assert( pOut->flags & MEM_Dyn );
64383     pOut->zMalloc = 0;
64384     pOut->flags |= MEM_Static;
64385     pOut->flags &= ~MEM_Dyn;
64386     if( pOp->p4type==P4_DYNAMIC ){
64387       sqlite3DbFree(db, pOp->p4.z);
64388     }
64389     pOp->p4type = P4_DYNAMIC;
64390     pOp->p4.z = pOut->z;
64391     pOp->p1 = pOut->n;
64392   }
64393 #endif
64394   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64395     goto too_big;
64396   }
64397   /* Fall through to the next case, OP_String */
64398 }
64399   
64400 /* Opcode: String P1 P2 * P4 *
64401 **
64402 ** The string value P4 of length P1 (bytes) is stored in register P2.
64403 */
64404 case OP_String: {          /* out2-prerelease */
64405   assert( pOp->p4.z!=0 );
64406   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64407   pOut->z = pOp->p4.z;
64408   pOut->n = pOp->p1;
64409   pOut->enc = encoding;
64410   UPDATE_MAX_BLOBSIZE(pOut);
64411   break;
64412 }
64413
64414 /* Opcode: Null * P2 P3 * *
64415 **
64416 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
64417 ** NULL into register P3 and ever register in between P2 and P3.  If P3
64418 ** is less than P2 (typically P3 is zero) then only register P2 is
64419 ** set to NULL
64420 */
64421 case OP_Null: {           /* out2-prerelease */
64422 #if 0  /* local variables moved into u.ab */
64423   int cnt;
64424 #endif /* local variables moved into u.ab */
64425   u.ab.cnt = pOp->p3-pOp->p2;
64426   assert( pOp->p3<=p->nMem );
64427   pOut->flags = MEM_Null;
64428   while( u.ab.cnt>0 ){
64429     pOut++;
64430     memAboutToChange(p, pOut);
64431     VdbeMemRelease(pOut);
64432     pOut->flags = MEM_Null;
64433     u.ab.cnt--;
64434   }
64435   break;
64436 }
64437
64438
64439 /* Opcode: Blob P1 P2 * P4
64440 **
64441 ** P4 points to a blob of data P1 bytes long.  Store this
64442 ** blob in register P2.
64443 */
64444 case OP_Blob: {                /* out2-prerelease */
64445   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
64446   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
64447   pOut->enc = encoding;
64448   UPDATE_MAX_BLOBSIZE(pOut);
64449   break;
64450 }
64451
64452 /* Opcode: Variable P1 P2 * P4 *
64453 **
64454 ** Transfer the values of bound parameter P1 into register P2
64455 **
64456 ** If the parameter is named, then its name appears in P4 and P3==1.
64457 ** The P4 value is used by sqlite3_bind_parameter_name().
64458 */
64459 case OP_Variable: {            /* out2-prerelease */
64460 #if 0  /* local variables moved into u.ac */
64461   Mem *pVar;       /* Value being transferred */
64462 #endif /* local variables moved into u.ac */
64463
64464   assert( pOp->p1>0 && pOp->p1<=p->nVar );
64465   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
64466   u.ac.pVar = &p->aVar[pOp->p1 - 1];
64467   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
64468     goto too_big;
64469   }
64470   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
64471   UPDATE_MAX_BLOBSIZE(pOut);
64472   break;
64473 }
64474
64475 /* Opcode: Move P1 P2 P3 * *
64476 **
64477 ** Move the values in register P1..P1+P3-1 over into
64478 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
64479 ** left holding a NULL.  It is an error for register ranges
64480 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
64481 */
64482 case OP_Move: {
64483 #if 0  /* local variables moved into u.ad */
64484   char *zMalloc;   /* Holding variable for allocated memory */
64485   int n;           /* Number of registers left to copy */
64486   int p1;          /* Register to copy from */
64487   int p2;          /* Register to copy to */
64488 #endif /* local variables moved into u.ad */
64489
64490   u.ad.n = pOp->p3;
64491   u.ad.p1 = pOp->p1;
64492   u.ad.p2 = pOp->p2;
64493   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
64494   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
64495
64496   pIn1 = &aMem[u.ad.p1];
64497   pOut = &aMem[u.ad.p2];
64498   while( u.ad.n-- ){
64499     assert( pOut<=&aMem[p->nMem] );
64500     assert( pIn1<=&aMem[p->nMem] );
64501     assert( memIsValid(pIn1) );
64502     memAboutToChange(p, pOut);
64503     u.ad.zMalloc = pOut->zMalloc;
64504     pOut->zMalloc = 0;
64505     sqlite3VdbeMemMove(pOut, pIn1);
64506 #ifdef SQLITE_DEBUG
64507     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
64508       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
64509     }
64510 #endif
64511     pIn1->zMalloc = u.ad.zMalloc;
64512     REGISTER_TRACE(u.ad.p2++, pOut);
64513     pIn1++;
64514     pOut++;
64515   }
64516   break;
64517 }
64518
64519 /* Opcode: Copy P1 P2 * * *
64520 **
64521 ** Make a copy of register P1 into register P2.
64522 **
64523 ** This instruction makes a deep copy of the value.  A duplicate
64524 ** is made of any string or blob constant.  See also OP_SCopy.
64525 */
64526 case OP_Copy: {             /* in1, out2 */
64527   pIn1 = &aMem[pOp->p1];
64528   pOut = &aMem[pOp->p2];
64529   assert( pOut!=pIn1 );
64530   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64531   Deephemeralize(pOut);
64532   REGISTER_TRACE(pOp->p2, pOut);
64533   break;
64534 }
64535
64536 /* Opcode: SCopy P1 P2 * * *
64537 **
64538 ** Make a shallow copy of register P1 into register P2.
64539 **
64540 ** This instruction makes a shallow copy of the value.  If the value
64541 ** is a string or blob, then the copy is only a pointer to the
64542 ** original and hence if the original changes so will the copy.
64543 ** Worse, if the original is deallocated, the copy becomes invalid.
64544 ** Thus the program must guarantee that the original will not change
64545 ** during the lifetime of the copy.  Use OP_Copy to make a complete
64546 ** copy.
64547 */
64548 case OP_SCopy: {            /* in1, out2 */
64549   pIn1 = &aMem[pOp->p1];
64550   pOut = &aMem[pOp->p2];
64551   assert( pOut!=pIn1 );
64552   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64553 #ifdef SQLITE_DEBUG
64554   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
64555 #endif
64556   REGISTER_TRACE(pOp->p2, pOut);
64557   break;
64558 }
64559
64560 /* Opcode: ResultRow P1 P2 * * *
64561 **
64562 ** The registers P1 through P1+P2-1 contain a single row of
64563 ** results. This opcode causes the sqlite3_step() call to terminate
64564 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
64565 ** structure to provide access to the top P1 values as the result
64566 ** row.
64567 */
64568 case OP_ResultRow: {
64569 #if 0  /* local variables moved into u.ae */
64570   Mem *pMem;
64571   int i;
64572 #endif /* local variables moved into u.ae */
64573   assert( p->nResColumn==pOp->p2 );
64574   assert( pOp->p1>0 );
64575   assert( pOp->p1+pOp->p2<=p->nMem+1 );
64576
64577   /* If this statement has violated immediate foreign key constraints, do
64578   ** not return the number of rows modified. And do not RELEASE the statement
64579   ** transaction. It needs to be rolled back.  */
64580   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
64581     assert( db->flags&SQLITE_CountRows );
64582     assert( p->usesStmtJournal );
64583     break;
64584   }
64585
64586   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
64587   ** DML statements invoke this opcode to return the number of rows
64588   ** modified to the user. This is the only way that a VM that
64589   ** opens a statement transaction may invoke this opcode.
64590   **
64591   ** In case this is such a statement, close any statement transaction
64592   ** opened by this VM before returning control to the user. This is to
64593   ** ensure that statement-transactions are always nested, not overlapping.
64594   ** If the open statement-transaction is not closed here, then the user
64595   ** may step another VM that opens its own statement transaction. This
64596   ** may lead to overlapping statement transactions.
64597   **
64598   ** The statement transaction is never a top-level transaction.  Hence
64599   ** the RELEASE call below can never fail.
64600   */
64601   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
64602   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
64603   if( NEVER(rc!=SQLITE_OK) ){
64604     break;
64605   }
64606
64607   /* Invalidate all ephemeral cursor row caches */
64608   p->cacheCtr = (p->cacheCtr + 2)|1;
64609
64610   /* Make sure the results of the current row are \000 terminated
64611   ** and have an assigned type.  The results are de-ephemeralized as
64612   ** a side effect.
64613   */
64614   u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
64615   for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
64616     assert( memIsValid(&u.ae.pMem[u.ae.i]) );
64617     Deephemeralize(&u.ae.pMem[u.ae.i]);
64618     assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
64619             || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
64620     sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
64621     sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
64622     REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
64623   }
64624   if( db->mallocFailed ) goto no_mem;
64625
64626   /* Return SQLITE_ROW
64627   */
64628   p->pc = pc + 1;
64629   rc = SQLITE_ROW;
64630   goto vdbe_return;
64631 }
64632
64633 /* Opcode: Concat P1 P2 P3 * *
64634 **
64635 ** Add the text in register P1 onto the end of the text in
64636 ** register P2 and store the result in register P3.
64637 ** If either the P1 or P2 text are NULL then store NULL in P3.
64638 **
64639 **   P3 = P2 || P1
64640 **
64641 ** It is illegal for P1 and P3 to be the same register. Sometimes,
64642 ** if P3 is the same register as P2, the implementation is able
64643 ** to avoid a memcpy().
64644 */
64645 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
64646 #if 0  /* local variables moved into u.af */
64647   i64 nByte;
64648 #endif /* local variables moved into u.af */
64649
64650   pIn1 = &aMem[pOp->p1];
64651   pIn2 = &aMem[pOp->p2];
64652   pOut = &aMem[pOp->p3];
64653   assert( pIn1!=pOut );
64654   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64655     sqlite3VdbeMemSetNull(pOut);
64656     break;
64657   }
64658   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
64659   Stringify(pIn1, encoding);
64660   Stringify(pIn2, encoding);
64661   u.af.nByte = pIn1->n + pIn2->n;
64662   if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64663     goto too_big;
64664   }
64665   MemSetTypeFlag(pOut, MEM_Str);
64666   if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
64667     goto no_mem;
64668   }
64669   if( pOut!=pIn2 ){
64670     memcpy(pOut->z, pIn2->z, pIn2->n);
64671   }
64672   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
64673   pOut->z[u.af.nByte] = 0;
64674   pOut->z[u.af.nByte+1] = 0;
64675   pOut->flags |= MEM_Term;
64676   pOut->n = (int)u.af.nByte;
64677   pOut->enc = encoding;
64678   UPDATE_MAX_BLOBSIZE(pOut);
64679   break;
64680 }
64681
64682 /* Opcode: Add P1 P2 P3 * *
64683 **
64684 ** Add the value in register P1 to the value in register P2
64685 ** and store the result in register P3.
64686 ** If either input is NULL, the result is NULL.
64687 */
64688 /* Opcode: Multiply P1 P2 P3 * *
64689 **
64690 **
64691 ** Multiply the value in register P1 by the value in register P2
64692 ** and store the result in register P3.
64693 ** If either input is NULL, the result is NULL.
64694 */
64695 /* Opcode: Subtract P1 P2 P3 * *
64696 **
64697 ** Subtract the value in register P1 from the value in register P2
64698 ** and store the result in register P3.
64699 ** If either input is NULL, the result is NULL.
64700 */
64701 /* Opcode: Divide P1 P2 P3 * *
64702 **
64703 ** Divide the value in register P1 by the value in register P2
64704 ** and store the result in register P3 (P3=P2/P1). If the value in 
64705 ** register P1 is zero, then the result is NULL. If either input is 
64706 ** NULL, the result is NULL.
64707 */
64708 /* Opcode: Remainder P1 P2 P3 * *
64709 **
64710 ** Compute the remainder after integer division of the value in
64711 ** register P1 by the value in register P2 and store the result in P3. 
64712 ** If the value in register P2 is zero the result is NULL.
64713 ** If either operand is NULL, the result is NULL.
64714 */
64715 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
64716 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
64717 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
64718 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
64719 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
64720 #if 0  /* local variables moved into u.ag */
64721   int flags;      /* Combined MEM_* flags from both inputs */
64722   i64 iA;         /* Integer value of left operand */
64723   i64 iB;         /* Integer value of right operand */
64724   double rA;      /* Real value of left operand */
64725   double rB;      /* Real value of right operand */
64726 #endif /* local variables moved into u.ag */
64727
64728   pIn1 = &aMem[pOp->p1];
64729   applyNumericAffinity(pIn1);
64730   pIn2 = &aMem[pOp->p2];
64731   applyNumericAffinity(pIn2);
64732   pOut = &aMem[pOp->p3];
64733   u.ag.flags = pIn1->flags | pIn2->flags;
64734   if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
64735   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
64736     u.ag.iA = pIn1->u.i;
64737     u.ag.iB = pIn2->u.i;
64738     switch( pOp->opcode ){
64739       case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
64740       case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
64741       case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
64742       case OP_Divide: {
64743         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
64744         if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
64745         u.ag.iB /= u.ag.iA;
64746         break;
64747       }
64748       default: {
64749         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
64750         if( u.ag.iA==-1 ) u.ag.iA = 1;
64751         u.ag.iB %= u.ag.iA;
64752         break;
64753       }
64754     }
64755     pOut->u.i = u.ag.iB;
64756     MemSetTypeFlag(pOut, MEM_Int);
64757   }else{
64758 fp_math:
64759     u.ag.rA = sqlite3VdbeRealValue(pIn1);
64760     u.ag.rB = sqlite3VdbeRealValue(pIn2);
64761     switch( pOp->opcode ){
64762       case OP_Add:         u.ag.rB += u.ag.rA;       break;
64763       case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
64764       case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
64765       case OP_Divide: {
64766         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
64767         if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
64768         u.ag.rB /= u.ag.rA;
64769         break;
64770       }
64771       default: {
64772         u.ag.iA = (i64)u.ag.rA;
64773         u.ag.iB = (i64)u.ag.rB;
64774         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
64775         if( u.ag.iA==-1 ) u.ag.iA = 1;
64776         u.ag.rB = (double)(u.ag.iB % u.ag.iA);
64777         break;
64778       }
64779     }
64780 #ifdef SQLITE_OMIT_FLOATING_POINT
64781     pOut->u.i = u.ag.rB;
64782     MemSetTypeFlag(pOut, MEM_Int);
64783 #else
64784     if( sqlite3IsNaN(u.ag.rB) ){
64785       goto arithmetic_result_is_null;
64786     }
64787     pOut->r = u.ag.rB;
64788     MemSetTypeFlag(pOut, MEM_Real);
64789     if( (u.ag.flags & MEM_Real)==0 ){
64790       sqlite3VdbeIntegerAffinity(pOut);
64791     }
64792 #endif
64793   }
64794   break;
64795
64796 arithmetic_result_is_null:
64797   sqlite3VdbeMemSetNull(pOut);
64798   break;
64799 }
64800
64801 /* Opcode: CollSeq P1 * * P4
64802 **
64803 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
64804 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
64805 ** be returned. This is used by the built-in min(), max() and nullif()
64806 ** functions.
64807 **
64808 ** If P1 is not zero, then it is a register that a subsequent min() or
64809 ** max() aggregate will set to 1 if the current row is not the minimum or
64810 ** maximum.  The P1 register is initialized to 0 by this instruction.
64811 **
64812 ** The interface used by the implementation of the aforementioned functions
64813 ** to retrieve the collation sequence set by this opcode is not available
64814 ** publicly, only to user functions defined in func.c.
64815 */
64816 case OP_CollSeq: {
64817   assert( pOp->p4type==P4_COLLSEQ );
64818   if( pOp->p1 ){
64819     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
64820   }
64821   break;
64822 }
64823
64824 /* Opcode: Function P1 P2 P3 P4 P5
64825 **
64826 ** Invoke a user function (P4 is a pointer to a Function structure that
64827 ** defines the function) with P5 arguments taken from register P2 and
64828 ** successors.  The result of the function is stored in register P3.
64829 ** Register P3 must not be one of the function inputs.
64830 **
64831 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
64832 ** function was determined to be constant at compile time. If the first
64833 ** argument was constant then bit 0 of P1 is set. This is used to determine
64834 ** whether meta data associated with a user function argument using the
64835 ** sqlite3_set_auxdata() API may be safely retained until the next
64836 ** invocation of this opcode.
64837 **
64838 ** See also: AggStep and AggFinal
64839 */
64840 case OP_Function: {
64841 #if 0  /* local variables moved into u.ah */
64842   int i;
64843   Mem *pArg;
64844   sqlite3_context ctx;
64845   sqlite3_value **apVal;
64846   int n;
64847 #endif /* local variables moved into u.ah */
64848
64849   u.ah.n = pOp->p5;
64850   u.ah.apVal = p->apArg;
64851   assert( u.ah.apVal || u.ah.n==0 );
64852   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64853   pOut = &aMem[pOp->p3];
64854   memAboutToChange(p, pOut);
64855
64856   assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
64857   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
64858   u.ah.pArg = &aMem[pOp->p2];
64859   for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
64860     assert( memIsValid(u.ah.pArg) );
64861     u.ah.apVal[u.ah.i] = u.ah.pArg;
64862     Deephemeralize(u.ah.pArg);
64863     sqlite3VdbeMemStoreType(u.ah.pArg);
64864     REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
64865   }
64866
64867   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
64868   if( pOp->p4type==P4_FUNCDEF ){
64869     u.ah.ctx.pFunc = pOp->p4.pFunc;
64870     u.ah.ctx.pVdbeFunc = 0;
64871   }else{
64872     u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
64873     u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
64874   }
64875
64876   u.ah.ctx.s.flags = MEM_Null;
64877   u.ah.ctx.s.db = db;
64878   u.ah.ctx.s.xDel = 0;
64879   u.ah.ctx.s.zMalloc = 0;
64880
64881   /* The output cell may already have a buffer allocated. Move
64882   ** the pointer to u.ah.ctx.s so in case the user-function can use
64883   ** the already allocated buffer instead of allocating a new one.
64884   */
64885   sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
64886   MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
64887
64888   u.ah.ctx.isError = 0;
64889   if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
64890     assert( pOp>aOp );
64891     assert( pOp[-1].p4type==P4_COLLSEQ );
64892     assert( pOp[-1].opcode==OP_CollSeq );
64893     u.ah.ctx.pColl = pOp[-1].p4.pColl;
64894   }
64895   db->lastRowid = lastRowid;
64896   (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
64897   lastRowid = db->lastRowid;
64898
64899   /* If any auxiliary data functions have been called by this user function,
64900   ** immediately call the destructor for any non-static values.
64901   */
64902   if( u.ah.ctx.pVdbeFunc ){
64903     sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
64904     pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
64905     pOp->p4type = P4_VDBEFUNC;
64906   }
64907
64908   if( db->mallocFailed ){
64909     /* Even though a malloc() has failed, the implementation of the
64910     ** user function may have called an sqlite3_result_XXX() function
64911     ** to return a value. The following call releases any resources
64912     ** associated with such a value.
64913     */
64914     sqlite3VdbeMemRelease(&u.ah.ctx.s);
64915     goto no_mem;
64916   }
64917
64918   /* If the function returned an error, throw an exception */
64919   if( u.ah.ctx.isError ){
64920     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
64921     rc = u.ah.ctx.isError;
64922   }
64923
64924   /* Copy the result of the function into register P3 */
64925   sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
64926   sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
64927   if( sqlite3VdbeMemTooBig(pOut) ){
64928     goto too_big;
64929   }
64930
64931 #if 0
64932   /* The app-defined function has done something that as caused this
64933   ** statement to expire.  (Perhaps the function called sqlite3_exec()
64934   ** with a CREATE TABLE statement.)
64935   */
64936   if( p->expired ) rc = SQLITE_ABORT;
64937 #endif
64938
64939   REGISTER_TRACE(pOp->p3, pOut);
64940   UPDATE_MAX_BLOBSIZE(pOut);
64941   break;
64942 }
64943
64944 /* Opcode: BitAnd P1 P2 P3 * *
64945 **
64946 ** Take the bit-wise AND of the values in register P1 and P2 and
64947 ** store the result in register P3.
64948 ** If either input is NULL, the result is NULL.
64949 */
64950 /* Opcode: BitOr P1 P2 P3 * *
64951 **
64952 ** Take the bit-wise OR of the values in register P1 and P2 and
64953 ** store the result in register P3.
64954 ** If either input is NULL, the result is NULL.
64955 */
64956 /* Opcode: ShiftLeft P1 P2 P3 * *
64957 **
64958 ** Shift the integer value in register P2 to the left by the
64959 ** number of bits specified by the integer in register P1.
64960 ** Store the result in register P3.
64961 ** If either input is NULL, the result is NULL.
64962 */
64963 /* Opcode: ShiftRight P1 P2 P3 * *
64964 **
64965 ** Shift the integer value in register P2 to the right by the
64966 ** number of bits specified by the integer in register P1.
64967 ** Store the result in register P3.
64968 ** If either input is NULL, the result is NULL.
64969 */
64970 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
64971 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
64972 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
64973 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
64974 #if 0  /* local variables moved into u.ai */
64975   i64 iA;
64976   u64 uA;
64977   i64 iB;
64978   u8 op;
64979 #endif /* local variables moved into u.ai */
64980
64981   pIn1 = &aMem[pOp->p1];
64982   pIn2 = &aMem[pOp->p2];
64983   pOut = &aMem[pOp->p3];
64984   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64985     sqlite3VdbeMemSetNull(pOut);
64986     break;
64987   }
64988   u.ai.iA = sqlite3VdbeIntValue(pIn2);
64989   u.ai.iB = sqlite3VdbeIntValue(pIn1);
64990   u.ai.op = pOp->opcode;
64991   if( u.ai.op==OP_BitAnd ){
64992     u.ai.iA &= u.ai.iB;
64993   }else if( u.ai.op==OP_BitOr ){
64994     u.ai.iA |= u.ai.iB;
64995   }else if( u.ai.iB!=0 ){
64996     assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
64997
64998     /* If shifting by a negative amount, shift in the other direction */
64999     if( u.ai.iB<0 ){
65000       assert( OP_ShiftRight==OP_ShiftLeft+1 );
65001       u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
65002       u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
65003     }
65004
65005     if( u.ai.iB>=64 ){
65006       u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
65007     }else{
65008       memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
65009       if( u.ai.op==OP_ShiftLeft ){
65010         u.ai.uA <<= u.ai.iB;
65011       }else{
65012         u.ai.uA >>= u.ai.iB;
65013         /* Sign-extend on a right shift of a negative number */
65014         if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
65015       }
65016       memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
65017     }
65018   }
65019   pOut->u.i = u.ai.iA;
65020   MemSetTypeFlag(pOut, MEM_Int);
65021   break;
65022 }
65023
65024 /* Opcode: AddImm  P1 P2 * * *
65025 ** 
65026 ** Add the constant P2 to the value in register P1.
65027 ** The result is always an integer.
65028 **
65029 ** To force any register to be an integer, just add 0.
65030 */
65031 case OP_AddImm: {            /* in1 */
65032   pIn1 = &aMem[pOp->p1];
65033   memAboutToChange(p, pIn1);
65034   sqlite3VdbeMemIntegerify(pIn1);
65035   pIn1->u.i += pOp->p2;
65036   break;
65037 }
65038
65039 /* Opcode: MustBeInt P1 P2 * * *
65040 ** 
65041 ** Force the value in register P1 to be an integer.  If the value
65042 ** in P1 is not an integer and cannot be converted into an integer
65043 ** without data loss, then jump immediately to P2, or if P2==0
65044 ** raise an SQLITE_MISMATCH exception.
65045 */
65046 case OP_MustBeInt: {            /* jump, in1 */
65047   pIn1 = &aMem[pOp->p1];
65048   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
65049   if( (pIn1->flags & MEM_Int)==0 ){
65050     if( pOp->p2==0 ){
65051       rc = SQLITE_MISMATCH;
65052       goto abort_due_to_error;
65053     }else{
65054       pc = pOp->p2 - 1;
65055     }
65056   }else{
65057     MemSetTypeFlag(pIn1, MEM_Int);
65058   }
65059   break;
65060 }
65061
65062 #ifndef SQLITE_OMIT_FLOATING_POINT
65063 /* Opcode: RealAffinity P1 * * * *
65064 **
65065 ** If register P1 holds an integer convert it to a real value.
65066 **
65067 ** This opcode is used when extracting information from a column that
65068 ** has REAL affinity.  Such column values may still be stored as
65069 ** integers, for space efficiency, but after extraction we want them
65070 ** to have only a real value.
65071 */
65072 case OP_RealAffinity: {                  /* in1 */
65073   pIn1 = &aMem[pOp->p1];
65074   if( pIn1->flags & MEM_Int ){
65075     sqlite3VdbeMemRealify(pIn1);
65076   }
65077   break;
65078 }
65079 #endif
65080
65081 #ifndef SQLITE_OMIT_CAST
65082 /* Opcode: ToText P1 * * * *
65083 **
65084 ** Force the value in register P1 to be text.
65085 ** If the value is numeric, convert it to a string using the
65086 ** equivalent of printf().  Blob values are unchanged and
65087 ** are afterwards simply interpreted as text.
65088 **
65089 ** A NULL value is not changed by this routine.  It remains NULL.
65090 */
65091 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
65092   pIn1 = &aMem[pOp->p1];
65093   memAboutToChange(p, pIn1);
65094   if( pIn1->flags & MEM_Null ) break;
65095   assert( MEM_Str==(MEM_Blob>>3) );
65096   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65097   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65098   rc = ExpandBlob(pIn1);
65099   assert( pIn1->flags & MEM_Str || db->mallocFailed );
65100   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65101   UPDATE_MAX_BLOBSIZE(pIn1);
65102   break;
65103 }
65104
65105 /* Opcode: ToBlob P1 * * * *
65106 **
65107 ** Force the value in register P1 to be a BLOB.
65108 ** If the value is numeric, convert it to a string first.
65109 ** Strings are simply reinterpreted as blobs with no change
65110 ** to the underlying data.
65111 **
65112 ** A NULL value is not changed by this routine.  It remains NULL.
65113 */
65114 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
65115   pIn1 = &aMem[pOp->p1];
65116   if( pIn1->flags & MEM_Null ) break;
65117   if( (pIn1->flags & MEM_Blob)==0 ){
65118     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65119     assert( pIn1->flags & MEM_Str || db->mallocFailed );
65120     MemSetTypeFlag(pIn1, MEM_Blob);
65121   }else{
65122     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65123   }
65124   UPDATE_MAX_BLOBSIZE(pIn1);
65125   break;
65126 }
65127
65128 /* Opcode: ToNumeric P1 * * * *
65129 **
65130 ** Force the value in register P1 to be numeric (either an
65131 ** integer or a floating-point number.)
65132 ** If the value is text or blob, try to convert it to an using the
65133 ** equivalent of atoi() or atof() and store 0 if no such conversion 
65134 ** is possible.
65135 **
65136 ** A NULL value is not changed by this routine.  It remains NULL.
65137 */
65138 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
65139   pIn1 = &aMem[pOp->p1];
65140   sqlite3VdbeMemNumerify(pIn1);
65141   break;
65142 }
65143 #endif /* SQLITE_OMIT_CAST */
65144
65145 /* Opcode: ToInt P1 * * * *
65146 **
65147 ** Force the value in register P1 to be an integer.  If
65148 ** The value is currently a real number, drop its fractional part.
65149 ** If the value is text or blob, try to convert it to an integer using the
65150 ** equivalent of atoi() and store 0 if no such conversion is possible.
65151 **
65152 ** A NULL value is not changed by this routine.  It remains NULL.
65153 */
65154 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
65155   pIn1 = &aMem[pOp->p1];
65156   if( (pIn1->flags & MEM_Null)==0 ){
65157     sqlite3VdbeMemIntegerify(pIn1);
65158   }
65159   break;
65160 }
65161
65162 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65163 /* Opcode: ToReal P1 * * * *
65164 **
65165 ** Force the value in register P1 to be a floating point number.
65166 ** If The value is currently an integer, convert it.
65167 ** If the value is text or blob, try to convert it to an integer using the
65168 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65169 **
65170 ** A NULL value is not changed by this routine.  It remains NULL.
65171 */
65172 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
65173   pIn1 = &aMem[pOp->p1];
65174   memAboutToChange(p, pIn1);
65175   if( (pIn1->flags & MEM_Null)==0 ){
65176     sqlite3VdbeMemRealify(pIn1);
65177   }
65178   break;
65179 }
65180 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65181
65182 /* Opcode: Lt P1 P2 P3 P4 P5
65183 **
65184 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
65185 ** jump to address P2.  
65186 **
65187 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65188 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
65189 ** bit is clear then fall through if either operand is NULL.
65190 **
65191 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65192 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
65193 ** to coerce both inputs according to this affinity before the
65194 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65195 ** affinity is used. Note that the affinity conversions are stored
65196 ** back into the input registers P1 and P3.  So this opcode can cause
65197 ** persistent changes to registers P1 and P3.
65198 **
65199 ** Once any conversions have taken place, and neither value is NULL, 
65200 ** the values are compared. If both values are blobs then memcmp() is
65201 ** used to determine the results of the comparison.  If both values
65202 ** are text, then the appropriate collating function specified in
65203 ** P4 is  used to do the comparison.  If P4 is not specified then
65204 ** memcmp() is used to compare text string.  If both values are
65205 ** numeric, then a numeric comparison is used. If the two values
65206 ** are of different types, then numbers are considered less than
65207 ** strings and strings are considered less than blobs.
65208 **
65209 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
65210 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65211 */
65212 /* Opcode: Ne P1 P2 P3 P4 P5
65213 **
65214 ** This works just like the Lt opcode except that the jump is taken if
65215 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
65216 ** additional information.
65217 **
65218 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65219 ** true or false and is never NULL.  If both operands are NULL then the result
65220 ** of comparison is false.  If either operand is NULL then the result is true.
65221 ** If neither operand is NULL the result is the same as it would be if
65222 ** the SQLITE_NULLEQ flag were omitted from P5.
65223 */
65224 /* Opcode: Eq P1 P2 P3 P4 P5
65225 **
65226 ** This works just like the Lt opcode except that the jump is taken if
65227 ** the operands in registers P1 and P3 are equal.
65228 ** See the Lt opcode for additional information.
65229 **
65230 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65231 ** true or false and is never NULL.  If both operands are NULL then the result
65232 ** of comparison is true.  If either operand is NULL then the result is false.
65233 ** If neither operand is NULL the result is the same as it would be if
65234 ** the SQLITE_NULLEQ flag were omitted from P5.
65235 */
65236 /* Opcode: Le P1 P2 P3 P4 P5
65237 **
65238 ** This works just like the Lt opcode except that the jump is taken if
65239 ** the content of register P3 is less than or equal to the content of
65240 ** register P1.  See the Lt opcode for additional information.
65241 */
65242 /* Opcode: Gt P1 P2 P3 P4 P5
65243 **
65244 ** This works just like the Lt opcode except that the jump is taken if
65245 ** the content of register P3 is greater than the content of
65246 ** register P1.  See the Lt opcode for additional information.
65247 */
65248 /* Opcode: Ge P1 P2 P3 P4 P5
65249 **
65250 ** This works just like the Lt opcode except that the jump is taken if
65251 ** the content of register P3 is greater than or equal to the content of
65252 ** register P1.  See the Lt opcode for additional information.
65253 */
65254 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
65255 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
65256 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
65257 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
65258 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
65259 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
65260 #if 0  /* local variables moved into u.aj */
65261   int res;            /* Result of the comparison of pIn1 against pIn3 */
65262   char affinity;      /* Affinity to use for comparison */
65263   u16 flags1;         /* Copy of initial value of pIn1->flags */
65264   u16 flags3;         /* Copy of initial value of pIn3->flags */
65265 #endif /* local variables moved into u.aj */
65266
65267   pIn1 = &aMem[pOp->p1];
65268   pIn3 = &aMem[pOp->p3];
65269   u.aj.flags1 = pIn1->flags;
65270   u.aj.flags3 = pIn3->flags;
65271   if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
65272     /* One or both operands are NULL */
65273     if( pOp->p5 & SQLITE_NULLEQ ){
65274       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65275       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65276       ** or not both operands are null.
65277       */
65278       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65279       u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
65280     }else{
65281       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65282       ** then the result is always NULL.
65283       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65284       */
65285       if( pOp->p5 & SQLITE_STOREP2 ){
65286         pOut = &aMem[pOp->p2];
65287         MemSetTypeFlag(pOut, MEM_Null);
65288         REGISTER_TRACE(pOp->p2, pOut);
65289       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65290         pc = pOp->p2-1;
65291       }
65292       break;
65293     }
65294   }else{
65295     /* Neither operand is NULL.  Do a comparison. */
65296     u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
65297     if( u.aj.affinity ){
65298       applyAffinity(pIn1, u.aj.affinity, encoding);
65299       applyAffinity(pIn3, u.aj.affinity, encoding);
65300       if( db->mallocFailed ) goto no_mem;
65301     }
65302
65303     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65304     ExpandBlob(pIn1);
65305     ExpandBlob(pIn3);
65306     u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65307   }
65308   switch( pOp->opcode ){
65309     case OP_Eq:    u.aj.res = u.aj.res==0;     break;
65310     case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
65311     case OP_Lt:    u.aj.res = u.aj.res<0;      break;
65312     case OP_Le:    u.aj.res = u.aj.res<=0;     break;
65313     case OP_Gt:    u.aj.res = u.aj.res>0;      break;
65314     default:       u.aj.res = u.aj.res>=0;     break;
65315   }
65316
65317   if( pOp->p5 & SQLITE_STOREP2 ){
65318     pOut = &aMem[pOp->p2];
65319     memAboutToChange(p, pOut);
65320     MemSetTypeFlag(pOut, MEM_Int);
65321     pOut->u.i = u.aj.res;
65322     REGISTER_TRACE(pOp->p2, pOut);
65323   }else if( u.aj.res ){
65324     pc = pOp->p2-1;
65325   }
65326
65327   /* Undo any changes made by applyAffinity() to the input registers. */
65328   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
65329   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
65330   break;
65331 }
65332
65333 /* Opcode: Permutation * * * P4 *
65334 **
65335 ** Set the permutation used by the OP_Compare operator to be the array
65336 ** of integers in P4.
65337 **
65338 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
65339 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
65340 ** immediately prior to the OP_Compare.
65341 */
65342 case OP_Permutation: {
65343   assert( pOp->p4type==P4_INTARRAY );
65344   assert( pOp->p4.ai );
65345   aPermute = pOp->p4.ai;
65346   break;
65347 }
65348
65349 /* Opcode: Compare P1 P2 P3 P4 *
65350 **
65351 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
65352 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
65353 ** the comparison for use by the next OP_Jump instruct.
65354 **
65355 ** P4 is a KeyInfo structure that defines collating sequences and sort
65356 ** orders for the comparison.  The permutation applies to registers
65357 ** only.  The KeyInfo elements are used sequentially.
65358 **
65359 ** The comparison is a sort comparison, so NULLs compare equal,
65360 ** NULLs are less than numbers, numbers are less than strings,
65361 ** and strings are less than blobs.
65362 */
65363 case OP_Compare: {
65364 #if 0  /* local variables moved into u.ak */
65365   int n;
65366   int i;
65367   int p1;
65368   int p2;
65369   const KeyInfo *pKeyInfo;
65370   int idx;
65371   CollSeq *pColl;    /* Collating sequence to use on this term */
65372   int bRev;          /* True for DESCENDING sort order */
65373 #endif /* local variables moved into u.ak */
65374
65375   u.ak.n = pOp->p3;
65376   u.ak.pKeyInfo = pOp->p4.pKeyInfo;
65377   assert( u.ak.n>0 );
65378   assert( u.ak.pKeyInfo!=0 );
65379   u.ak.p1 = pOp->p1;
65380   u.ak.p2 = pOp->p2;
65381 #if SQLITE_DEBUG
65382   if( aPermute ){
65383     int k, mx = 0;
65384     for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
65385     assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
65386     assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
65387   }else{
65388     assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
65389     assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
65390   }
65391 #endif /* SQLITE_DEBUG */
65392   for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
65393     u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
65394     assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
65395     assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
65396     REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
65397     REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
65398     assert( u.ak.i<u.ak.pKeyInfo->nField );
65399     u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
65400     u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
65401     iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
65402     if( iCompare ){
65403       if( u.ak.bRev ) iCompare = -iCompare;
65404       break;
65405     }
65406   }
65407   aPermute = 0;
65408   break;
65409 }
65410
65411 /* Opcode: Jump P1 P2 P3 * *
65412 **
65413 ** Jump to the instruction at address P1, P2, or P3 depending on whether
65414 ** in the most recent OP_Compare instruction the P1 vector was less than
65415 ** equal to, or greater than the P2 vector, respectively.
65416 */
65417 case OP_Jump: {             /* jump */
65418   if( iCompare<0 ){
65419     pc = pOp->p1 - 1;
65420   }else if( iCompare==0 ){
65421     pc = pOp->p2 - 1;
65422   }else{
65423     pc = pOp->p3 - 1;
65424   }
65425   break;
65426 }
65427
65428 /* Opcode: And P1 P2 P3 * *
65429 **
65430 ** Take the logical AND of the values in registers P1 and P2 and
65431 ** write the result into register P3.
65432 **
65433 ** If either P1 or P2 is 0 (false) then the result is 0 even if
65434 ** the other input is NULL.  A NULL and true or two NULLs give
65435 ** a NULL output.
65436 */
65437 /* Opcode: Or P1 P2 P3 * *
65438 **
65439 ** Take the logical OR of the values in register P1 and P2 and
65440 ** store the answer in register P3.
65441 **
65442 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
65443 ** even if the other input is NULL.  A NULL and false or two NULLs
65444 ** give a NULL output.
65445 */
65446 case OP_And:              /* same as TK_AND, in1, in2, out3 */
65447 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
65448 #if 0  /* local variables moved into u.al */
65449   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65450   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65451 #endif /* local variables moved into u.al */
65452
65453   pIn1 = &aMem[pOp->p1];
65454   if( pIn1->flags & MEM_Null ){
65455     u.al.v1 = 2;
65456   }else{
65457     u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
65458   }
65459   pIn2 = &aMem[pOp->p2];
65460   if( pIn2->flags & MEM_Null ){
65461     u.al.v2 = 2;
65462   }else{
65463     u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
65464   }
65465   if( pOp->opcode==OP_And ){
65466     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
65467     u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
65468   }else{
65469     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
65470     u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
65471   }
65472   pOut = &aMem[pOp->p3];
65473   if( u.al.v1==2 ){
65474     MemSetTypeFlag(pOut, MEM_Null);
65475   }else{
65476     pOut->u.i = u.al.v1;
65477     MemSetTypeFlag(pOut, MEM_Int);
65478   }
65479   break;
65480 }
65481
65482 /* Opcode: Not P1 P2 * * *
65483 **
65484 ** Interpret the value in register P1 as a boolean value.  Store the
65485 ** boolean complement in register P2.  If the value in register P1 is 
65486 ** NULL, then a NULL is stored in P2.
65487 */
65488 case OP_Not: {                /* same as TK_NOT, in1, out2 */
65489   pIn1 = &aMem[pOp->p1];
65490   pOut = &aMem[pOp->p2];
65491   if( pIn1->flags & MEM_Null ){
65492     sqlite3VdbeMemSetNull(pOut);
65493   }else{
65494     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
65495   }
65496   break;
65497 }
65498
65499 /* Opcode: BitNot P1 P2 * * *
65500 **
65501 ** Interpret the content of register P1 as an integer.  Store the
65502 ** ones-complement of the P1 value into register P2.  If P1 holds
65503 ** a NULL then store a NULL in P2.
65504 */
65505 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
65506   pIn1 = &aMem[pOp->p1];
65507   pOut = &aMem[pOp->p2];
65508   if( pIn1->flags & MEM_Null ){
65509     sqlite3VdbeMemSetNull(pOut);
65510   }else{
65511     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
65512   }
65513   break;
65514 }
65515
65516 /* Opcode: Once P1 P2 * * *
65517 **
65518 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
65519 ** set the flag and fall through to the next instruction.
65520 **
65521 ** See also: JumpOnce
65522 */
65523 case OP_Once: {             /* jump */
65524   assert( pOp->p1<p->nOnceFlag );
65525   if( p->aOnceFlag[pOp->p1] ){
65526     pc = pOp->p2-1;
65527   }else{
65528     p->aOnceFlag[pOp->p1] = 1;
65529   }
65530   break;
65531 }
65532
65533 /* Opcode: If P1 P2 P3 * *
65534 **
65535 ** Jump to P2 if the value in register P1 is true.  The value
65536 ** is considered true if it is numeric and non-zero.  If the value
65537 ** in P1 is NULL then take the jump if P3 is non-zero.
65538 */
65539 /* Opcode: IfNot P1 P2 P3 * *
65540 **
65541 ** Jump to P2 if the value in register P1 is False.  The value
65542 ** is considered false if it has a numeric value of zero.  If the value
65543 ** in P1 is NULL then take the jump if P3 is zero.
65544 */
65545 case OP_If:                 /* jump, in1 */
65546 case OP_IfNot: {            /* jump, in1 */
65547 #if 0  /* local variables moved into u.am */
65548   int c;
65549 #endif /* local variables moved into u.am */
65550   pIn1 = &aMem[pOp->p1];
65551   if( pIn1->flags & MEM_Null ){
65552     u.am.c = pOp->p3;
65553   }else{
65554 #ifdef SQLITE_OMIT_FLOATING_POINT
65555     u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
65556 #else
65557     u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
65558 #endif
65559     if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
65560   }
65561   if( u.am.c ){
65562     pc = pOp->p2-1;
65563   }
65564   break;
65565 }
65566
65567 /* Opcode: IsNull P1 P2 * * *
65568 **
65569 ** Jump to P2 if the value in register P1 is NULL.
65570 */
65571 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
65572   pIn1 = &aMem[pOp->p1];
65573   if( (pIn1->flags & MEM_Null)!=0 ){
65574     pc = pOp->p2 - 1;
65575   }
65576   break;
65577 }
65578
65579 /* Opcode: NotNull P1 P2 * * *
65580 **
65581 ** Jump to P2 if the value in register P1 is not NULL.  
65582 */
65583 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
65584   pIn1 = &aMem[pOp->p1];
65585   if( (pIn1->flags & MEM_Null)==0 ){
65586     pc = pOp->p2 - 1;
65587   }
65588   break;
65589 }
65590
65591 /* Opcode: Column P1 P2 P3 P4 P5
65592 **
65593 ** Interpret the data that cursor P1 points to as a structure built using
65594 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
65595 ** information about the format of the data.)  Extract the P2-th column
65596 ** from this record.  If there are less that (P2+1) 
65597 ** values in the record, extract a NULL.
65598 **
65599 ** The value extracted is stored in register P3.
65600 **
65601 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
65602 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
65603 ** the result.
65604 **
65605 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
65606 ** then the cache of the cursor is reset prior to extracting the column.
65607 ** The first OP_Column against a pseudo-table after the value of the content
65608 ** register has changed should have this bit set.
65609 **
65610 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
65611 ** the result is guaranteed to only be used as the argument of a length()
65612 ** or typeof() function, respectively.  The loading of large blobs can be
65613 ** skipped for length() and all content loading can be skipped for typeof().
65614 */
65615 case OP_Column: {
65616 #if 0  /* local variables moved into u.an */
65617   u32 payloadSize;   /* Number of bytes in the record */
65618   i64 payloadSize64; /* Number of bytes in the record */
65619   int p1;            /* P1 value of the opcode */
65620   int p2;            /* column number to retrieve */
65621   VdbeCursor *pC;    /* The VDBE cursor */
65622   char *zRec;        /* Pointer to complete record-data */
65623   BtCursor *pCrsr;   /* The BTree cursor */
65624   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65625   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65626   int nField;        /* number of fields in the record */
65627   int len;           /* The length of the serialized data for the column */
65628   int i;             /* Loop counter */
65629   char *zData;       /* Part of the record being decoded */
65630   Mem *pDest;        /* Where to write the extracted value */
65631   Mem sMem;          /* For storing the record being decoded */
65632   u8 *zIdx;          /* Index into header */
65633   u8 *zEndHdr;       /* Pointer to first byte after the header */
65634   u32 offset;        /* Offset into the data */
65635   u32 szField;       /* Number of bytes in the content of a field */
65636   int szHdr;         /* Size of the header size field at start of record */
65637   int avail;         /* Number of bytes of available data */
65638   u32 t;             /* A type code from the record header */
65639   Mem *pReg;         /* PseudoTable input register */
65640 #endif /* local variables moved into u.an */
65641
65642
65643   u.an.p1 = pOp->p1;
65644   u.an.p2 = pOp->p2;
65645   u.an.pC = 0;
65646   memset(&u.an.sMem, 0, sizeof(u.an.sMem));
65647   assert( u.an.p1<p->nCursor );
65648   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65649   u.an.pDest = &aMem[pOp->p3];
65650   memAboutToChange(p, u.an.pDest);
65651   u.an.zRec = 0;
65652
65653   /* This block sets the variable u.an.payloadSize to be the total number of
65654   ** bytes in the record.
65655   **
65656   ** u.an.zRec is set to be the complete text of the record if it is available.
65657   ** The complete record text is always available for pseudo-tables
65658   ** If the record is stored in a cursor, the complete record text
65659   ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
65660   ** If the data is unavailable,  u.an.zRec is set to NULL.
65661   **
65662   ** We also compute the number of columns in the record.  For cursors,
65663   ** the number of columns is stored in the VdbeCursor.nField element.
65664   */
65665   u.an.pC = p->apCsr[u.an.p1];
65666   assert( u.an.pC!=0 );
65667 #ifndef SQLITE_OMIT_VIRTUALTABLE
65668   assert( u.an.pC->pVtabCursor==0 );
65669 #endif
65670   u.an.pCrsr = u.an.pC->pCursor;
65671   if( u.an.pCrsr!=0 ){
65672     /* The record is stored in a B-Tree */
65673     rc = sqlite3VdbeCursorMoveto(u.an.pC);
65674     if( rc ) goto abort_due_to_error;
65675     if( u.an.pC->nullRow ){
65676       u.an.payloadSize = 0;
65677     }else if( u.an.pC->cacheStatus==p->cacheCtr ){
65678       u.an.payloadSize = u.an.pC->payloadSize;
65679       u.an.zRec = (char*)u.an.pC->aRow;
65680     }else if( u.an.pC->isIndex ){
65681       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
65682       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
65683       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
65684       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
65685       ** payload size, so it is impossible for u.an.payloadSize64 to be
65686       ** larger than 32 bits. */
65687       assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
65688       u.an.payloadSize = (u32)u.an.payloadSize64;
65689     }else{
65690       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
65691       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
65692       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
65693     }
65694   }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
65695     u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
65696     assert( u.an.pReg->flags & MEM_Blob );
65697     assert( memIsValid(u.an.pReg) );
65698     u.an.payloadSize = u.an.pReg->n;
65699     u.an.zRec = u.an.pReg->z;
65700     u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
65701     assert( u.an.payloadSize==0 || u.an.zRec!=0 );
65702   }else{
65703     /* Consider the row to be NULL */
65704     u.an.payloadSize = 0;
65705   }
65706
65707   /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
65708   ** nullRow or because of a corrupt database. */
65709   if( u.an.payloadSize==0 ){
65710     MemSetTypeFlag(u.an.pDest, MEM_Null);
65711     goto op_column_out;
65712   }
65713   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
65714   if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
65715     goto too_big;
65716   }
65717
65718   u.an.nField = u.an.pC->nField;
65719   assert( u.an.p2<u.an.nField );
65720
65721   /* Read and parse the table header.  Store the results of the parse
65722   ** into the record header cache fields of the cursor.
65723   */
65724   u.an.aType = u.an.pC->aType;
65725   if( u.an.pC->cacheStatus==p->cacheCtr ){
65726     u.an.aOffset = u.an.pC->aOffset;
65727   }else{
65728     assert(u.an.aType);
65729     u.an.avail = 0;
65730     u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
65731     u.an.pC->payloadSize = u.an.payloadSize;
65732     u.an.pC->cacheStatus = p->cacheCtr;
65733
65734     /* Figure out how many bytes are in the header */
65735     if( u.an.zRec ){
65736       u.an.zData = u.an.zRec;
65737     }else{
65738       if( u.an.pC->isIndex ){
65739         u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
65740       }else{
65741         u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
65742       }
65743       /* If KeyFetch()/DataFetch() managed to get the entire payload,
65744       ** save the payload in the u.an.pC->aRow cache.  That will save us from
65745       ** having to make additional calls to fetch the content portion of
65746       ** the record.
65747       */
65748       assert( u.an.avail>=0 );
65749       if( u.an.payloadSize <= (u32)u.an.avail ){
65750         u.an.zRec = u.an.zData;
65751         u.an.pC->aRow = (u8*)u.an.zData;
65752       }else{
65753         u.an.pC->aRow = 0;
65754       }
65755     }
65756     /* The following assert is true in all cases except when
65757     ** the database file has been corrupted externally.
65758     **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
65759     u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
65760
65761     /* Make sure a corrupt database has not given us an oversize header.
65762     ** Do this now to avoid an oversize memory allocation.
65763     **
65764     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
65765     ** types use so much data space that there can only be 4096 and 32 of
65766     ** them, respectively.  So the maximum header length results from a
65767     ** 3-byte type for each of the maximum of 32768 columns plus three
65768     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
65769     */
65770     if( u.an.offset > 98307 ){
65771       rc = SQLITE_CORRUPT_BKPT;
65772       goto op_column_out;
65773     }
65774
65775     /* Compute in u.an.len the number of bytes of data we need to read in order
65776     ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
65777     ** u.an.nField might be significantly less than the true number of columns
65778     ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
65779     ** We want to minimize u.an.len in order to limit the size of the memory
65780     ** allocation, especially if a corrupt database file has caused u.an.offset
65781     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
65782     ** still exceed Robson memory allocation limits on some configurations.
65783     ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
65784     ** will likely be much smaller since u.an.nField will likely be less than
65785     ** 20 or so.  This insures that Robson memory allocation limits are
65786     ** not exceeded even for corrupt database files.
65787     */
65788     u.an.len = u.an.nField*5 + 3;
65789     if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
65790
65791     /* The KeyFetch() or DataFetch() above are fast and will get the entire
65792     ** record header in most cases.  But they will fail to get the complete
65793     ** record header if the record header does not fit on a single page
65794     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
65795     ** acquire the complete header text.
65796     */
65797     if( !u.an.zRec && u.an.avail<u.an.len ){
65798       u.an.sMem.flags = 0;
65799       u.an.sMem.db = 0;
65800       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
65801       if( rc!=SQLITE_OK ){
65802         goto op_column_out;
65803       }
65804       u.an.zData = u.an.sMem.z;
65805     }
65806     u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
65807     u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
65808
65809     /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
65810     ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
65811     ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
65812     ** of the record to the start of the data for the u.an.i-th column
65813     */
65814     for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
65815       if( u.an.zIdx<u.an.zEndHdr ){
65816         u.an.aOffset[u.an.i] = u.an.offset;
65817         if( u.an.zIdx[0]<0x80 ){
65818           u.an.t = u.an.zIdx[0];
65819           u.an.zIdx++;
65820         }else{
65821           u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
65822         }
65823         u.an.aType[u.an.i] = u.an.t;
65824         u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
65825         u.an.offset += u.an.szField;
65826         if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
65827           u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
65828           break;
65829         }
65830       }else{
65831         /* If u.an.i is less that u.an.nField, then there are fewer fields in this
65832         ** record than SetNumColumns indicated there are columns in the
65833         ** table. Set the u.an.offset for any extra columns not present in
65834         ** the record to 0. This tells code below to store the default value
65835         ** for the column instead of deserializing a value from the record.
65836         */
65837         u.an.aOffset[u.an.i] = 0;
65838       }
65839     }
65840     sqlite3VdbeMemRelease(&u.an.sMem);
65841     u.an.sMem.flags = MEM_Null;
65842
65843     /* If we have read more header data than was contained in the header,
65844     ** or if the end of the last field appears to be past the end of the
65845     ** record, or if the end of the last field appears to be before the end
65846     ** of the record (when all fields present), then we must be dealing
65847     ** with a corrupt database.
65848     */
65849     if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
65850          || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
65851       rc = SQLITE_CORRUPT_BKPT;
65852       goto op_column_out;
65853     }
65854   }
65855
65856   /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
65857   ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
65858   ** then there are not enough fields in the record to satisfy the
65859   ** request.  In this case, set the value NULL or to P4 if P4 is
65860   ** a pointer to a Mem object.
65861   */
65862   if( u.an.aOffset[u.an.p2] ){
65863     assert( rc==SQLITE_OK );
65864     if( u.an.zRec ){
65865       /* This is the common case where the whole row fits on a single page */
65866       VdbeMemRelease(u.an.pDest);
65867       sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
65868     }else{
65869       /* This branch happens only when the row overflows onto multiple pages */
65870       u.an.t = u.an.aType[u.an.p2];
65871       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
65872        && ((u.an.t>=12 && (u.an.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
65873       ){
65874         /* Content is irrelevant for the typeof() function and for
65875         ** the length(X) function if X is a blob.  So we might as well use
65876         ** bogus content rather than reading content from disk.  NULL works
65877         ** for text and blob and whatever is in the u.an.payloadSize64 variable
65878         ** will work for everything else. */
65879         u.an.zData = u.an.t<12 ? (char*)&u.an.payloadSize64 : 0;
65880       }else{
65881         u.an.len = sqlite3VdbeSerialTypeLen(u.an.t);
65882         sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
65883         rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len,  u.an.pC->isIndex,
65884                                      &u.an.sMem);
65885         if( rc!=SQLITE_OK ){
65886           goto op_column_out;
65887         }
65888         u.an.zData = u.an.sMem.z;
65889       }
65890       sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.t, u.an.pDest);
65891     }
65892     u.an.pDest->enc = encoding;
65893   }else{
65894     if( pOp->p4type==P4_MEM ){
65895       sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
65896     }else{
65897       MemSetTypeFlag(u.an.pDest, MEM_Null);
65898     }
65899   }
65900
65901   /* If we dynamically allocated space to hold the data (in the
65902   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
65903   ** dynamically allocated space over to the u.an.pDest structure.
65904   ** This prevents a memory copy.
65905   */
65906   if( u.an.sMem.zMalloc ){
65907     assert( u.an.sMem.z==u.an.sMem.zMalloc );
65908     assert( !(u.an.pDest->flags & MEM_Dyn) );
65909     assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
65910     u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
65911     u.an.pDest->flags |= MEM_Term;
65912     u.an.pDest->z = u.an.sMem.z;
65913     u.an.pDest->zMalloc = u.an.sMem.zMalloc;
65914   }
65915
65916   rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
65917
65918 op_column_out:
65919   UPDATE_MAX_BLOBSIZE(u.an.pDest);
65920   REGISTER_TRACE(pOp->p3, u.an.pDest);
65921   break;
65922 }
65923
65924 /* Opcode: Affinity P1 P2 * P4 *
65925 **
65926 ** Apply affinities to a range of P2 registers starting with P1.
65927 **
65928 ** P4 is a string that is P2 characters long. The nth character of the
65929 ** string indicates the column affinity that should be used for the nth
65930 ** memory cell in the range.
65931 */
65932 case OP_Affinity: {
65933 #if 0  /* local variables moved into u.ao */
65934   const char *zAffinity;   /* The affinity to be applied */
65935   char cAff;               /* A single character of affinity */
65936 #endif /* local variables moved into u.ao */
65937
65938   u.ao.zAffinity = pOp->p4.z;
65939   assert( u.ao.zAffinity!=0 );
65940   assert( u.ao.zAffinity[pOp->p2]==0 );
65941   pIn1 = &aMem[pOp->p1];
65942   while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
65943     assert( pIn1 <= &p->aMem[p->nMem] );
65944     assert( memIsValid(pIn1) );
65945     ExpandBlob(pIn1);
65946     applyAffinity(pIn1, u.ao.cAff, encoding);
65947     pIn1++;
65948   }
65949   break;
65950 }
65951
65952 /* Opcode: MakeRecord P1 P2 P3 P4 *
65953 **
65954 ** Convert P2 registers beginning with P1 into the [record format]
65955 ** use as a data record in a database table or as a key
65956 ** in an index.  The OP_Column opcode can decode the record later.
65957 **
65958 ** P4 may be a string that is P2 characters long.  The nth character of the
65959 ** string indicates the column affinity that should be used for the nth
65960 ** field of the index key.
65961 **
65962 ** The mapping from character to affinity is given by the SQLITE_AFF_
65963 ** macros defined in sqliteInt.h.
65964 **
65965 ** If P4 is NULL then all index fields have the affinity NONE.
65966 */
65967 case OP_MakeRecord: {
65968 #if 0  /* local variables moved into u.ap */
65969   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65970   Mem *pRec;             /* The new record */
65971   u64 nData;             /* Number of bytes of data space */
65972   int nHdr;              /* Number of bytes of header space */
65973   i64 nByte;             /* Data space required for this record */
65974   int nZero;             /* Number of zero bytes at the end of the record */
65975   int nVarint;           /* Number of bytes in a varint */
65976   u32 serial_type;       /* Type field */
65977   Mem *pData0;           /* First field to be combined into the record */
65978   Mem *pLast;            /* Last field of the record */
65979   int nField;            /* Number of fields in the record */
65980   char *zAffinity;       /* The affinity string for the record */
65981   int file_format;       /* File format to use for encoding */
65982   int i;                 /* Space used in zNewRecord[] */
65983   int len;               /* Length of a field */
65984 #endif /* local variables moved into u.ap */
65985
65986   /* Assuming the record contains N fields, the record format looks
65987   ** like this:
65988   **
65989   ** ------------------------------------------------------------------------
65990   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
65991   ** ------------------------------------------------------------------------
65992   **
65993   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
65994   ** and so froth.
65995   **
65996   ** Each type field is a varint representing the serial type of the
65997   ** corresponding data element (see sqlite3VdbeSerialType()). The
65998   ** hdr-size field is also a varint which is the offset from the beginning
65999   ** of the record to data0.
66000   */
66001   u.ap.nData = 0;         /* Number of bytes of data space */
66002   u.ap.nHdr = 0;          /* Number of bytes of header space */
66003   u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
66004   u.ap.nField = pOp->p1;
66005   u.ap.zAffinity = pOp->p4.z;
66006   assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
66007   u.ap.pData0 = &aMem[u.ap.nField];
66008   u.ap.nField = pOp->p2;
66009   u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
66010   u.ap.file_format = p->minWriteFileFormat;
66011
66012   /* Identify the output register */
66013   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
66014   pOut = &aMem[pOp->p3];
66015   memAboutToChange(p, pOut);
66016
66017   /* Loop through the elements that will make up the record to figure
66018   ** out how much space is required for the new record.
66019   */
66020   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
66021     assert( memIsValid(u.ap.pRec) );
66022     if( u.ap.zAffinity ){
66023       applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
66024     }
66025     if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
66026       sqlite3VdbeMemExpandBlob(u.ap.pRec);
66027     }
66028     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
66029     u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
66030     u.ap.nData += u.ap.len;
66031     u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
66032     if( u.ap.pRec->flags & MEM_Zero ){
66033       /* Only pure zero-filled BLOBs can be input to this Opcode.
66034       ** We do not allow blobs with a prefix and a zero-filled tail. */
66035       u.ap.nZero += u.ap.pRec->u.nZero;
66036     }else if( u.ap.len ){
66037       u.ap.nZero = 0;
66038     }
66039   }
66040
66041   /* Add the initial header varint and total the size */
66042   u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
66043   if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
66044     u.ap.nHdr++;
66045   }
66046   u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
66047   if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66048     goto too_big;
66049   }
66050
66051   /* Make sure the output register has a buffer large enough to store
66052   ** the new record. The output register (pOp->p3) is not allowed to
66053   ** be one of the input registers (because the following call to
66054   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
66055   */
66056   if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
66057     goto no_mem;
66058   }
66059   u.ap.zNewRecord = (u8 *)pOut->z;
66060
66061   /* Write the record */
66062   u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
66063   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
66064     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
66065     u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
66066   }
66067   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
66068     u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
66069   }
66070   assert( u.ap.i==u.ap.nByte );
66071
66072   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66073   pOut->n = (int)u.ap.nByte;
66074   pOut->flags = MEM_Blob | MEM_Dyn;
66075   pOut->xDel = 0;
66076   if( u.ap.nZero ){
66077     pOut->u.nZero = u.ap.nZero;
66078     pOut->flags |= MEM_Zero;
66079   }
66080   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
66081   REGISTER_TRACE(pOp->p3, pOut);
66082   UPDATE_MAX_BLOBSIZE(pOut);
66083   break;
66084 }
66085
66086 /* Opcode: Count P1 P2 * * *
66087 **
66088 ** Store the number of entries (an integer value) in the table or index 
66089 ** opened by cursor P1 in register P2
66090 */
66091 #ifndef SQLITE_OMIT_BTREECOUNT
66092 case OP_Count: {         /* out2-prerelease */
66093 #if 0  /* local variables moved into u.aq */
66094   i64 nEntry;
66095   BtCursor *pCrsr;
66096 #endif /* local variables moved into u.aq */
66097
66098   u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
66099   if( ALWAYS(u.aq.pCrsr) ){
66100     rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
66101   }else{
66102     u.aq.nEntry = 0;
66103   }
66104   pOut->u.i = u.aq.nEntry;
66105   break;
66106 }
66107 #endif
66108
66109 /* Opcode: Savepoint P1 * * P4 *
66110 **
66111 ** Open, release or rollback the savepoint named by parameter P4, depending
66112 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66113 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66114 */
66115 case OP_Savepoint: {
66116 #if 0  /* local variables moved into u.ar */
66117   int p1;                         /* Value of P1 operand */
66118   char *zName;                    /* Name of savepoint */
66119   int nName;
66120   Savepoint *pNew;
66121   Savepoint *pSavepoint;
66122   Savepoint *pTmp;
66123   int iSavepoint;
66124   int ii;
66125 #endif /* local variables moved into u.ar */
66126
66127   u.ar.p1 = pOp->p1;
66128   u.ar.zName = pOp->p4.z;
66129
66130   /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
66131   ** transaction, then there cannot be any savepoints.
66132   */
66133   assert( db->pSavepoint==0 || db->autoCommit==0 );
66134   assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
66135   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66136   assert( checkSavepointCount(db) );
66137
66138   if( u.ar.p1==SAVEPOINT_BEGIN ){
66139     if( db->writeVdbeCnt>0 ){
66140       /* A new savepoint cannot be created if there are active write
66141       ** statements (i.e. open read/write incremental blob handles).
66142       */
66143       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66144         "SQL statements in progress");
66145       rc = SQLITE_BUSY;
66146     }else{
66147       u.ar.nName = sqlite3Strlen30(u.ar.zName);
66148
66149 #ifndef SQLITE_OMIT_VIRTUALTABLE
66150       /* This call is Ok even if this savepoint is actually a transaction
66151       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66152       ** If this is a transaction savepoint being opened, it is guaranteed
66153       ** that the db->aVTrans[] array is empty.  */
66154       assert( db->autoCommit==0 || db->nVTrans==0 );
66155       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66156                                 db->nStatement+db->nSavepoint);
66157       if( rc!=SQLITE_OK ) goto abort_due_to_error;
66158 #endif
66159
66160       /* Create a new savepoint structure. */
66161       u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
66162       if( u.ar.pNew ){
66163         u.ar.pNew->zName = (char *)&u.ar.pNew[1];
66164         memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
66165
66166         /* If there is no open transaction, then mark this as a special
66167         ** "transaction savepoint". */
66168         if( db->autoCommit ){
66169           db->autoCommit = 0;
66170           db->isTransactionSavepoint = 1;
66171         }else{
66172           db->nSavepoint++;
66173         }
66174
66175         /* Link the new savepoint into the database handle's list. */
66176         u.ar.pNew->pNext = db->pSavepoint;
66177         db->pSavepoint = u.ar.pNew;
66178         u.ar.pNew->nDeferredCons = db->nDeferredCons;
66179       }
66180     }
66181   }else{
66182     u.ar.iSavepoint = 0;
66183
66184     /* Find the named savepoint. If there is no such savepoint, then an
66185     ** an error is returned to the user.  */
66186     for(
66187       u.ar.pSavepoint = db->pSavepoint;
66188       u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
66189       u.ar.pSavepoint = u.ar.pSavepoint->pNext
66190     ){
66191       u.ar.iSavepoint++;
66192     }
66193     if( !u.ar.pSavepoint ){
66194       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
66195       rc = SQLITE_ERROR;
66196     }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
66197       /* It is not possible to release (commit) a savepoint if there are
66198       ** active write statements.
66199       */
66200       sqlite3SetString(&p->zErrMsg, db,
66201         "cannot release savepoint - SQL statements in progress"
66202       );
66203       rc = SQLITE_BUSY;
66204     }else{
66205
66206       /* Determine whether or not this is a transaction savepoint. If so,
66207       ** and this is a RELEASE command, then the current transaction
66208       ** is committed.
66209       */
66210       int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66211       if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
66212         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66213           goto vdbe_return;
66214         }
66215         db->autoCommit = 1;
66216         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66217           p->pc = pc;
66218           db->autoCommit = 0;
66219           p->rc = rc = SQLITE_BUSY;
66220           goto vdbe_return;
66221         }
66222         db->isTransactionSavepoint = 0;
66223         rc = p->rc;
66224       }else{
66225         u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
66226         if( u.ar.p1==SAVEPOINT_ROLLBACK ){
66227           for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
66228             sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
66229           }
66230         }
66231         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
66232           rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
66233           if( rc!=SQLITE_OK ){
66234             goto abort_due_to_error;
66235           }
66236         }
66237         if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66238           sqlite3ExpirePreparedStatements(db);
66239           sqlite3ResetAllSchemasOfConnection(db);
66240           db->flags = (db->flags | SQLITE_InternChanges);
66241         }
66242       }
66243
66244       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66245       ** savepoints nested inside of the savepoint being operated on. */
66246       while( db->pSavepoint!=u.ar.pSavepoint ){
66247         u.ar.pTmp = db->pSavepoint;
66248         db->pSavepoint = u.ar.pTmp->pNext;
66249         sqlite3DbFree(db, u.ar.pTmp);
66250         db->nSavepoint--;
66251       }
66252
66253       /* If it is a RELEASE, then destroy the savepoint being operated on
66254       ** too. If it is a ROLLBACK TO, then set the number of deferred
66255       ** constraint violations present in the database to the value stored
66256       ** when the savepoint was created.  */
66257       if( u.ar.p1==SAVEPOINT_RELEASE ){
66258         assert( u.ar.pSavepoint==db->pSavepoint );
66259         db->pSavepoint = u.ar.pSavepoint->pNext;
66260         sqlite3DbFree(db, u.ar.pSavepoint);
66261         if( !isTransaction ){
66262           db->nSavepoint--;
66263         }
66264       }else{
66265         db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
66266       }
66267
66268       if( !isTransaction ){
66269         rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
66270         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66271       }
66272     }
66273   }
66274
66275   break;
66276 }
66277
66278 /* Opcode: AutoCommit P1 P2 * * *
66279 **
66280 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66281 ** back any currently active btree transactions. If there are any active
66282 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
66283 ** there are active writing VMs or active VMs that use shared cache.
66284 **
66285 ** This instruction causes the VM to halt.
66286 */
66287 case OP_AutoCommit: {
66288 #if 0  /* local variables moved into u.as */
66289   int desiredAutoCommit;
66290   int iRollback;
66291   int turnOnAC;
66292 #endif /* local variables moved into u.as */
66293
66294   u.as.desiredAutoCommit = pOp->p1;
66295   u.as.iRollback = pOp->p2;
66296   u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
66297   assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
66298   assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
66299   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
66300
66301 #if 0
66302   if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
66303     /* If this instruction implements a ROLLBACK and other VMs are
66304     ** still running, and a transaction is active, return an error indicating
66305     ** that the other VMs must complete first.
66306     */
66307     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66308         "SQL statements in progress");
66309     rc = SQLITE_BUSY;
66310   }else
66311 #endif
66312   if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
66313     /* If this instruction implements a COMMIT and other VMs are writing
66314     ** return an error indicating that the other VMs must complete first.
66315     */
66316     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66317         "SQL statements in progress");
66318     rc = SQLITE_BUSY;
66319   }else if( u.as.desiredAutoCommit!=db->autoCommit ){
66320     if( u.as.iRollback ){
66321       assert( u.as.desiredAutoCommit==1 );
66322       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
66323       db->autoCommit = 1;
66324     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66325       goto vdbe_return;
66326     }else{
66327       db->autoCommit = (u8)u.as.desiredAutoCommit;
66328       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66329         p->pc = pc;
66330         db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
66331         p->rc = rc = SQLITE_BUSY;
66332         goto vdbe_return;
66333       }
66334     }
66335     assert( db->nStatement==0 );
66336     sqlite3CloseSavepoints(db);
66337     if( p->rc==SQLITE_OK ){
66338       rc = SQLITE_DONE;
66339     }else{
66340       rc = SQLITE_ERROR;
66341     }
66342     goto vdbe_return;
66343   }else{
66344     sqlite3SetString(&p->zErrMsg, db,
66345         (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
66346         (u.as.iRollback)?"cannot rollback - no transaction is active":
66347                    "cannot commit - no transaction is active"));
66348
66349     rc = SQLITE_ERROR;
66350   }
66351   break;
66352 }
66353
66354 /* Opcode: Transaction P1 P2 * * *
66355 **
66356 ** Begin a transaction.  The transaction ends when a Commit or Rollback
66357 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
66358 ** transaction might also be rolled back if an error is encountered.
66359 **
66360 ** P1 is the index of the database file on which the transaction is
66361 ** started.  Index 0 is the main database file and index 1 is the
66362 ** file used for temporary tables.  Indices of 2 or more are used for
66363 ** attached databases.
66364 **
66365 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
66366 ** obtained on the database file when a write-transaction is started.  No
66367 ** other process can start another write transaction while this transaction is
66368 ** underway.  Starting a write transaction also creates a rollback journal. A
66369 ** write transaction must be started before any changes can be made to the
66370 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
66371 ** on the file.
66372 **
66373 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
66374 ** true (this flag is set if the Vdbe may modify more than one row and may
66375 ** throw an ABORT exception), a statement transaction may also be opened.
66376 ** More specifically, a statement transaction is opened iff the database
66377 ** connection is currently not in autocommit mode, or if there are other
66378 ** active statements. A statement transaction allows the changes made by this
66379 ** VDBE to be rolled back after an error without having to roll back the
66380 ** entire transaction. If no error is encountered, the statement transaction
66381 ** will automatically commit when the VDBE halts.
66382 **
66383 ** If P2 is zero, then a read-lock is obtained on the database file.
66384 */
66385 case OP_Transaction: {
66386 #if 0  /* local variables moved into u.at */
66387   Btree *pBt;
66388 #endif /* local variables moved into u.at */
66389
66390   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66391   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66392   u.at.pBt = db->aDb[pOp->p1].pBt;
66393
66394   if( u.at.pBt ){
66395     rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
66396     if( rc==SQLITE_BUSY ){
66397       p->pc = pc;
66398       p->rc = rc = SQLITE_BUSY;
66399       goto vdbe_return;
66400     }
66401     if( rc!=SQLITE_OK ){
66402       goto abort_due_to_error;
66403     }
66404
66405     if( pOp->p2 && p->usesStmtJournal
66406      && (db->autoCommit==0 || db->activeVdbeCnt>1)
66407     ){
66408       assert( sqlite3BtreeIsInTrans(u.at.pBt) );
66409       if( p->iStatement==0 ){
66410         assert( db->nStatement>=0 && db->nSavepoint>=0 );
66411         db->nStatement++;
66412         p->iStatement = db->nSavepoint + db->nStatement;
66413       }
66414
66415       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
66416       if( rc==SQLITE_OK ){
66417         rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
66418       }
66419
66420       /* Store the current value of the database handles deferred constraint
66421       ** counter. If the statement transaction needs to be rolled back,
66422       ** the value of this counter needs to be restored too.  */
66423       p->nStmtDefCons = db->nDeferredCons;
66424     }
66425   }
66426   break;
66427 }
66428
66429 /* Opcode: ReadCookie P1 P2 P3 * *
66430 **
66431 ** Read cookie number P3 from database P1 and write it into register P2.
66432 ** P3==1 is the schema version.  P3==2 is the database format.
66433 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
66434 ** the main database file and P1==1 is the database file used to store
66435 ** temporary tables.
66436 **
66437 ** There must be a read-lock on the database (either a transaction
66438 ** must be started or there must be an open cursor) before
66439 ** executing this instruction.
66440 */
66441 case OP_ReadCookie: {               /* out2-prerelease */
66442 #if 0  /* local variables moved into u.au */
66443   int iMeta;
66444   int iDb;
66445   int iCookie;
66446 #endif /* local variables moved into u.au */
66447
66448   u.au.iDb = pOp->p1;
66449   u.au.iCookie = pOp->p3;
66450   assert( pOp->p3<SQLITE_N_BTREE_META );
66451   assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
66452   assert( db->aDb[u.au.iDb].pBt!=0 );
66453   assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
66454
66455   sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
66456   pOut->u.i = u.au.iMeta;
66457   break;
66458 }
66459
66460 /* Opcode: SetCookie P1 P2 P3 * *
66461 **
66462 ** Write the content of register P3 (interpreted as an integer)
66463 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
66464 ** P2==2 is the database format. P2==3 is the recommended pager cache 
66465 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
66466 ** database file used to store temporary tables.
66467 **
66468 ** A transaction must be started before executing this opcode.
66469 */
66470 case OP_SetCookie: {       /* in3 */
66471 #if 0  /* local variables moved into u.av */
66472   Db *pDb;
66473 #endif /* local variables moved into u.av */
66474   assert( pOp->p2<SQLITE_N_BTREE_META );
66475   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66476   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66477   u.av.pDb = &db->aDb[pOp->p1];
66478   assert( u.av.pDb->pBt!=0 );
66479   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66480   pIn3 = &aMem[pOp->p3];
66481   sqlite3VdbeMemIntegerify(pIn3);
66482   /* See note about index shifting on OP_ReadCookie */
66483   rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
66484   if( pOp->p2==BTREE_SCHEMA_VERSION ){
66485     /* When the schema cookie changes, record the new cookie internally */
66486     u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
66487     db->flags |= SQLITE_InternChanges;
66488   }else if( pOp->p2==BTREE_FILE_FORMAT ){
66489     /* Record changes in the file format */
66490     u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
66491   }
66492   if( pOp->p1==1 ){
66493     /* Invalidate all prepared statements whenever the TEMP database
66494     ** schema is changed.  Ticket #1644 */
66495     sqlite3ExpirePreparedStatements(db);
66496     p->expired = 0;
66497   }
66498   break;
66499 }
66500
66501 /* Opcode: VerifyCookie P1 P2 P3 * *
66502 **
66503 ** Check the value of global database parameter number 0 (the
66504 ** schema version) and make sure it is equal to P2 and that the
66505 ** generation counter on the local schema parse equals P3.
66506 **
66507 ** P1 is the database number which is 0 for the main database file
66508 ** and 1 for the file holding temporary tables and some higher number
66509 ** for auxiliary databases.
66510 **
66511 ** The cookie changes its value whenever the database schema changes.
66512 ** This operation is used to detect when that the cookie has changed
66513 ** and that the current process needs to reread the schema.
66514 **
66515 ** Either a transaction needs to have been started or an OP_Open needs
66516 ** to be executed (to establish a read lock) before this opcode is
66517 ** invoked.
66518 */
66519 case OP_VerifyCookie: {
66520 #if 0  /* local variables moved into u.aw */
66521   int iMeta;
66522   int iGen;
66523   Btree *pBt;
66524 #endif /* local variables moved into u.aw */
66525
66526   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66527   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66528   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66529   u.aw.pBt = db->aDb[pOp->p1].pBt;
66530   if( u.aw.pBt ){
66531     sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
66532     u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
66533   }else{
66534     u.aw.iGen = u.aw.iMeta = 0;
66535   }
66536   if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
66537     sqlite3DbFree(db, p->zErrMsg);
66538     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
66539     /* If the schema-cookie from the database file matches the cookie
66540     ** stored with the in-memory representation of the schema, do
66541     ** not reload the schema from the database file.
66542     **
66543     ** If virtual-tables are in use, this is not just an optimization.
66544     ** Often, v-tables store their data in other SQLite tables, which
66545     ** are queried from within xNext() and other v-table methods using
66546     ** prepared queries. If such a query is out-of-date, we do not want to
66547     ** discard the database schema, as the user code implementing the
66548     ** v-table would have to be ready for the sqlite3_vtab structure itself
66549     ** to be invalidated whenever sqlite3_step() is called from within
66550     ** a v-table method.
66551     */
66552     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
66553       sqlite3ResetOneSchema(db, pOp->p1);
66554     }
66555
66556     p->expired = 1;
66557     rc = SQLITE_SCHEMA;
66558   }
66559   break;
66560 }
66561
66562 /* Opcode: OpenRead P1 P2 P3 P4 P5
66563 **
66564 ** Open a read-only cursor for the database table whose root page is
66565 ** P2 in a database file.  The database file is determined by P3. 
66566 ** P3==0 means the main database, P3==1 means the database used for 
66567 ** temporary tables, and P3>1 means used the corresponding attached
66568 ** database.  Give the new cursor an identifier of P1.  The P1
66569 ** values need not be contiguous but all P1 values should be small integers.
66570 ** It is an error for P1 to be negative.
66571 **
66572 ** If P5!=0 then use the content of register P2 as the root page, not
66573 ** the value of P2 itself.
66574 **
66575 ** There will be a read lock on the database whenever there is an
66576 ** open cursor.  If the database was unlocked prior to this instruction
66577 ** then a read lock is acquired as part of this instruction.  A read
66578 ** lock allows other processes to read the database but prohibits
66579 ** any other process from modifying the database.  The read lock is
66580 ** released when all cursors are closed.  If this instruction attempts
66581 ** to get a read lock but fails, the script terminates with an
66582 ** SQLITE_BUSY error code.
66583 **
66584 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66585 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
66586 ** structure, then said structure defines the content and collating 
66587 ** sequence of the index being opened. Otherwise, if P4 is an integer 
66588 ** value, it is set to the number of columns in the table.
66589 **
66590 ** See also OpenWrite.
66591 */
66592 /* Opcode: OpenWrite P1 P2 P3 P4 P5
66593 **
66594 ** Open a read/write cursor named P1 on the table or index whose root
66595 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
66596 ** root page.
66597 **
66598 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66599 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
66600 ** structure, then said structure defines the content and collating 
66601 ** sequence of the index being opened. Otherwise, if P4 is an integer 
66602 ** value, it is set to the number of columns in the table, or to the
66603 ** largest index of any column of the table that is actually used.
66604 **
66605 ** This instruction works just like OpenRead except that it opens the cursor
66606 ** in read/write mode.  For a given table, there can be one or more read-only
66607 ** cursors or a single read/write cursor but not both.
66608 **
66609 ** See also OpenRead.
66610 */
66611 case OP_OpenRead:
66612 case OP_OpenWrite: {
66613 #if 0  /* local variables moved into u.ax */
66614   int nField;
66615   KeyInfo *pKeyInfo;
66616   int p2;
66617   int iDb;
66618   int wrFlag;
66619   Btree *pX;
66620   VdbeCursor *pCur;
66621   Db *pDb;
66622 #endif /* local variables moved into u.ax */
66623
66624   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
66625   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
66626
66627   if( p->expired ){
66628     rc = SQLITE_ABORT;
66629     break;
66630   }
66631
66632   u.ax.nField = 0;
66633   u.ax.pKeyInfo = 0;
66634   u.ax.p2 = pOp->p2;
66635   u.ax.iDb = pOp->p3;
66636   assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
66637   assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
66638   u.ax.pDb = &db->aDb[u.ax.iDb];
66639   u.ax.pX = u.ax.pDb->pBt;
66640   assert( u.ax.pX!=0 );
66641   if( pOp->opcode==OP_OpenWrite ){
66642     u.ax.wrFlag = 1;
66643     assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
66644     if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
66645       p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
66646     }
66647   }else{
66648     u.ax.wrFlag = 0;
66649   }
66650   if( pOp->p5 & OPFLAG_P2ISREG ){
66651     assert( u.ax.p2>0 );
66652     assert( u.ax.p2<=p->nMem );
66653     pIn2 = &aMem[u.ax.p2];
66654     assert( memIsValid(pIn2) );
66655     assert( (pIn2->flags & MEM_Int)!=0 );
66656     sqlite3VdbeMemIntegerify(pIn2);
66657     u.ax.p2 = (int)pIn2->u.i;
66658     /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
66659     ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
66660     ** If there were a failure, the prepared statement would have halted
66661     ** before reaching this instruction. */
66662     if( NEVER(u.ax.p2<2) ) {
66663       rc = SQLITE_CORRUPT_BKPT;
66664       goto abort_due_to_error;
66665     }
66666   }
66667   if( pOp->p4type==P4_KEYINFO ){
66668     u.ax.pKeyInfo = pOp->p4.pKeyInfo;
66669     u.ax.pKeyInfo->enc = ENC(p->db);
66670     u.ax.nField = u.ax.pKeyInfo->nField+1;
66671   }else if( pOp->p4type==P4_INT32 ){
66672     u.ax.nField = pOp->p4.i;
66673   }
66674   assert( pOp->p1>=0 );
66675   u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
66676   if( u.ax.pCur==0 ) goto no_mem;
66677   u.ax.pCur->nullRow = 1;
66678   u.ax.pCur->isOrdered = 1;
66679   rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
66680   u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
66681   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
66682   sqlite3BtreeCursorHints(u.ax.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
66683
66684   /* Since it performs no memory allocation or IO, the only value that
66685   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
66686   assert( rc==SQLITE_OK );
66687
66688   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
66689   ** SQLite used to check if the root-page flags were sane at this point
66690   ** and report database corruption if they were not, but this check has
66691   ** since moved into the btree layer.  */
66692   u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
66693   u.ax.pCur->isIndex = !u.ax.pCur->isTable;
66694   break;
66695 }
66696
66697 /* Opcode: OpenEphemeral P1 P2 * P4 P5
66698 **
66699 ** Open a new cursor P1 to a transient table.
66700 ** The cursor is always opened read/write even if 
66701 ** the main database is read-only.  The ephemeral
66702 ** table is deleted automatically when the cursor is closed.
66703 **
66704 ** P2 is the number of columns in the ephemeral table.
66705 ** The cursor points to a BTree table if P4==0 and to a BTree index
66706 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
66707 ** that defines the format of keys in the index.
66708 **
66709 ** This opcode was once called OpenTemp.  But that created
66710 ** confusion because the term "temp table", might refer either
66711 ** to a TEMP table at the SQL level, or to a table opened by
66712 ** this opcode.  Then this opcode was call OpenVirtual.  But
66713 ** that created confusion with the whole virtual-table idea.
66714 **
66715 ** The P5 parameter can be a mask of the BTREE_* flags defined
66716 ** in btree.h.  These flags control aspects of the operation of
66717 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
66718 ** added automatically.
66719 */
66720 /* Opcode: OpenAutoindex P1 P2 * P4 *
66721 **
66722 ** This opcode works the same as OP_OpenEphemeral.  It has a
66723 ** different name to distinguish its use.  Tables created using
66724 ** by this opcode will be used for automatically created transient
66725 ** indices in joins.
66726 */
66727 case OP_OpenAutoindex: 
66728 case OP_OpenEphemeral: {
66729 #if 0  /* local variables moved into u.ay */
66730   VdbeCursor *pCx;
66731 #endif /* local variables moved into u.ay */
66732   static const int vfsFlags =
66733       SQLITE_OPEN_READWRITE |
66734       SQLITE_OPEN_CREATE |
66735       SQLITE_OPEN_EXCLUSIVE |
66736       SQLITE_OPEN_DELETEONCLOSE |
66737       SQLITE_OPEN_TRANSIENT_DB;
66738
66739   assert( pOp->p1>=0 );
66740   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66741   if( u.ay.pCx==0 ) goto no_mem;
66742   u.ay.pCx->nullRow = 1;
66743   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
66744                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
66745   if( rc==SQLITE_OK ){
66746     rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
66747   }
66748   if( rc==SQLITE_OK ){
66749     /* If a transient index is required, create it by calling
66750     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
66751     ** opening it. If a transient table is required, just use the
66752     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
66753     */
66754     if( pOp->p4.pKeyInfo ){
66755       int pgno;
66756       assert( pOp->p4type==P4_KEYINFO );
66757       rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
66758       if( rc==SQLITE_OK ){
66759         assert( pgno==MASTER_ROOT+1 );
66760         rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
66761                                 (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
66762         u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66763         u.ay.pCx->pKeyInfo->enc = ENC(p->db);
66764       }
66765       u.ay.pCx->isTable = 0;
66766     }else{
66767       rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
66768       u.ay.pCx->isTable = 1;
66769     }
66770   }
66771   u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
66772   u.ay.pCx->isIndex = !u.ay.pCx->isTable;
66773   break;
66774 }
66775
66776 /* Opcode: OpenSorter P1 P2 * P4 *
66777 **
66778 ** This opcode works like OP_OpenEphemeral except that it opens
66779 ** a transient index that is specifically designed to sort large
66780 ** tables using an external merge-sort algorithm.
66781 */
66782 case OP_SorterOpen: {
66783 #if 0  /* local variables moved into u.az */
66784   VdbeCursor *pCx;
66785 #endif /* local variables moved into u.az */
66786 #ifndef SQLITE_OMIT_MERGE_SORT
66787   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66788   if( u.az.pCx==0 ) goto no_mem;
66789   u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66790   u.az.pCx->pKeyInfo->enc = ENC(p->db);
66791   u.az.pCx->isSorter = 1;
66792   rc = sqlite3VdbeSorterInit(db, u.az.pCx);
66793 #else
66794   pOp->opcode = OP_OpenEphemeral;
66795   pc--;
66796 #endif
66797   break;
66798 }
66799
66800 /* Opcode: OpenPseudo P1 P2 P3 * *
66801 **
66802 ** Open a new cursor that points to a fake table that contains a single
66803 ** row of data.  The content of that one row in the content of memory
66804 ** register P2.  In other words, cursor P1 becomes an alias for the 
66805 ** MEM_Blob content contained in register P2.
66806 **
66807 ** A pseudo-table created by this opcode is used to hold a single
66808 ** row output from the sorter so that the row can be decomposed into
66809 ** individual columns using the OP_Column opcode.  The OP_Column opcode
66810 ** is the only cursor opcode that works with a pseudo-table.
66811 **
66812 ** P3 is the number of fields in the records that will be stored by
66813 ** the pseudo-table.
66814 */
66815 case OP_OpenPseudo: {
66816 #if 0  /* local variables moved into u.ba */
66817   VdbeCursor *pCx;
66818 #endif /* local variables moved into u.ba */
66819
66820   assert( pOp->p1>=0 );
66821   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
66822   if( u.ba.pCx==0 ) goto no_mem;
66823   u.ba.pCx->nullRow = 1;
66824   u.ba.pCx->pseudoTableReg = pOp->p2;
66825   u.ba.pCx->isTable = 1;
66826   u.ba.pCx->isIndex = 0;
66827   break;
66828 }
66829
66830 /* Opcode: Close P1 * * * *
66831 **
66832 ** Close a cursor previously opened as P1.  If P1 is not
66833 ** currently open, this instruction is a no-op.
66834 */
66835 case OP_Close: {
66836   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66837   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
66838   p->apCsr[pOp->p1] = 0;
66839   break;
66840 }
66841
66842 /* Opcode: SeekGe P1 P2 P3 P4 *
66843 **
66844 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66845 ** use the value in register P3 as the key.  If cursor P1 refers 
66846 ** to an SQL index, then P3 is the first in an array of P4 registers 
66847 ** that are used as an unpacked index key. 
66848 **
66849 ** Reposition cursor P1 so that  it points to the smallest entry that 
66850 ** is greater than or equal to the key value. If there are no records 
66851 ** greater than or equal to the key and P2 is not zero, then jump to P2.
66852 **
66853 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
66854 */
66855 /* Opcode: SeekGt P1 P2 P3 P4 *
66856 **
66857 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66858 ** use the value in register P3 as a key. If cursor P1 refers 
66859 ** to an SQL index, then P3 is the first in an array of P4 registers 
66860 ** that are used as an unpacked index key. 
66861 **
66862 ** Reposition cursor P1 so that  it points to the smallest entry that 
66863 ** is greater than the key value. If there are no records greater than 
66864 ** the key and P2 is not zero, then jump to P2.
66865 **
66866 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
66867 */
66868 /* Opcode: SeekLt P1 P2 P3 P4 * 
66869 **
66870 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66871 ** use the value in register P3 as a key. If cursor P1 refers 
66872 ** to an SQL index, then P3 is the first in an array of P4 registers 
66873 ** that are used as an unpacked index key. 
66874 **
66875 ** Reposition cursor P1 so that  it points to the largest entry that 
66876 ** is less than the key value. If there are no records less than 
66877 ** the key and P2 is not zero, then jump to P2.
66878 **
66879 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
66880 */
66881 /* Opcode: SeekLe P1 P2 P3 P4 *
66882 **
66883 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66884 ** use the value in register P3 as a key. If cursor P1 refers 
66885 ** to an SQL index, then P3 is the first in an array of P4 registers 
66886 ** that are used as an unpacked index key. 
66887 **
66888 ** Reposition cursor P1 so that it points to the largest entry that 
66889 ** is less than or equal to the key value. If there are no records 
66890 ** less than or equal to the key and P2 is not zero, then jump to P2.
66891 **
66892 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
66893 */
66894 case OP_SeekLt:         /* jump, in3 */
66895 case OP_SeekLe:         /* jump, in3 */
66896 case OP_SeekGe:         /* jump, in3 */
66897 case OP_SeekGt: {       /* jump, in3 */
66898 #if 0  /* local variables moved into u.bb */
66899   int res;
66900   int oc;
66901   VdbeCursor *pC;
66902   UnpackedRecord r;
66903   int nField;
66904   i64 iKey;      /* The rowid we are to seek to */
66905 #endif /* local variables moved into u.bb */
66906
66907   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66908   assert( pOp->p2!=0 );
66909   u.bb.pC = p->apCsr[pOp->p1];
66910   assert( u.bb.pC!=0 );
66911   assert( u.bb.pC->pseudoTableReg==0 );
66912   assert( OP_SeekLe == OP_SeekLt+1 );
66913   assert( OP_SeekGe == OP_SeekLt+2 );
66914   assert( OP_SeekGt == OP_SeekLt+3 );
66915   assert( u.bb.pC->isOrdered );
66916   if( ALWAYS(u.bb.pC->pCursor!=0) ){
66917     u.bb.oc = pOp->opcode;
66918     u.bb.pC->nullRow = 0;
66919     if( u.bb.pC->isTable ){
66920       /* The input value in P3 might be of any type: integer, real, string,
66921       ** blob, or NULL.  But it needs to be an integer before we can do
66922       ** the seek, so covert it. */
66923       pIn3 = &aMem[pOp->p3];
66924       applyNumericAffinity(pIn3);
66925       u.bb.iKey = sqlite3VdbeIntValue(pIn3);
66926       u.bb.pC->rowidIsValid = 0;
66927
66928       /* If the P3 value could not be converted into an integer without
66929       ** loss of information, then special processing is required... */
66930       if( (pIn3->flags & MEM_Int)==0 ){
66931         if( (pIn3->flags & MEM_Real)==0 ){
66932           /* If the P3 value cannot be converted into any kind of a number,
66933           ** then the seek is not possible, so jump to P2 */
66934           pc = pOp->p2 - 1;
66935           break;
66936         }
66937         /* If we reach this point, then the P3 value must be a floating
66938         ** point number. */
66939         assert( (pIn3->flags & MEM_Real)!=0 );
66940
66941         if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
66942           /* The P3 value is too large in magnitude to be expressed as an
66943           ** integer. */
66944           u.bb.res = 1;
66945           if( pIn3->r<0 ){
66946             if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
66947               rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
66948               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66949             }
66950           }else{
66951             if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
66952               rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
66953               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66954             }
66955           }
66956           if( u.bb.res ){
66957             pc = pOp->p2 - 1;
66958           }
66959           break;
66960         }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
66961           /* Use the ceiling() function to convert real->int */
66962           if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
66963         }else{
66964           /* Use the floor() function to convert real->int */
66965           assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
66966           if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
66967         }
66968       }
66969       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
66970       if( rc!=SQLITE_OK ){
66971         goto abort_due_to_error;
66972       }
66973       if( u.bb.res==0 ){
66974         u.bb.pC->rowidIsValid = 1;
66975         u.bb.pC->lastRowid = u.bb.iKey;
66976       }
66977     }else{
66978       u.bb.nField = pOp->p4.i;
66979       assert( pOp->p4type==P4_INT32 );
66980       assert( u.bb.nField>0 );
66981       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
66982       u.bb.r.nField = (u16)u.bb.nField;
66983
66984       /* The next line of code computes as follows, only faster:
66985       **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
66986       **     u.bb.r.flags = UNPACKED_INCRKEY;
66987       **   }else{
66988       **     u.bb.r.flags = 0;
66989       **   }
66990       */
66991       u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
66992       assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
66993       assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
66994       assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
66995       assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
66996
66997       u.bb.r.aMem = &aMem[pOp->p3];
66998 #ifdef SQLITE_DEBUG
66999       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
67000 #endif
67001       ExpandBlob(u.bb.r.aMem);
67002       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
67003       if( rc!=SQLITE_OK ){
67004         goto abort_due_to_error;
67005       }
67006       u.bb.pC->rowidIsValid = 0;
67007     }
67008     u.bb.pC->deferredMoveto = 0;
67009     u.bb.pC->cacheStatus = CACHE_STALE;
67010 #ifdef SQLITE_TEST
67011     sqlite3_search_count++;
67012 #endif
67013     if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
67014       if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
67015         rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
67016         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67017         u.bb.pC->rowidIsValid = 0;
67018       }else{
67019         u.bb.res = 0;
67020       }
67021     }else{
67022       assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
67023       if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
67024         rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
67025         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67026         u.bb.pC->rowidIsValid = 0;
67027       }else{
67028         /* u.bb.res might be negative because the table is empty.  Check to
67029         ** see if this is the case.
67030         */
67031         u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
67032       }
67033     }
67034     assert( pOp->p2>0 );
67035     if( u.bb.res ){
67036       pc = pOp->p2 - 1;
67037     }
67038   }else{
67039     /* This happens when attempting to open the sqlite3_master table
67040     ** for read access returns SQLITE_EMPTY. In this case always
67041     ** take the jump (since there are no records in the table).
67042     */
67043     pc = pOp->p2 - 1;
67044   }
67045   break;
67046 }
67047
67048 /* Opcode: Seek P1 P2 * * *
67049 **
67050 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
67051 ** for P1 to move so that it points to the rowid given by P2.
67052 **
67053 ** This is actually a deferred seek.  Nothing actually happens until
67054 ** the cursor is used to read a record.  That way, if no reads
67055 ** occur, no unnecessary I/O happens.
67056 */
67057 case OP_Seek: {    /* in2 */
67058 #if 0  /* local variables moved into u.bc */
67059   VdbeCursor *pC;
67060 #endif /* local variables moved into u.bc */
67061
67062   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67063   u.bc.pC = p->apCsr[pOp->p1];
67064   assert( u.bc.pC!=0 );
67065   if( ALWAYS(u.bc.pC->pCursor!=0) ){
67066     assert( u.bc.pC->isTable );
67067     u.bc.pC->nullRow = 0;
67068     pIn2 = &aMem[pOp->p2];
67069     u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
67070     u.bc.pC->rowidIsValid = 0;
67071     u.bc.pC->deferredMoveto = 1;
67072   }
67073   break;
67074 }
67075   
67076
67077 /* Opcode: Found P1 P2 P3 P4 *
67078 **
67079 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67080 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67081 ** record.
67082 **
67083 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67084 ** is a prefix of any entry in P1 then a jump is made to P2 and
67085 ** P1 is left pointing at the matching entry.
67086 */
67087 /* Opcode: NotFound P1 P2 P3 P4 *
67088 **
67089 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67090 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67091 ** record.
67092 ** 
67093 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67094 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
67095 ** does contain an entry whose prefix matches the P3/P4 record then control
67096 ** falls through to the next instruction and P1 is left pointing at the
67097 ** matching entry.
67098 **
67099 ** See also: Found, NotExists, IsUnique
67100 */
67101 case OP_NotFound:       /* jump, in3 */
67102 case OP_Found: {        /* jump, in3 */
67103 #if 0  /* local variables moved into u.bd */
67104   int alreadyExists;
67105   VdbeCursor *pC;
67106   int res;
67107   char *pFree;
67108   UnpackedRecord *pIdxKey;
67109   UnpackedRecord r;
67110   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67111 #endif /* local variables moved into u.bd */
67112
67113 #ifdef SQLITE_TEST
67114   sqlite3_found_count++;
67115 #endif
67116
67117   u.bd.alreadyExists = 0;
67118   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67119   assert( pOp->p4type==P4_INT32 );
67120   u.bd.pC = p->apCsr[pOp->p1];
67121   assert( u.bd.pC!=0 );
67122   pIn3 = &aMem[pOp->p3];
67123   if( ALWAYS(u.bd.pC->pCursor!=0) ){
67124
67125     assert( u.bd.pC->isTable==0 );
67126     if( pOp->p4.i>0 ){
67127       u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
67128       u.bd.r.nField = (u16)pOp->p4.i;
67129       u.bd.r.aMem = pIn3;
67130 #ifdef SQLITE_DEBUG
67131       { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
67132 #endif
67133       u.bd.r.flags = UNPACKED_PREFIX_MATCH;
67134       u.bd.pIdxKey = &u.bd.r;
67135     }else{
67136       u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67137           u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
67138       );
67139       if( u.bd.pIdxKey==0 ) goto no_mem;
67140       assert( pIn3->flags & MEM_Blob );
67141       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
67142       sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
67143       u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67144     }
67145     rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
67146     if( pOp->p4.i==0 ){
67147       sqlite3DbFree(db, u.bd.pFree);
67148     }
67149     if( rc!=SQLITE_OK ){
67150       break;
67151     }
67152     u.bd.alreadyExists = (u.bd.res==0);
67153     u.bd.pC->deferredMoveto = 0;
67154     u.bd.pC->cacheStatus = CACHE_STALE;
67155   }
67156   if( pOp->opcode==OP_Found ){
67157     if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
67158   }else{
67159     if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
67160   }
67161   break;
67162 }
67163
67164 /* Opcode: IsUnique P1 P2 P3 P4 *
67165 **
67166 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67167 ** no data and where the key are records generated by OP_MakeRecord with
67168 ** the list field being the integer ROWID of the entry that the index
67169 ** entry refers to.
67170 **
67171 ** The P3 register contains an integer record number. Call this record 
67172 ** number R. Register P4 is the first in a set of N contiguous registers
67173 ** that make up an unpacked index key that can be used with cursor P1.
67174 ** The value of N can be inferred from the cursor. N includes the rowid
67175 ** value appended to the end of the index record. This rowid value may
67176 ** or may not be the same as R.
67177 **
67178 ** If any of the N registers beginning with register P4 contains a NULL
67179 ** value, jump immediately to P2.
67180 **
67181 ** Otherwise, this instruction checks if cursor P1 contains an entry
67182 ** where the first (N-1) fields match but the rowid value at the end
67183 ** of the index entry is not R. If there is no such entry, control jumps
67184 ** to instruction P2. Otherwise, the rowid of the conflicting index
67185 ** entry is copied to register P3 and control falls through to the next
67186 ** instruction.
67187 **
67188 ** See also: NotFound, NotExists, Found
67189 */
67190 case OP_IsUnique: {        /* jump, in3 */
67191 #if 0  /* local variables moved into u.be */
67192   u16 ii;
67193   VdbeCursor *pCx;
67194   BtCursor *pCrsr;
67195   u16 nField;
67196   Mem *aMx;
67197   UnpackedRecord r;                  /* B-Tree index search key */
67198   i64 R;                             /* Rowid stored in register P3 */
67199 #endif /* local variables moved into u.be */
67200
67201   pIn3 = &aMem[pOp->p3];
67202   u.be.aMx = &aMem[pOp->p4.i];
67203   /* Assert that the values of parameters P1 and P4 are in range. */
67204   assert( pOp->p4type==P4_INT32 );
67205   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67206   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67207
67208   /* Find the index cursor. */
67209   u.be.pCx = p->apCsr[pOp->p1];
67210   assert( u.be.pCx->deferredMoveto==0 );
67211   u.be.pCx->seekResult = 0;
67212   u.be.pCx->cacheStatus = CACHE_STALE;
67213   u.be.pCrsr = u.be.pCx->pCursor;
67214
67215   /* If any of the values are NULL, take the jump. */
67216   u.be.nField = u.be.pCx->pKeyInfo->nField;
67217   for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
67218     if( u.be.aMx[u.be.ii].flags & MEM_Null ){
67219       pc = pOp->p2 - 1;
67220       u.be.pCrsr = 0;
67221       break;
67222     }
67223   }
67224   assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
67225
67226   if( u.be.pCrsr!=0 ){
67227     /* Populate the index search key. */
67228     u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
67229     u.be.r.nField = u.be.nField + 1;
67230     u.be.r.flags = UNPACKED_PREFIX_SEARCH;
67231     u.be.r.aMem = u.be.aMx;
67232 #ifdef SQLITE_DEBUG
67233     { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
67234 #endif
67235
67236     /* Extract the value of u.be.R from register P3. */
67237     sqlite3VdbeMemIntegerify(pIn3);
67238     u.be.R = pIn3->u.i;
67239
67240     /* Search the B-Tree index. If no conflicting record is found, jump
67241     ** to P2. Otherwise, copy the rowid of the conflicting record to
67242     ** register P3 and fall through to the next instruction.  */
67243     rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
67244     if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
67245       pc = pOp->p2 - 1;
67246     }else{
67247       pIn3->u.i = u.be.r.rowid;
67248     }
67249   }
67250   break;
67251 }
67252
67253 /* Opcode: NotExists P1 P2 P3 * *
67254 **
67255 ** Use the content of register P3 as an integer key.  If a record 
67256 ** with that key does not exist in table of P1, then jump to P2. 
67257 ** If the record does exist, then fall through.  The cursor is left 
67258 ** pointing to the record if it exists.
67259 **
67260 ** The difference between this operation and NotFound is that this
67261 ** operation assumes the key is an integer and that P1 is a table whereas
67262 ** NotFound assumes key is a blob constructed from MakeRecord and
67263 ** P1 is an index.
67264 **
67265 ** See also: Found, NotFound, IsUnique
67266 */
67267 case OP_NotExists: {        /* jump, in3 */
67268 #if 0  /* local variables moved into u.bf */
67269   VdbeCursor *pC;
67270   BtCursor *pCrsr;
67271   int res;
67272   u64 iKey;
67273 #endif /* local variables moved into u.bf */
67274
67275   pIn3 = &aMem[pOp->p3];
67276   assert( pIn3->flags & MEM_Int );
67277   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67278   u.bf.pC = p->apCsr[pOp->p1];
67279   assert( u.bf.pC!=0 );
67280   assert( u.bf.pC->isTable );
67281   assert( u.bf.pC->pseudoTableReg==0 );
67282   u.bf.pCrsr = u.bf.pC->pCursor;
67283   if( ALWAYS(u.bf.pCrsr!=0) ){
67284     u.bf.res = 0;
67285     u.bf.iKey = pIn3->u.i;
67286     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
67287     u.bf.pC->lastRowid = pIn3->u.i;
67288     u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
67289     u.bf.pC->nullRow = 0;
67290     u.bf.pC->cacheStatus = CACHE_STALE;
67291     u.bf.pC->deferredMoveto = 0;
67292     if( u.bf.res!=0 ){
67293       pc = pOp->p2 - 1;
67294       assert( u.bf.pC->rowidIsValid==0 );
67295     }
67296     u.bf.pC->seekResult = u.bf.res;
67297   }else{
67298     /* This happens when an attempt to open a read cursor on the
67299     ** sqlite_master table returns SQLITE_EMPTY.
67300     */
67301     pc = pOp->p2 - 1;
67302     assert( u.bf.pC->rowidIsValid==0 );
67303     u.bf.pC->seekResult = 0;
67304   }
67305   break;
67306 }
67307
67308 /* Opcode: Sequence P1 P2 * * *
67309 **
67310 ** Find the next available sequence number for cursor P1.
67311 ** Write the sequence number into register P2.
67312 ** The sequence number on the cursor is incremented after this
67313 ** instruction.  
67314 */
67315 case OP_Sequence: {           /* out2-prerelease */
67316   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67317   assert( p->apCsr[pOp->p1]!=0 );
67318   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67319   break;
67320 }
67321
67322
67323 /* Opcode: NewRowid P1 P2 P3 * *
67324 **
67325 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
67326 ** The record number is not previously used as a key in the database
67327 ** table that cursor P1 points to.  The new record number is written
67328 ** written to register P2.
67329 **
67330 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
67331 ** the largest previously generated record number. No new record numbers are
67332 ** allowed to be less than this value. When this value reaches its maximum, 
67333 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
67334 ** generated record number. This P3 mechanism is used to help implement the
67335 ** AUTOINCREMENT feature.
67336 */
67337 case OP_NewRowid: {           /* out2-prerelease */
67338 #if 0  /* local variables moved into u.bg */
67339   i64 v;                 /* The new rowid */
67340   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
67341   int res;               /* Result of an sqlite3BtreeLast() */
67342   int cnt;               /* Counter to limit the number of searches */
67343   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
67344   VdbeFrame *pFrame;     /* Root frame of VDBE */
67345 #endif /* local variables moved into u.bg */
67346
67347   u.bg.v = 0;
67348   u.bg.res = 0;
67349   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67350   u.bg.pC = p->apCsr[pOp->p1];
67351   assert( u.bg.pC!=0 );
67352   if( NEVER(u.bg.pC->pCursor==0) ){
67353     /* The zero initialization above is all that is needed */
67354   }else{
67355     /* The next rowid or record number (different terms for the same
67356     ** thing) is obtained in a two-step algorithm.
67357     **
67358     ** First we attempt to find the largest existing rowid and add one
67359     ** to that.  But if the largest existing rowid is already the maximum
67360     ** positive integer, we have to fall through to the second
67361     ** probabilistic algorithm
67362     **
67363     ** The second algorithm is to select a rowid at random and see if
67364     ** it already exists in the table.  If it does not exist, we have
67365     ** succeeded.  If the random rowid does exist, we select a new one
67366     ** and try again, up to 100 times.
67367     */
67368     assert( u.bg.pC->isTable );
67369
67370 #ifdef SQLITE_32BIT_ROWID
67371 #   define MAX_ROWID 0x7fffffff
67372 #else
67373     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
67374     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
67375     ** to provide the constant while making all compilers happy.
67376     */
67377 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
67378 #endif
67379
67380     if( !u.bg.pC->useRandomRowid ){
67381       u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
67382       if( u.bg.v==0 ){
67383         rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
67384         if( rc!=SQLITE_OK ){
67385           goto abort_due_to_error;
67386         }
67387         if( u.bg.res ){
67388           u.bg.v = 1;   /* IMP: R-61914-48074 */
67389         }else{
67390           assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
67391           rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
67392           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
67393           if( u.bg.v>=MAX_ROWID ){
67394             u.bg.pC->useRandomRowid = 1;
67395           }else{
67396             u.bg.v++;   /* IMP: R-29538-34987 */
67397           }
67398         }
67399       }
67400
67401 #ifndef SQLITE_OMIT_AUTOINCREMENT
67402       if( pOp->p3 ){
67403         /* Assert that P3 is a valid memory cell. */
67404         assert( pOp->p3>0 );
67405         if( p->pFrame ){
67406           for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
67407           /* Assert that P3 is a valid memory cell. */
67408           assert( pOp->p3<=u.bg.pFrame->nMem );
67409           u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
67410         }else{
67411           /* Assert that P3 is a valid memory cell. */
67412           assert( pOp->p3<=p->nMem );
67413           u.bg.pMem = &aMem[pOp->p3];
67414           memAboutToChange(p, u.bg.pMem);
67415         }
67416         assert( memIsValid(u.bg.pMem) );
67417
67418         REGISTER_TRACE(pOp->p3, u.bg.pMem);
67419         sqlite3VdbeMemIntegerify(u.bg.pMem);
67420         assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
67421         if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
67422           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
67423           goto abort_due_to_error;
67424         }
67425         if( u.bg.v<u.bg.pMem->u.i+1 ){
67426           u.bg.v = u.bg.pMem->u.i + 1;
67427         }
67428         u.bg.pMem->u.i = u.bg.v;
67429       }
67430 #endif
67431
67432       sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
67433     }
67434     if( u.bg.pC->useRandomRowid ){
67435       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
67436       ** largest possible integer (9223372036854775807) then the database
67437       ** engine starts picking positive candidate ROWIDs at random until
67438       ** it finds one that is not previously used. */
67439       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
67440                              ** an AUTOINCREMENT table. */
67441       /* on the first attempt, simply do one more than previous */
67442       u.bg.v = lastRowid;
67443       u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67444       u.bg.v++; /* ensure non-zero */
67445       u.bg.cnt = 0;
67446       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
67447                                                  0, &u.bg.res))==SQLITE_OK)
67448             && (u.bg.res==0)
67449             && (++u.bg.cnt<100)){
67450         /* collision - try another random rowid */
67451         sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
67452         if( u.bg.cnt<5 ){
67453           /* try "small" random rowids for the initial attempts */
67454           u.bg.v &= 0xffffff;
67455         }else{
67456           u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67457         }
67458         u.bg.v++; /* ensure non-zero */
67459       }
67460       if( rc==SQLITE_OK && u.bg.res==0 ){
67461         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
67462         goto abort_due_to_error;
67463       }
67464       assert( u.bg.v>0 );  /* EV: R-40812-03570 */
67465     }
67466     u.bg.pC->rowidIsValid = 0;
67467     u.bg.pC->deferredMoveto = 0;
67468     u.bg.pC->cacheStatus = CACHE_STALE;
67469   }
67470   pOut->u.i = u.bg.v;
67471   break;
67472 }
67473
67474 /* Opcode: Insert P1 P2 P3 P4 P5
67475 **
67476 ** Write an entry into the table of cursor P1.  A new entry is
67477 ** created if it doesn't already exist or the data for an existing
67478 ** entry is overwritten.  The data is the value MEM_Blob stored in register
67479 ** number P2. The key is stored in register P3. The key must
67480 ** be a MEM_Int.
67481 **
67482 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
67483 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
67484 ** then rowid is stored for subsequent return by the
67485 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
67486 **
67487 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
67488 ** the last seek operation (OP_NotExists) was a success, then this
67489 ** operation will not attempt to find the appropriate row before doing
67490 ** the insert but will instead overwrite the row that the cursor is
67491 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
67492 ** has already positioned the cursor correctly.  This is an optimization
67493 ** that boosts performance by avoiding redundant seeks.
67494 **
67495 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
67496 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
67497 ** is part of an INSERT operation.  The difference is only important to
67498 ** the update hook.
67499 **
67500 ** Parameter P4 may point to a string containing the table-name, or
67501 ** may be NULL. If it is not NULL, then the update-hook 
67502 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
67503 **
67504 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
67505 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
67506 ** and register P2 becomes ephemeral.  If the cursor is changed, the
67507 ** value of register P2 will then change.  Make sure this does not
67508 ** cause any problems.)
67509 **
67510 ** This instruction only works on tables.  The equivalent instruction
67511 ** for indices is OP_IdxInsert.
67512 */
67513 /* Opcode: InsertInt P1 P2 P3 P4 P5
67514 **
67515 ** This works exactly like OP_Insert except that the key is the
67516 ** integer value P3, not the value of the integer stored in register P3.
67517 */
67518 case OP_Insert: 
67519 case OP_InsertInt: {
67520 #if 0  /* local variables moved into u.bh */
67521   Mem *pData;       /* MEM cell holding data for the record to be inserted */
67522   Mem *pKey;        /* MEM cell holding key  for the record */
67523   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
67524   VdbeCursor *pC;   /* Cursor to table into which insert is written */
67525   int nZero;        /* Number of zero-bytes to append */
67526   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
67527   const char *zDb;  /* database name - used by the update hook */
67528   const char *zTbl; /* Table name - used by the opdate hook */
67529   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
67530 #endif /* local variables moved into u.bh */
67531
67532   u.bh.pData = &aMem[pOp->p2];
67533   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67534   assert( memIsValid(u.bh.pData) );
67535   u.bh.pC = p->apCsr[pOp->p1];
67536   assert( u.bh.pC!=0 );
67537   assert( u.bh.pC->pCursor!=0 );
67538   assert( u.bh.pC->pseudoTableReg==0 );
67539   assert( u.bh.pC->isTable );
67540   REGISTER_TRACE(pOp->p2, u.bh.pData);
67541
67542   if( pOp->opcode==OP_Insert ){
67543     u.bh.pKey = &aMem[pOp->p3];
67544     assert( u.bh.pKey->flags & MEM_Int );
67545     assert( memIsValid(u.bh.pKey) );
67546     REGISTER_TRACE(pOp->p3, u.bh.pKey);
67547     u.bh.iKey = u.bh.pKey->u.i;
67548   }else{
67549     assert( pOp->opcode==OP_InsertInt );
67550     u.bh.iKey = pOp->p3;
67551   }
67552
67553   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
67554   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
67555   if( u.bh.pData->flags & MEM_Null ){
67556     u.bh.pData->z = 0;
67557     u.bh.pData->n = 0;
67558   }else{
67559     assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
67560   }
67561   u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
67562   if( u.bh.pData->flags & MEM_Zero ){
67563     u.bh.nZero = u.bh.pData->u.nZero;
67564   }else{
67565     u.bh.nZero = 0;
67566   }
67567   sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
67568   rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
67569                           u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
67570                           pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
67571   );
67572   u.bh.pC->rowidIsValid = 0;
67573   u.bh.pC->deferredMoveto = 0;
67574   u.bh.pC->cacheStatus = CACHE_STALE;
67575
67576   /* Invoke the update-hook if required. */
67577   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67578     u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
67579     u.bh.zTbl = pOp->p4.z;
67580     u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
67581     assert( u.bh.pC->isTable );
67582     db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
67583     assert( u.bh.pC->iDb>=0 );
67584   }
67585   break;
67586 }
67587
67588 /* Opcode: Delete P1 P2 * P4 *
67589 **
67590 ** Delete the record at which the P1 cursor is currently pointing.
67591 **
67592 ** The cursor will be left pointing at either the next or the previous
67593 ** record in the table. If it is left pointing at the next record, then
67594 ** the next Next instruction will be a no-op.  Hence it is OK to delete
67595 ** a record from within an Next loop.
67596 **
67597 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
67598 ** incremented (otherwise not).
67599 **
67600 ** P1 must not be pseudo-table.  It has to be a real table with
67601 ** multiple rows.
67602 **
67603 ** If P4 is not NULL, then it is the name of the table that P1 is
67604 ** pointing to.  The update hook will be invoked, if it exists.
67605 ** If P4 is not NULL then the P1 cursor must have been positioned
67606 ** using OP_NotFound prior to invoking this opcode.
67607 */
67608 case OP_Delete: {
67609 #if 0  /* local variables moved into u.bi */
67610   i64 iKey;
67611   VdbeCursor *pC;
67612 #endif /* local variables moved into u.bi */
67613
67614   u.bi.iKey = 0;
67615   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67616   u.bi.pC = p->apCsr[pOp->p1];
67617   assert( u.bi.pC!=0 );
67618   assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
67619
67620   /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
67621   ** row being deleted.
67622   */
67623   if( db->xUpdateCallback && pOp->p4.z ){
67624     assert( u.bi.pC->isTable );
67625     assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
67626     u.bi.iKey = u.bi.pC->lastRowid;
67627   }
67628
67629   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
67630   ** OP_Column on the same table without any intervening operations that
67631   ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
67632   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
67633   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
67634   ** to guard against future changes to the code generator.
67635   **/
67636   assert( u.bi.pC->deferredMoveto==0 );
67637   rc = sqlite3VdbeCursorMoveto(u.bi.pC);
67638   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67639
67640   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
67641   rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
67642   u.bi.pC->cacheStatus = CACHE_STALE;
67643
67644   /* Invoke the update-hook if required. */
67645   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67646     const char *zDb = db->aDb[u.bi.pC->iDb].zName;
67647     const char *zTbl = pOp->p4.z;
67648     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
67649     assert( u.bi.pC->iDb>=0 );
67650   }
67651   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
67652   break;
67653 }
67654 /* Opcode: ResetCount * * * * *
67655 **
67656 ** The value of the change counter is copied to the database handle
67657 ** change counter (returned by subsequent calls to sqlite3_changes()).
67658 ** Then the VMs internal change counter resets to 0.
67659 ** This is used by trigger programs.
67660 */
67661 case OP_ResetCount: {
67662   sqlite3VdbeSetChanges(db, p->nChange);
67663   p->nChange = 0;
67664   break;
67665 }
67666
67667 /* Opcode: SorterCompare P1 P2 P3
67668 **
67669 ** P1 is a sorter cursor. This instruction compares the record blob in 
67670 ** register P3 with the entry that the sorter cursor currently points to.
67671 ** If, excluding the rowid fields at the end, the two records are a match,
67672 ** fall through to the next instruction. Otherwise, jump to instruction P2.
67673 */
67674 case OP_SorterCompare: {
67675 #if 0  /* local variables moved into u.bj */
67676   VdbeCursor *pC;
67677   int res;
67678 #endif /* local variables moved into u.bj */
67679
67680   u.bj.pC = p->apCsr[pOp->p1];
67681   assert( isSorter(u.bj.pC) );
67682   pIn3 = &aMem[pOp->p3];
67683   rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
67684   if( u.bj.res ){
67685     pc = pOp->p2-1;
67686   }
67687   break;
67688 };
67689
67690 /* Opcode: SorterData P1 P2 * * *
67691 **
67692 ** Write into register P2 the current sorter data for sorter cursor P1.
67693 */
67694 case OP_SorterData: {
67695 #if 0  /* local variables moved into u.bk */
67696   VdbeCursor *pC;
67697 #endif /* local variables moved into u.bk */
67698 #ifndef SQLITE_OMIT_MERGE_SORT
67699   pOut = &aMem[pOp->p2];
67700   u.bk.pC = p->apCsr[pOp->p1];
67701   assert( u.bk.pC->isSorter );
67702   rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
67703 #else
67704   pOp->opcode = OP_RowKey;
67705   pc--;
67706 #endif
67707   break;
67708 }
67709
67710 /* Opcode: RowData P1 P2 * * *
67711 **
67712 ** Write into register P2 the complete row data for cursor P1.
67713 ** There is no interpretation of the data.  
67714 ** It is just copied onto the P2 register exactly as 
67715 ** it is found in the database file.
67716 **
67717 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67718 ** of a real table, not a pseudo-table.
67719 */
67720 /* Opcode: RowKey P1 P2 * * *
67721 **
67722 ** Write into register P2 the complete row key for cursor P1.
67723 ** There is no interpretation of the data.  
67724 ** The key is copied onto the P3 register exactly as 
67725 ** it is found in the database file.
67726 **
67727 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67728 ** of a real table, not a pseudo-table.
67729 */
67730 case OP_RowKey:
67731 case OP_RowData: {
67732 #if 0  /* local variables moved into u.bl */
67733   VdbeCursor *pC;
67734   BtCursor *pCrsr;
67735   u32 n;
67736   i64 n64;
67737 #endif /* local variables moved into u.bl */
67738
67739   pOut = &aMem[pOp->p2];
67740   memAboutToChange(p, pOut);
67741
67742   /* Note that RowKey and RowData are really exactly the same instruction */
67743   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67744   u.bl.pC = p->apCsr[pOp->p1];
67745   assert( u.bl.pC->isSorter==0 );
67746   assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
67747   assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
67748   assert( u.bl.pC!=0 );
67749   assert( u.bl.pC->nullRow==0 );
67750   assert( u.bl.pC->pseudoTableReg==0 );
67751   assert( u.bl.pC->pCursor!=0 );
67752   u.bl.pCrsr = u.bl.pC->pCursor;
67753   assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
67754
67755   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
67756   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
67757   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
67758   ** a no-op and can never fail.  But we leave it in place as a safety.
67759   */
67760   assert( u.bl.pC->deferredMoveto==0 );
67761   rc = sqlite3VdbeCursorMoveto(u.bl.pC);
67762   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67763
67764   if( u.bl.pC->isIndex ){
67765     assert( !u.bl.pC->isTable );
67766     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
67767     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
67768     if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67769       goto too_big;
67770     }
67771     u.bl.n = (u32)u.bl.n64;
67772   }else{
67773     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
67774     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
67775     if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67776       goto too_big;
67777     }
67778   }
67779   if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
67780     goto no_mem;
67781   }
67782   pOut->n = u.bl.n;
67783   MemSetTypeFlag(pOut, MEM_Blob);
67784   if( u.bl.pC->isIndex ){
67785     rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
67786   }else{
67787     rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
67788   }
67789   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
67790   UPDATE_MAX_BLOBSIZE(pOut);
67791   break;
67792 }
67793
67794 /* Opcode: Rowid P1 P2 * * *
67795 **
67796 ** Store in register P2 an integer which is the key of the table entry that
67797 ** P1 is currently point to.
67798 **
67799 ** P1 can be either an ordinary table or a virtual table.  There used to
67800 ** be a separate OP_VRowid opcode for use with virtual tables, but this
67801 ** one opcode now works for both table types.
67802 */
67803 case OP_Rowid: {                 /* out2-prerelease */
67804 #if 0  /* local variables moved into u.bm */
67805   VdbeCursor *pC;
67806   i64 v;
67807   sqlite3_vtab *pVtab;
67808   const sqlite3_module *pModule;
67809 #endif /* local variables moved into u.bm */
67810
67811   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67812   u.bm.pC = p->apCsr[pOp->p1];
67813   assert( u.bm.pC!=0 );
67814   assert( u.bm.pC->pseudoTableReg==0 );
67815   if( u.bm.pC->nullRow ){
67816     pOut->flags = MEM_Null;
67817     break;
67818   }else if( u.bm.pC->deferredMoveto ){
67819     u.bm.v = u.bm.pC->movetoTarget;
67820 #ifndef SQLITE_OMIT_VIRTUALTABLE
67821   }else if( u.bm.pC->pVtabCursor ){
67822     u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
67823     u.bm.pModule = u.bm.pVtab->pModule;
67824     assert( u.bm.pModule->xRowid );
67825     rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
67826     importVtabErrMsg(p, u.bm.pVtab);
67827 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67828   }else{
67829     assert( u.bm.pC->pCursor!=0 );
67830     rc = sqlite3VdbeCursorMoveto(u.bm.pC);
67831     if( rc ) goto abort_due_to_error;
67832     if( u.bm.pC->rowidIsValid ){
67833       u.bm.v = u.bm.pC->lastRowid;
67834     }else{
67835       rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
67836       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
67837     }
67838   }
67839   pOut->u.i = u.bm.v;
67840   break;
67841 }
67842
67843 /* Opcode: NullRow P1 * * * *
67844 **
67845 ** Move the cursor P1 to a null row.  Any OP_Column operations
67846 ** that occur while the cursor is on the null row will always
67847 ** write a NULL.
67848 */
67849 case OP_NullRow: {
67850 #if 0  /* local variables moved into u.bn */
67851   VdbeCursor *pC;
67852 #endif /* local variables moved into u.bn */
67853
67854   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67855   u.bn.pC = p->apCsr[pOp->p1];
67856   assert( u.bn.pC!=0 );
67857   u.bn.pC->nullRow = 1;
67858   u.bn.pC->rowidIsValid = 0;
67859   assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
67860   if( u.bn.pC->pCursor ){
67861     sqlite3BtreeClearCursor(u.bn.pC->pCursor);
67862   }
67863   break;
67864 }
67865
67866 /* Opcode: Last P1 P2 * * *
67867 **
67868 ** The next use of the Rowid or Column or Next instruction for P1 
67869 ** will refer to the last entry in the database table or index.
67870 ** If the table or index is empty and P2>0, then jump immediately to P2.
67871 ** If P2 is 0 or if the table or index is not empty, fall through
67872 ** to the following instruction.
67873 */
67874 case OP_Last: {        /* jump */
67875 #if 0  /* local variables moved into u.bo */
67876   VdbeCursor *pC;
67877   BtCursor *pCrsr;
67878   int res;
67879 #endif /* local variables moved into u.bo */
67880
67881   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67882   u.bo.pC = p->apCsr[pOp->p1];
67883   assert( u.bo.pC!=0 );
67884   u.bo.pCrsr = u.bo.pC->pCursor;
67885   u.bo.res = 0;
67886   if( ALWAYS(u.bo.pCrsr!=0) ){
67887     rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
67888   }
67889   u.bo.pC->nullRow = (u8)u.bo.res;
67890   u.bo.pC->deferredMoveto = 0;
67891   u.bo.pC->rowidIsValid = 0;
67892   u.bo.pC->cacheStatus = CACHE_STALE;
67893   if( pOp->p2>0 && u.bo.res ){
67894     pc = pOp->p2 - 1;
67895   }
67896   break;
67897 }
67898
67899
67900 /* Opcode: Sort P1 P2 * * *
67901 **
67902 ** This opcode does exactly the same thing as OP_Rewind except that
67903 ** it increments an undocumented global variable used for testing.
67904 **
67905 ** Sorting is accomplished by writing records into a sorting index,
67906 ** then rewinding that index and playing it back from beginning to
67907 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
67908 ** rewinding so that the global variable will be incremented and
67909 ** regression tests can determine whether or not the optimizer is
67910 ** correctly optimizing out sorts.
67911 */
67912 case OP_SorterSort:    /* jump */
67913 #ifdef SQLITE_OMIT_MERGE_SORT
67914   pOp->opcode = OP_Sort;
67915 #endif
67916 case OP_Sort: {        /* jump */
67917 #ifdef SQLITE_TEST
67918   sqlite3_sort_count++;
67919   sqlite3_search_count--;
67920 #endif
67921   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
67922   /* Fall through into OP_Rewind */
67923 }
67924 /* Opcode: Rewind P1 P2 * * *
67925 **
67926 ** The next use of the Rowid or Column or Next instruction for P1 
67927 ** will refer to the first entry in the database table or index.
67928 ** If the table or index is empty and P2>0, then jump immediately to P2.
67929 ** If P2 is 0 or if the table or index is not empty, fall through
67930 ** to the following instruction.
67931 */
67932 case OP_Rewind: {        /* jump */
67933 #if 0  /* local variables moved into u.bp */
67934   VdbeCursor *pC;
67935   BtCursor *pCrsr;
67936   int res;
67937 #endif /* local variables moved into u.bp */
67938
67939   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67940   u.bp.pC = p->apCsr[pOp->p1];
67941   assert( u.bp.pC!=0 );
67942   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
67943   u.bp.res = 1;
67944   if( isSorter(u.bp.pC) ){
67945     rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
67946   }else{
67947     u.bp.pCrsr = u.bp.pC->pCursor;
67948     assert( u.bp.pCrsr );
67949     rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
67950     u.bp.pC->atFirst = u.bp.res==0 ?1:0;
67951     u.bp.pC->deferredMoveto = 0;
67952     u.bp.pC->cacheStatus = CACHE_STALE;
67953     u.bp.pC->rowidIsValid = 0;
67954   }
67955   u.bp.pC->nullRow = (u8)u.bp.res;
67956   assert( pOp->p2>0 && pOp->p2<p->nOp );
67957   if( u.bp.res ){
67958     pc = pOp->p2 - 1;
67959   }
67960   break;
67961 }
67962
67963 /* Opcode: Next P1 P2 * P4 P5
67964 **
67965 ** Advance cursor P1 so that it points to the next key/data pair in its
67966 ** table or index.  If there are no more key/value pairs then fall through
67967 ** to the following instruction.  But if the cursor advance was successful,
67968 ** jump immediately to P2.
67969 **
67970 ** The P1 cursor must be for a real table, not a pseudo-table.
67971 **
67972 ** P4 is always of type P4_ADVANCE. The function pointer points to
67973 ** sqlite3BtreeNext().
67974 **
67975 ** If P5 is positive and the jump is taken, then event counter
67976 ** number P5-1 in the prepared statement is incremented.
67977 **
67978 ** See also: Prev
67979 */
67980 /* Opcode: Prev P1 P2 * * P5
67981 **
67982 ** Back up cursor P1 so that it points to the previous key/data pair in its
67983 ** table or index.  If there is no previous key/value pairs then fall through
67984 ** to the following instruction.  But if the cursor backup was successful,
67985 ** jump immediately to P2.
67986 **
67987 ** The P1 cursor must be for a real table, not a pseudo-table.
67988 **
67989 ** P4 is always of type P4_ADVANCE. The function pointer points to
67990 ** sqlite3BtreePrevious().
67991 **
67992 ** If P5 is positive and the jump is taken, then event counter
67993 ** number P5-1 in the prepared statement is incremented.
67994 */
67995 case OP_SorterNext:    /* jump */
67996 #ifdef SQLITE_OMIT_MERGE_SORT
67997   pOp->opcode = OP_Next;
67998 #endif
67999 case OP_Prev:          /* jump */
68000 case OP_Next: {        /* jump */
68001 #if 0  /* local variables moved into u.bq */
68002   VdbeCursor *pC;
68003   int res;
68004 #endif /* local variables moved into u.bq */
68005
68006   CHECK_FOR_INTERRUPT;
68007   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68008   assert( pOp->p5<=ArraySize(p->aCounter) );
68009   u.bq.pC = p->apCsr[pOp->p1];
68010   if( u.bq.pC==0 ){
68011     break;  /* See ticket #2273 */
68012   }
68013   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
68014   if( isSorter(u.bq.pC) ){
68015     assert( pOp->opcode==OP_SorterNext );
68016     rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
68017   }else{
68018     u.bq.res = 1;
68019     assert( u.bq.pC->deferredMoveto==0 );
68020     assert( u.bq.pC->pCursor );
68021     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
68022     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
68023     rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
68024   }
68025   u.bq.pC->nullRow = (u8)u.bq.res;
68026   u.bq.pC->cacheStatus = CACHE_STALE;
68027   if( u.bq.res==0 ){
68028     pc = pOp->p2 - 1;
68029     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
68030 #ifdef SQLITE_TEST
68031     sqlite3_search_count++;
68032 #endif
68033   }
68034   u.bq.pC->rowidIsValid = 0;
68035   break;
68036 }
68037
68038 /* Opcode: IdxInsert P1 P2 P3 * P5
68039 **
68040 ** Register P2 holds an SQL index key made using the
68041 ** MakeRecord instructions.  This opcode writes that key
68042 ** into the index P1.  Data for the entry is nil.
68043 **
68044 ** P3 is a flag that provides a hint to the b-tree layer that this
68045 ** insert is likely to be an append.
68046 **
68047 ** This instruction only works for indices.  The equivalent instruction
68048 ** for tables is OP_Insert.
68049 */
68050 case OP_SorterInsert:       /* in2 */
68051 #ifdef SQLITE_OMIT_MERGE_SORT
68052   pOp->opcode = OP_IdxInsert;
68053 #endif
68054 case OP_IdxInsert: {        /* in2 */
68055 #if 0  /* local variables moved into u.br */
68056   VdbeCursor *pC;
68057   BtCursor *pCrsr;
68058   int nKey;
68059   const char *zKey;
68060 #endif /* local variables moved into u.br */
68061
68062   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68063   u.br.pC = p->apCsr[pOp->p1];
68064   assert( u.br.pC!=0 );
68065   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
68066   pIn2 = &aMem[pOp->p2];
68067   assert( pIn2->flags & MEM_Blob );
68068   u.br.pCrsr = u.br.pC->pCursor;
68069   if( ALWAYS(u.br.pCrsr!=0) ){
68070     assert( u.br.pC->isTable==0 );
68071     rc = ExpandBlob(pIn2);
68072     if( rc==SQLITE_OK ){
68073       if( isSorter(u.br.pC) ){
68074         rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
68075       }else{
68076         u.br.nKey = pIn2->n;
68077         u.br.zKey = pIn2->z;
68078         rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
68079             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
68080             );
68081         assert( u.br.pC->deferredMoveto==0 );
68082         u.br.pC->cacheStatus = CACHE_STALE;
68083       }
68084     }
68085   }
68086   break;
68087 }
68088
68089 /* Opcode: IdxDelete P1 P2 P3 * *
68090 **
68091 ** The content of P3 registers starting at register P2 form
68092 ** an unpacked index key. This opcode removes that entry from the 
68093 ** index opened by cursor P1.
68094 */
68095 case OP_IdxDelete: {
68096 #if 0  /* local variables moved into u.bs */
68097   VdbeCursor *pC;
68098   BtCursor *pCrsr;
68099   int res;
68100   UnpackedRecord r;
68101 #endif /* local variables moved into u.bs */
68102
68103   assert( pOp->p3>0 );
68104   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68105   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68106   u.bs.pC = p->apCsr[pOp->p1];
68107   assert( u.bs.pC!=0 );
68108   u.bs.pCrsr = u.bs.pC->pCursor;
68109   if( ALWAYS(u.bs.pCrsr!=0) ){
68110     u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
68111     u.bs.r.nField = (u16)pOp->p3;
68112     u.bs.r.flags = 0;
68113     u.bs.r.aMem = &aMem[pOp->p2];
68114 #ifdef SQLITE_DEBUG
68115     { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
68116 #endif
68117     rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
68118     if( rc==SQLITE_OK && u.bs.res==0 ){
68119       rc = sqlite3BtreeDelete(u.bs.pCrsr);
68120     }
68121     assert( u.bs.pC->deferredMoveto==0 );
68122     u.bs.pC->cacheStatus = CACHE_STALE;
68123   }
68124   break;
68125 }
68126
68127 /* Opcode: IdxRowid P1 P2 * * *
68128 **
68129 ** Write into register P2 an integer which is the last entry in the record at
68130 ** the end of the index key pointed to by cursor P1.  This integer should be
68131 ** the rowid of the table entry to which this index entry points.
68132 **
68133 ** See also: Rowid, MakeRecord.
68134 */
68135 case OP_IdxRowid: {              /* out2-prerelease */
68136 #if 0  /* local variables moved into u.bt */
68137   BtCursor *pCrsr;
68138   VdbeCursor *pC;
68139   i64 rowid;
68140 #endif /* local variables moved into u.bt */
68141
68142   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68143   u.bt.pC = p->apCsr[pOp->p1];
68144   assert( u.bt.pC!=0 );
68145   u.bt.pCrsr = u.bt.pC->pCursor;
68146   pOut->flags = MEM_Null;
68147   if( ALWAYS(u.bt.pCrsr!=0) ){
68148     rc = sqlite3VdbeCursorMoveto(u.bt.pC);
68149     if( NEVER(rc) ) goto abort_due_to_error;
68150     assert( u.bt.pC->deferredMoveto==0 );
68151     assert( u.bt.pC->isTable==0 );
68152     if( !u.bt.pC->nullRow ){
68153       rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
68154       if( rc!=SQLITE_OK ){
68155         goto abort_due_to_error;
68156       }
68157       pOut->u.i = u.bt.rowid;
68158       pOut->flags = MEM_Int;
68159     }
68160   }
68161   break;
68162 }
68163
68164 /* Opcode: IdxGE P1 P2 P3 P4 P5
68165 **
68166 ** The P4 register values beginning with P3 form an unpacked index 
68167 ** key that omits the ROWID.  Compare this key value against the index 
68168 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68169 **
68170 ** If the P1 index entry is greater than or equal to the key value
68171 ** then jump to P2.  Otherwise fall through to the next instruction.
68172 **
68173 ** If P5 is non-zero then the key value is increased by an epsilon 
68174 ** prior to the comparison.  This make the opcode work like IdxGT except
68175 ** that if the key from register P3 is a prefix of the key in the cursor,
68176 ** the result is false whereas it would be true with IdxGT.
68177 */
68178 /* Opcode: IdxLT P1 P2 P3 P4 P5
68179 **
68180 ** The P4 register values beginning with P3 form an unpacked index 
68181 ** key that omits the ROWID.  Compare this key value against the index 
68182 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68183 **
68184 ** If the P1 index entry is less than the key value then jump to P2.
68185 ** Otherwise fall through to the next instruction.
68186 **
68187 ** If P5 is non-zero then the key value is increased by an epsilon prior 
68188 ** to the comparison.  This makes the opcode work like IdxLE.
68189 */
68190 case OP_IdxLT:          /* jump */
68191 case OP_IdxGE: {        /* jump */
68192 #if 0  /* local variables moved into u.bu */
68193   VdbeCursor *pC;
68194   int res;
68195   UnpackedRecord r;
68196 #endif /* local variables moved into u.bu */
68197
68198   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68199   u.bu.pC = p->apCsr[pOp->p1];
68200   assert( u.bu.pC!=0 );
68201   assert( u.bu.pC->isOrdered );
68202   if( ALWAYS(u.bu.pC->pCursor!=0) ){
68203     assert( u.bu.pC->deferredMoveto==0 );
68204     assert( pOp->p5==0 || pOp->p5==1 );
68205     assert( pOp->p4type==P4_INT32 );
68206     u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
68207     u.bu.r.nField = (u16)pOp->p4.i;
68208     if( pOp->p5 ){
68209       u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
68210     }else{
68211       u.bu.r.flags = UNPACKED_PREFIX_MATCH;
68212     }
68213     u.bu.r.aMem = &aMem[pOp->p3];
68214 #ifdef SQLITE_DEBUG
68215     { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
68216 #endif
68217     rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
68218     if( pOp->opcode==OP_IdxLT ){
68219       u.bu.res = -u.bu.res;
68220     }else{
68221       assert( pOp->opcode==OP_IdxGE );
68222       u.bu.res++;
68223     }
68224     if( u.bu.res>0 ){
68225       pc = pOp->p2 - 1 ;
68226     }
68227   }
68228   break;
68229 }
68230
68231 /* Opcode: Destroy P1 P2 P3 * *
68232 **
68233 ** Delete an entire database table or index whose root page in the database
68234 ** file is given by P1.
68235 **
68236 ** The table being destroyed is in the main database file if P3==0.  If
68237 ** P3==1 then the table to be clear is in the auxiliary database file
68238 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68239 **
68240 ** If AUTOVACUUM is enabled then it is possible that another root page
68241 ** might be moved into the newly deleted root page in order to keep all
68242 ** root pages contiguous at the beginning of the database.  The former
68243 ** value of the root page that moved - its value before the move occurred -
68244 ** is stored in register P2.  If no page 
68245 ** movement was required (because the table being dropped was already 
68246 ** the last one in the database) then a zero is stored in register P2.
68247 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68248 **
68249 ** See also: Clear
68250 */
68251 case OP_Destroy: {     /* out2-prerelease */
68252 #if 0  /* local variables moved into u.bv */
68253   int iMoved;
68254   int iCnt;
68255   Vdbe *pVdbe;
68256   int iDb;
68257 #endif /* local variables moved into u.bv */
68258 #ifndef SQLITE_OMIT_VIRTUALTABLE
68259   u.bv.iCnt = 0;
68260   for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
68261     if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
68262       u.bv.iCnt++;
68263     }
68264   }
68265 #else
68266   u.bv.iCnt = db->activeVdbeCnt;
68267 #endif
68268   pOut->flags = MEM_Null;
68269   if( u.bv.iCnt>1 ){
68270     rc = SQLITE_LOCKED;
68271     p->errorAction = OE_Abort;
68272   }else{
68273     u.bv.iDb = pOp->p3;
68274     assert( u.bv.iCnt==1 );
68275     assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
68276     rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
68277     pOut->flags = MEM_Int;
68278     pOut->u.i = u.bv.iMoved;
68279 #ifndef SQLITE_OMIT_AUTOVACUUM
68280     if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
68281       sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
68282       /* All OP_Destroy operations occur on the same btree */
68283       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
68284       resetSchemaOnFault = u.bv.iDb+1;
68285     }
68286 #endif
68287   }
68288   break;
68289 }
68290
68291 /* Opcode: Clear P1 P2 P3
68292 **
68293 ** Delete all contents of the database table or index whose root page
68294 ** in the database file is given by P1.  But, unlike Destroy, do not
68295 ** remove the table or index from the database file.
68296 **
68297 ** The table being clear is in the main database file if P2==0.  If
68298 ** P2==1 then the table to be clear is in the auxiliary database file
68299 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68300 **
68301 ** If the P3 value is non-zero, then the table referred to must be an
68302 ** intkey table (an SQL table, not an index). In this case the row change 
68303 ** count is incremented by the number of rows in the table being cleared. 
68304 ** If P3 is greater than zero, then the value stored in register P3 is
68305 ** also incremented by the number of rows in the table being cleared.
68306 **
68307 ** See also: Destroy
68308 */
68309 case OP_Clear: {
68310 #if 0  /* local variables moved into u.bw */
68311   int nChange;
68312 #endif /* local variables moved into u.bw */
68313
68314   u.bw.nChange = 0;
68315   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68316   rc = sqlite3BtreeClearTable(
68317       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
68318   );
68319   if( pOp->p3 ){
68320     p->nChange += u.bw.nChange;
68321     if( pOp->p3>0 ){
68322       assert( memIsValid(&aMem[pOp->p3]) );
68323       memAboutToChange(p, &aMem[pOp->p3]);
68324       aMem[pOp->p3].u.i += u.bw.nChange;
68325     }
68326   }
68327   break;
68328 }
68329
68330 /* Opcode: CreateTable P1 P2 * * *
68331 **
68332 ** Allocate a new table in the main database file if P1==0 or in the
68333 ** auxiliary database file if P1==1 or in an attached database if
68334 ** P1>1.  Write the root page number of the new table into
68335 ** register P2
68336 **
68337 ** The difference between a table and an index is this:  A table must
68338 ** have a 4-byte integer key and can have arbitrary data.  An index
68339 ** has an arbitrary key but no data.
68340 **
68341 ** See also: CreateIndex
68342 */
68343 /* Opcode: CreateIndex P1 P2 * * *
68344 **
68345 ** Allocate a new index in the main database file if P1==0 or in the
68346 ** auxiliary database file if P1==1 or in an attached database if
68347 ** P1>1.  Write the root page number of the new table into
68348 ** register P2.
68349 **
68350 ** See documentation on OP_CreateTable for additional information.
68351 */
68352 case OP_CreateIndex:            /* out2-prerelease */
68353 case OP_CreateTable: {          /* out2-prerelease */
68354 #if 0  /* local variables moved into u.bx */
68355   int pgno;
68356   int flags;
68357   Db *pDb;
68358 #endif /* local variables moved into u.bx */
68359
68360   u.bx.pgno = 0;
68361   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68362   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68363   u.bx.pDb = &db->aDb[pOp->p1];
68364   assert( u.bx.pDb->pBt!=0 );
68365   if( pOp->opcode==OP_CreateTable ){
68366     /* u.bx.flags = BTREE_INTKEY; */
68367     u.bx.flags = BTREE_INTKEY;
68368   }else{
68369     u.bx.flags = BTREE_BLOBKEY;
68370   }
68371   rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
68372   pOut->u.i = u.bx.pgno;
68373   break;
68374 }
68375
68376 /* Opcode: ParseSchema P1 * * P4 *
68377 **
68378 ** Read and parse all entries from the SQLITE_MASTER table of database P1
68379 ** that match the WHERE clause P4. 
68380 **
68381 ** This opcode invokes the parser to create a new virtual machine,
68382 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
68383 */
68384 case OP_ParseSchema: {
68385 #if 0  /* local variables moved into u.by */
68386   int iDb;
68387   const char *zMaster;
68388   char *zSql;
68389   InitData initData;
68390 #endif /* local variables moved into u.by */
68391
68392   /* Any prepared statement that invokes this opcode will hold mutexes
68393   ** on every btree.  This is a prerequisite for invoking
68394   ** sqlite3InitCallback().
68395   */
68396 #ifdef SQLITE_DEBUG
68397   for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
68398     assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
68399   }
68400 #endif
68401
68402   u.by.iDb = pOp->p1;
68403   assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
68404   assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
68405   /* Used to be a conditional */ {
68406     u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
68407     u.by.initData.db = db;
68408     u.by.initData.iDb = pOp->p1;
68409     u.by.initData.pzErrMsg = &p->zErrMsg;
68410     u.by.zSql = sqlite3MPrintf(db,
68411        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
68412        db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
68413     if( u.by.zSql==0 ){
68414       rc = SQLITE_NOMEM;
68415     }else{
68416       assert( db->init.busy==0 );
68417       db->init.busy = 1;
68418       u.by.initData.rc = SQLITE_OK;
68419       assert( !db->mallocFailed );
68420       rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
68421       if( rc==SQLITE_OK ) rc = u.by.initData.rc;
68422       sqlite3DbFree(db, u.by.zSql);
68423       db->init.busy = 0;
68424     }
68425   }
68426   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
68427   if( rc==SQLITE_NOMEM ){
68428     goto no_mem;
68429   }
68430   break;
68431 }
68432
68433 #if !defined(SQLITE_OMIT_ANALYZE)
68434 /* Opcode: LoadAnalysis P1 * * * *
68435 **
68436 ** Read the sqlite_stat1 table for database P1 and load the content
68437 ** of that table into the internal index hash table.  This will cause
68438 ** the analysis to be used when preparing all subsequent queries.
68439 */
68440 case OP_LoadAnalysis: {
68441   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68442   rc = sqlite3AnalysisLoad(db, pOp->p1);
68443   break;  
68444 }
68445 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
68446
68447 /* Opcode: DropTable P1 * * P4 *
68448 **
68449 ** Remove the internal (in-memory) data structures that describe
68450 ** the table named P4 in database P1.  This is called after a table
68451 ** is dropped in order to keep the internal representation of the
68452 ** schema consistent with what is on disk.
68453 */
68454 case OP_DropTable: {
68455   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
68456   break;
68457 }
68458
68459 /* Opcode: DropIndex P1 * * P4 *
68460 **
68461 ** Remove the internal (in-memory) data structures that describe
68462 ** the index named P4 in database P1.  This is called after an index
68463 ** is dropped in order to keep the internal representation of the
68464 ** schema consistent with what is on disk.
68465 */
68466 case OP_DropIndex: {
68467   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
68468   break;
68469 }
68470
68471 /* Opcode: DropTrigger P1 * * P4 *
68472 **
68473 ** Remove the internal (in-memory) data structures that describe
68474 ** the trigger named P4 in database P1.  This is called after a trigger
68475 ** is dropped in order to keep the internal representation of the
68476 ** schema consistent with what is on disk.
68477 */
68478 case OP_DropTrigger: {
68479   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
68480   break;
68481 }
68482
68483
68484 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68485 /* Opcode: IntegrityCk P1 P2 P3 * P5
68486 **
68487 ** Do an analysis of the currently open database.  Store in
68488 ** register P1 the text of an error message describing any problems.
68489 ** If no problems are found, store a NULL in register P1.
68490 **
68491 ** The register P3 contains the maximum number of allowed errors.
68492 ** At most reg(P3) errors will be reported.
68493 ** In other words, the analysis stops as soon as reg(P1) errors are 
68494 ** seen.  Reg(P1) is updated with the number of errors remaining.
68495 **
68496 ** The root page numbers of all tables in the database are integer
68497 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
68498 ** total.
68499 **
68500 ** If P5 is not zero, the check is done on the auxiliary database
68501 ** file, not the main database file.
68502 **
68503 ** This opcode is used to implement the integrity_check pragma.
68504 */
68505 case OP_IntegrityCk: {
68506 #if 0  /* local variables moved into u.bz */
68507   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
68508   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
68509   int j;          /* Loop counter */
68510   int nErr;       /* Number of errors reported */
68511   char *z;        /* Text of the error report */
68512   Mem *pnErr;     /* Register keeping track of errors remaining */
68513 #endif /* local variables moved into u.bz */
68514
68515   u.bz.nRoot = pOp->p2;
68516   assert( u.bz.nRoot>0 );
68517   u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
68518   if( u.bz.aRoot==0 ) goto no_mem;
68519   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68520   u.bz.pnErr = &aMem[pOp->p3];
68521   assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
68522   assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
68523   pIn1 = &aMem[pOp->p1];
68524   for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
68525     u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
68526   }
68527   u.bz.aRoot[u.bz.j] = 0;
68528   assert( pOp->p5<db->nDb );
68529   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
68530   u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
68531                                  (int)u.bz.pnErr->u.i, &u.bz.nErr);
68532   sqlite3DbFree(db, u.bz.aRoot);
68533   u.bz.pnErr->u.i -= u.bz.nErr;
68534   sqlite3VdbeMemSetNull(pIn1);
68535   if( u.bz.nErr==0 ){
68536     assert( u.bz.z==0 );
68537   }else if( u.bz.z==0 ){
68538     goto no_mem;
68539   }else{
68540     sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
68541   }
68542   UPDATE_MAX_BLOBSIZE(pIn1);
68543   sqlite3VdbeChangeEncoding(pIn1, encoding);
68544   break;
68545 }
68546 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68547
68548 /* Opcode: RowSetAdd P1 P2 * * *
68549 **
68550 ** Insert the integer value held by register P2 into a boolean index
68551 ** held in register P1.
68552 **
68553 ** An assertion fails if P2 is not an integer.
68554 */
68555 case OP_RowSetAdd: {       /* in1, in2 */
68556   pIn1 = &aMem[pOp->p1];
68557   pIn2 = &aMem[pOp->p2];
68558   assert( (pIn2->flags & MEM_Int)!=0 );
68559   if( (pIn1->flags & MEM_RowSet)==0 ){
68560     sqlite3VdbeMemSetRowSet(pIn1);
68561     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68562   }
68563   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
68564   break;
68565 }
68566
68567 /* Opcode: RowSetRead P1 P2 P3 * *
68568 **
68569 ** Extract the smallest value from boolean index P1 and put that value into
68570 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
68571 ** unchanged and jump to instruction P2.
68572 */
68573 case OP_RowSetRead: {       /* jump, in1, out3 */
68574 #if 0  /* local variables moved into u.ca */
68575   i64 val;
68576 #endif /* local variables moved into u.ca */
68577   CHECK_FOR_INTERRUPT;
68578   pIn1 = &aMem[pOp->p1];
68579   if( (pIn1->flags & MEM_RowSet)==0
68580    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
68581   ){
68582     /* The boolean index is empty */
68583     sqlite3VdbeMemSetNull(pIn1);
68584     pc = pOp->p2 - 1;
68585   }else{
68586     /* A value was pulled from the index */
68587     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
68588   }
68589   break;
68590 }
68591
68592 /* Opcode: RowSetTest P1 P2 P3 P4
68593 **
68594 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
68595 ** contains a RowSet object and that RowSet object contains
68596 ** the value held in P3, jump to register P2. Otherwise, insert the
68597 ** integer in P3 into the RowSet and continue on to the
68598 ** next opcode.
68599 **
68600 ** The RowSet object is optimized for the case where successive sets
68601 ** of integers, where each set contains no duplicates. Each set
68602 ** of values is identified by a unique P4 value. The first set
68603 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
68604 ** non-negative.  For non-negative values of P4 only the lower 4
68605 ** bits are significant.
68606 **
68607 ** This allows optimizations: (a) when P4==0 there is no need to test
68608 ** the rowset object for P3, as it is guaranteed not to contain it,
68609 ** (b) when P4==-1 there is no need to insert the value, as it will
68610 ** never be tested for, and (c) when a value that is part of set X is
68611 ** inserted, there is no need to search to see if the same value was
68612 ** previously inserted as part of set X (only if it was previously
68613 ** inserted as part of some other set).
68614 */
68615 case OP_RowSetTest: {                     /* jump, in1, in3 */
68616 #if 0  /* local variables moved into u.cb */
68617   int iSet;
68618   int exists;
68619 #endif /* local variables moved into u.cb */
68620
68621   pIn1 = &aMem[pOp->p1];
68622   pIn3 = &aMem[pOp->p3];
68623   u.cb.iSet = pOp->p4.i;
68624   assert( pIn3->flags&MEM_Int );
68625
68626   /* If there is anything other than a rowset object in memory cell P1,
68627   ** delete it now and initialize P1 with an empty rowset
68628   */
68629   if( (pIn1->flags & MEM_RowSet)==0 ){
68630     sqlite3VdbeMemSetRowSet(pIn1);
68631     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68632   }
68633
68634   assert( pOp->p4type==P4_INT32 );
68635   assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
68636   if( u.cb.iSet ){
68637     u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
68638                                (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
68639                                pIn3->u.i);
68640     if( u.cb.exists ){
68641       pc = pOp->p2 - 1;
68642       break;
68643     }
68644   }
68645   if( u.cb.iSet>=0 ){
68646     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
68647   }
68648   break;
68649 }
68650
68651
68652 #ifndef SQLITE_OMIT_TRIGGER
68653
68654 /* Opcode: Program P1 P2 P3 P4 *
68655 **
68656 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
68657 **
68658 ** P1 contains the address of the memory cell that contains the first memory 
68659 ** cell in an array of values used as arguments to the sub-program. P2 
68660 ** contains the address to jump to if the sub-program throws an IGNORE 
68661 ** exception using the RAISE() function. Register P3 contains the address 
68662 ** of a memory cell in this (the parent) VM that is used to allocate the 
68663 ** memory required by the sub-vdbe at runtime.
68664 **
68665 ** P4 is a pointer to the VM containing the trigger program.
68666 */
68667 case OP_Program: {        /* jump */
68668 #if 0  /* local variables moved into u.cc */
68669   int nMem;               /* Number of memory registers for sub-program */
68670   int nByte;              /* Bytes of runtime space required for sub-program */
68671   Mem *pRt;               /* Register to allocate runtime space */
68672   Mem *pMem;              /* Used to iterate through memory cells */
68673   Mem *pEnd;              /* Last memory cell in new array */
68674   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
68675   SubProgram *pProgram;   /* Sub-program to execute */
68676   void *t;                /* Token identifying trigger */
68677 #endif /* local variables moved into u.cc */
68678
68679   u.cc.pProgram = pOp->p4.pProgram;
68680   u.cc.pRt = &aMem[pOp->p3];
68681   assert( u.cc.pProgram->nOp>0 );
68682
68683   /* If the p5 flag is clear, then recursive invocation of triggers is
68684   ** disabled for backwards compatibility (p5 is set if this sub-program
68685   ** is really a trigger, not a foreign key action, and the flag set
68686   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
68687   **
68688   ** It is recursive invocation of triggers, at the SQL level, that is
68689   ** disabled. In some cases a single trigger may generate more than one
68690   ** SubProgram (if the trigger may be executed with more than one different
68691   ** ON CONFLICT algorithm). SubProgram structures associated with a
68692   ** single trigger all have the same value for the SubProgram.token
68693   ** variable.  */
68694   if( pOp->p5 ){
68695     u.cc.t = u.cc.pProgram->token;
68696     for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
68697     if( u.cc.pFrame ) break;
68698   }
68699
68700   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
68701     rc = SQLITE_ERROR;
68702     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
68703     break;
68704   }
68705
68706   /* Register u.cc.pRt is used to store the memory required to save the state
68707   ** of the current program, and the memory required at runtime to execute
68708   ** the trigger program. If this trigger has been fired before, then u.cc.pRt
68709   ** is already allocated. Otherwise, it must be initialized.  */
68710   if( (u.cc.pRt->flags&MEM_Frame)==0 ){
68711     /* SubProgram.nMem is set to the number of memory cells used by the
68712     ** program stored in SubProgram.aOp. As well as these, one memory
68713     ** cell is required for each cursor used by the program. Set local
68714     ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
68715     */
68716     u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
68717     u.cc.nByte = ROUND8(sizeof(VdbeFrame))
68718               + u.cc.nMem * sizeof(Mem)
68719               + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
68720               + u.cc.pProgram->nOnce * sizeof(u8);
68721     u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
68722     if( !u.cc.pFrame ){
68723       goto no_mem;
68724     }
68725     sqlite3VdbeMemRelease(u.cc.pRt);
68726     u.cc.pRt->flags = MEM_Frame;
68727     u.cc.pRt->u.pFrame = u.cc.pFrame;
68728
68729     u.cc.pFrame->v = p;
68730     u.cc.pFrame->nChildMem = u.cc.nMem;
68731     u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
68732     u.cc.pFrame->pc = pc;
68733     u.cc.pFrame->aMem = p->aMem;
68734     u.cc.pFrame->nMem = p->nMem;
68735     u.cc.pFrame->apCsr = p->apCsr;
68736     u.cc.pFrame->nCursor = p->nCursor;
68737     u.cc.pFrame->aOp = p->aOp;
68738     u.cc.pFrame->nOp = p->nOp;
68739     u.cc.pFrame->token = u.cc.pProgram->token;
68740     u.cc.pFrame->aOnceFlag = p->aOnceFlag;
68741     u.cc.pFrame->nOnceFlag = p->nOnceFlag;
68742
68743     u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
68744     for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
68745       u.cc.pMem->flags = MEM_Invalid;
68746       u.cc.pMem->db = db;
68747     }
68748   }else{
68749     u.cc.pFrame = u.cc.pRt->u.pFrame;
68750     assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
68751     assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
68752     assert( pc==u.cc.pFrame->pc );
68753   }
68754
68755   p->nFrame++;
68756   u.cc.pFrame->pParent = p->pFrame;
68757   u.cc.pFrame->lastRowid = lastRowid;
68758   u.cc.pFrame->nChange = p->nChange;
68759   p->nChange = 0;
68760   p->pFrame = u.cc.pFrame;
68761   p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
68762   p->nMem = u.cc.pFrame->nChildMem;
68763   p->nCursor = (u16)u.cc.pFrame->nChildCsr;
68764   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
68765   p->aOp = aOp = u.cc.pProgram->aOp;
68766   p->nOp = u.cc.pProgram->nOp;
68767   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
68768   p->nOnceFlag = u.cc.pProgram->nOnce;
68769   pc = -1;
68770   memset(p->aOnceFlag, 0, p->nOnceFlag);
68771
68772   break;
68773 }
68774
68775 /* Opcode: Param P1 P2 * * *
68776 **
68777 ** This opcode is only ever present in sub-programs called via the 
68778 ** OP_Program instruction. Copy a value currently stored in a memory 
68779 ** cell of the calling (parent) frame to cell P2 in the current frames 
68780 ** address space. This is used by trigger programs to access the new.* 
68781 ** and old.* values.
68782 **
68783 ** The address of the cell in the parent frame is determined by adding
68784 ** the value of the P1 argument to the value of the P1 argument to the
68785 ** calling OP_Program instruction.
68786 */
68787 case OP_Param: {           /* out2-prerelease */
68788 #if 0  /* local variables moved into u.cd */
68789   VdbeFrame *pFrame;
68790   Mem *pIn;
68791 #endif /* local variables moved into u.cd */
68792   u.cd.pFrame = p->pFrame;
68793   u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
68794   sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
68795   break;
68796 }
68797
68798 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
68799
68800 #ifndef SQLITE_OMIT_FOREIGN_KEY
68801 /* Opcode: FkCounter P1 P2 * * *
68802 **
68803 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
68804 ** If P1 is non-zero, the database constraint counter is incremented 
68805 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
68806 ** statement counter is incremented (immediate foreign key constraints).
68807 */
68808 case OP_FkCounter: {
68809   if( pOp->p1 ){
68810     db->nDeferredCons += pOp->p2;
68811   }else{
68812     p->nFkConstraint += pOp->p2;
68813   }
68814   break;
68815 }
68816
68817 /* Opcode: FkIfZero P1 P2 * * *
68818 **
68819 ** This opcode tests if a foreign key constraint-counter is currently zero.
68820 ** If so, jump to instruction P2. Otherwise, fall through to the next 
68821 ** instruction.
68822 **
68823 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
68824 ** is zero (the one that counts deferred constraint violations). If P1 is
68825 ** zero, the jump is taken if the statement constraint-counter is zero
68826 ** (immediate foreign key constraint violations).
68827 */
68828 case OP_FkIfZero: {         /* jump */
68829   if( pOp->p1 ){
68830     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
68831   }else{
68832     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
68833   }
68834   break;
68835 }
68836 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
68837
68838 #ifndef SQLITE_OMIT_AUTOINCREMENT
68839 /* Opcode: MemMax P1 P2 * * *
68840 **
68841 ** P1 is a register in the root frame of this VM (the root frame is
68842 ** different from the current frame if this instruction is being executed
68843 ** within a sub-program). Set the value of register P1 to the maximum of 
68844 ** its current value and the value in register P2.
68845 **
68846 ** This instruction throws an error if the memory cell is not initially
68847 ** an integer.
68848 */
68849 case OP_MemMax: {        /* in2 */
68850 #if 0  /* local variables moved into u.ce */
68851   Mem *pIn1;
68852   VdbeFrame *pFrame;
68853 #endif /* local variables moved into u.ce */
68854   if( p->pFrame ){
68855     for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
68856     u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
68857   }else{
68858     u.ce.pIn1 = &aMem[pOp->p1];
68859   }
68860   assert( memIsValid(u.ce.pIn1) );
68861   sqlite3VdbeMemIntegerify(u.ce.pIn1);
68862   pIn2 = &aMem[pOp->p2];
68863   sqlite3VdbeMemIntegerify(pIn2);
68864   if( u.ce.pIn1->u.i<pIn2->u.i){
68865     u.ce.pIn1->u.i = pIn2->u.i;
68866   }
68867   break;
68868 }
68869 #endif /* SQLITE_OMIT_AUTOINCREMENT */
68870
68871 /* Opcode: IfPos P1 P2 * * *
68872 **
68873 ** If the value of register P1 is 1 or greater, jump to P2.
68874 **
68875 ** It is illegal to use this instruction on a register that does
68876 ** not contain an integer.  An assertion fault will result if you try.
68877 */
68878 case OP_IfPos: {        /* jump, in1 */
68879   pIn1 = &aMem[pOp->p1];
68880   assert( pIn1->flags&MEM_Int );
68881   if( pIn1->u.i>0 ){
68882      pc = pOp->p2 - 1;
68883   }
68884   break;
68885 }
68886
68887 /* Opcode: IfNeg P1 P2 * * *
68888 **
68889 ** If the value of register P1 is less than zero, jump to P2. 
68890 **
68891 ** It is illegal to use this instruction on a register that does
68892 ** not contain an integer.  An assertion fault will result if you try.
68893 */
68894 case OP_IfNeg: {        /* jump, in1 */
68895   pIn1 = &aMem[pOp->p1];
68896   assert( pIn1->flags&MEM_Int );
68897   if( pIn1->u.i<0 ){
68898      pc = pOp->p2 - 1;
68899   }
68900   break;
68901 }
68902
68903 /* Opcode: IfZero P1 P2 P3 * *
68904 **
68905 ** The register P1 must contain an integer.  Add literal P3 to the
68906 ** value in register P1.  If the result is exactly 0, jump to P2. 
68907 **
68908 ** It is illegal to use this instruction on a register that does
68909 ** not contain an integer.  An assertion fault will result if you try.
68910 */
68911 case OP_IfZero: {        /* jump, in1 */
68912   pIn1 = &aMem[pOp->p1];
68913   assert( pIn1->flags&MEM_Int );
68914   pIn1->u.i += pOp->p3;
68915   if( pIn1->u.i==0 ){
68916      pc = pOp->p2 - 1;
68917   }
68918   break;
68919 }
68920
68921 /* Opcode: AggStep * P2 P3 P4 P5
68922 **
68923 ** Execute the step function for an aggregate.  The
68924 ** function has P5 arguments.   P4 is a pointer to the FuncDef
68925 ** structure that specifies the function.  Use register
68926 ** P3 as the accumulator.
68927 **
68928 ** The P5 arguments are taken from register P2 and its
68929 ** successors.
68930 */
68931 case OP_AggStep: {
68932 #if 0  /* local variables moved into u.cf */
68933   int n;
68934   int i;
68935   Mem *pMem;
68936   Mem *pRec;
68937   sqlite3_context ctx;
68938   sqlite3_value **apVal;
68939 #endif /* local variables moved into u.cf */
68940
68941   u.cf.n = pOp->p5;
68942   assert( u.cf.n>=0 );
68943   u.cf.pRec = &aMem[pOp->p2];
68944   u.cf.apVal = p->apArg;
68945   assert( u.cf.apVal || u.cf.n==0 );
68946   for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
68947     assert( memIsValid(u.cf.pRec) );
68948     u.cf.apVal[u.cf.i] = u.cf.pRec;
68949     memAboutToChange(p, u.cf.pRec);
68950     sqlite3VdbeMemStoreType(u.cf.pRec);
68951   }
68952   u.cf.ctx.pFunc = pOp->p4.pFunc;
68953   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68954   u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
68955   u.cf.pMem->n++;
68956   u.cf.ctx.s.flags = MEM_Null;
68957   u.cf.ctx.s.z = 0;
68958   u.cf.ctx.s.zMalloc = 0;
68959   u.cf.ctx.s.xDel = 0;
68960   u.cf.ctx.s.db = db;
68961   u.cf.ctx.isError = 0;
68962   u.cf.ctx.pColl = 0;
68963   u.cf.ctx.skipFlag = 0;
68964   if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
68965     assert( pOp>p->aOp );
68966     assert( pOp[-1].p4type==P4_COLLSEQ );
68967     assert( pOp[-1].opcode==OP_CollSeq );
68968     u.cf.ctx.pColl = pOp[-1].p4.pColl;
68969   }
68970   (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
68971   if( u.cf.ctx.isError ){
68972     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
68973     rc = u.cf.ctx.isError;
68974   }
68975   if( u.cf.ctx.skipFlag ){
68976     assert( pOp[-1].opcode==OP_CollSeq );
68977     u.cf.i = pOp[-1].p1;
68978     if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
68979   }
68980
68981   sqlite3VdbeMemRelease(&u.cf.ctx.s);
68982
68983   break;
68984 }
68985
68986 /* Opcode: AggFinal P1 P2 * P4 *
68987 **
68988 ** Execute the finalizer function for an aggregate.  P1 is
68989 ** the memory location that is the accumulator for the aggregate.
68990 **
68991 ** P2 is the number of arguments that the step function takes and
68992 ** P4 is a pointer to the FuncDef for this function.  The P2
68993 ** argument is not used by this opcode.  It is only there to disambiguate
68994 ** functions that can take varying numbers of arguments.  The
68995 ** P4 argument is only needed for the degenerate case where
68996 ** the step function was not previously called.
68997 */
68998 case OP_AggFinal: {
68999 #if 0  /* local variables moved into u.cg */
69000   Mem *pMem;
69001 #endif /* local variables moved into u.cg */
69002   assert( pOp->p1>0 && pOp->p1<=p->nMem );
69003   u.cg.pMem = &aMem[pOp->p1];
69004   assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69005   rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
69006   if( rc ){
69007     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
69008   }
69009   sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
69010   UPDATE_MAX_BLOBSIZE(u.cg.pMem);
69011   if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
69012     goto too_big;
69013   }
69014   break;
69015 }
69016
69017 #ifndef SQLITE_OMIT_WAL
69018 /* Opcode: Checkpoint P1 P2 P3 * *
69019 **
69020 ** Checkpoint database P1. This is a no-op if P1 is not currently in
69021 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
69022 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
69023 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
69024 ** WAL after the checkpoint into mem[P3+1] and the number of pages
69025 ** in the WAL that have been checkpointed after the checkpoint
69026 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
69027 ** mem[P3+2] are initialized to -1.
69028 */
69029 case OP_Checkpoint: {
69030 #if 0  /* local variables moved into u.ch */
69031   int i;                          /* Loop counter */
69032   int aRes[3];                    /* Results */
69033   Mem *pMem;                      /* Write results here */
69034 #endif /* local variables moved into u.ch */
69035
69036   u.ch.aRes[0] = 0;
69037   u.ch.aRes[1] = u.ch.aRes[2] = -1;
69038   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
69039        || pOp->p2==SQLITE_CHECKPOINT_FULL
69040        || pOp->p2==SQLITE_CHECKPOINT_RESTART
69041   );
69042   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
69043   if( rc==SQLITE_BUSY ){
69044     rc = SQLITE_OK;
69045     u.ch.aRes[0] = 1;
69046   }
69047   for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
69048     sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
69049   }
69050   break;
69051 };  
69052 #endif
69053
69054 #ifndef SQLITE_OMIT_PRAGMA
69055 /* Opcode: JournalMode P1 P2 P3 * P5
69056 **
69057 ** Change the journal mode of database P1 to P3. P3 must be one of the
69058 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
69059 ** modes (delete, truncate, persist, off and memory), this is a simple
69060 ** operation. No IO is required.
69061 **
69062 ** If changing into or out of WAL mode the procedure is more complicated.
69063 **
69064 ** Write a string containing the final journal-mode to register P2.
69065 */
69066 case OP_JournalMode: {    /* out2-prerelease */
69067 #if 0  /* local variables moved into u.ci */
69068   Btree *pBt;                     /* Btree to change journal mode of */
69069   Pager *pPager;                  /* Pager associated with pBt */
69070   int eNew;                       /* New journal mode */
69071   int eOld;                       /* The old journal mode */
69072   const char *zFilename;          /* Name of database file for pPager */
69073 #endif /* local variables moved into u.ci */
69074
69075   u.ci.eNew = pOp->p3;
69076   assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
69077        || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
69078        || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
69079        || u.ci.eNew==PAGER_JOURNALMODE_OFF
69080        || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
69081        || u.ci.eNew==PAGER_JOURNALMODE_WAL
69082        || u.ci.eNew==PAGER_JOURNALMODE_QUERY
69083   );
69084   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69085
69086   u.ci.pBt = db->aDb[pOp->p1].pBt;
69087   u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
69088   u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
69089   if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
69090   if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
69091
69092 #ifndef SQLITE_OMIT_WAL
69093   u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager, 1);
69094
69095   /* Do not allow a transition to journal_mode=WAL for a database
69096   ** in temporary storage or if the VFS does not support shared memory
69097   */
69098   if( u.ci.eNew==PAGER_JOURNALMODE_WAL
69099    && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
69100        || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
69101   ){
69102     u.ci.eNew = u.ci.eOld;
69103   }
69104
69105   if( (u.ci.eNew!=u.ci.eOld)
69106    && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
69107   ){
69108     if( !db->autoCommit || db->activeVdbeCnt>1 ){
69109       rc = SQLITE_ERROR;
69110       sqlite3SetString(&p->zErrMsg, db,
69111           "cannot change %s wal mode from within a transaction",
69112           (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69113       );
69114       break;
69115     }else{
69116
69117       if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
69118         /* If leaving WAL mode, close the log file. If successful, the call
69119         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69120         ** file. An EXCLUSIVE lock may still be held on the database file
69121         ** after a successful return.
69122         */
69123         rc = sqlite3PagerCloseWal(u.ci.pPager);
69124         if( rc==SQLITE_OK ){
69125           sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
69126         }
69127       }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
69128         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
69129         ** as an intermediate */
69130         sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
69131       }
69132
69133       /* Open a transaction on the database file. Regardless of the journal
69134       ** mode, this transaction always uses a rollback journal.
69135       */
69136       assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
69137       if( rc==SQLITE_OK ){
69138         rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69139       }
69140     }
69141   }
69142 #endif /* ifndef SQLITE_OMIT_WAL */
69143
69144   if( rc ){
69145     u.ci.eNew = u.ci.eOld;
69146   }
69147   u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
69148
69149   pOut = &aMem[pOp->p2];
69150   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69151   pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
69152   pOut->n = sqlite3Strlen30(pOut->z);
69153   pOut->enc = SQLITE_UTF8;
69154   sqlite3VdbeChangeEncoding(pOut, encoding);
69155   break;
69156 };
69157 #endif /* SQLITE_OMIT_PRAGMA */
69158
69159 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69160 /* Opcode: Vacuum * * * * *
69161 **
69162 ** Vacuum the entire database.  This opcode will cause other virtual
69163 ** machines to be created and run.  It may not be called from within
69164 ** a transaction.
69165 */
69166 case OP_Vacuum: {
69167   rc = sqlite3RunVacuum(&p->zErrMsg, db);
69168   break;
69169 }
69170 #endif
69171
69172 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69173 /* Opcode: IncrVacuum P1 P2 * * *
69174 **
69175 ** Perform a single step of the incremental vacuum procedure on
69176 ** the P1 database. If the vacuum has finished, jump to instruction
69177 ** P2. Otherwise, fall through to the next instruction.
69178 */
69179 case OP_IncrVacuum: {        /* jump */
69180 #if 0  /* local variables moved into u.cj */
69181   Btree *pBt;
69182 #endif /* local variables moved into u.cj */
69183
69184   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69185   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69186   u.cj.pBt = db->aDb[pOp->p1].pBt;
69187   rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
69188   if( rc==SQLITE_DONE ){
69189     pc = pOp->p2 - 1;
69190     rc = SQLITE_OK;
69191   }
69192   break;
69193 }
69194 #endif
69195
69196 /* Opcode: Expire P1 * * * *
69197 **
69198 ** Cause precompiled statements to become expired. An expired statement
69199 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
69200 ** (via sqlite3_step()).
69201 ** 
69202 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69203 ** then only the currently executing statement is affected. 
69204 */
69205 case OP_Expire: {
69206   if( !pOp->p1 ){
69207     sqlite3ExpirePreparedStatements(db);
69208   }else{
69209     p->expired = 1;
69210   }
69211   break;
69212 }
69213
69214 #ifndef SQLITE_OMIT_SHARED_CACHE
69215 /* Opcode: TableLock P1 P2 P3 P4 *
69216 **
69217 ** Obtain a lock on a particular table. This instruction is only used when
69218 ** the shared-cache feature is enabled. 
69219 **
69220 ** P1 is the index of the database in sqlite3.aDb[] of the database
69221 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
69222 ** a write lock if P3==1.
69223 **
69224 ** P2 contains the root-page of the table to lock.
69225 **
69226 ** P4 contains a pointer to the name of the table being locked. This is only
69227 ** used to generate an error message if the lock cannot be obtained.
69228 */
69229 case OP_TableLock: {
69230   u8 isWriteLock = (u8)pOp->p3;
69231   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69232     int p1 = pOp->p1; 
69233     assert( p1>=0 && p1<db->nDb );
69234     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69235     assert( isWriteLock==0 || isWriteLock==1 );
69236     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69237     if( (rc&0xFF)==SQLITE_LOCKED ){
69238       const char *z = pOp->p4.z;
69239       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69240     }
69241   }
69242   break;
69243 }
69244 #endif /* SQLITE_OMIT_SHARED_CACHE */
69245
69246 #ifndef SQLITE_OMIT_VIRTUALTABLE
69247 /* Opcode: VBegin * * * P4 *
69248 **
69249 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
69250 ** xBegin method for that table.
69251 **
69252 ** Also, whether or not P4 is set, check that this is not being called from
69253 ** within a callback to a virtual table xSync() method. If it is, the error
69254 ** code will be set to SQLITE_LOCKED.
69255 */
69256 case OP_VBegin: {
69257 #if 0  /* local variables moved into u.ck */
69258   VTable *pVTab;
69259 #endif /* local variables moved into u.ck */
69260   u.ck.pVTab = pOp->p4.pVtab;
69261   rc = sqlite3VtabBegin(db, u.ck.pVTab);
69262   if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
69263   break;
69264 }
69265 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69266
69267 #ifndef SQLITE_OMIT_VIRTUALTABLE
69268 /* Opcode: VCreate P1 * * P4 *
69269 **
69270 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69271 ** for that table.
69272 */
69273 case OP_VCreate: {
69274   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69275   break;
69276 }
69277 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69278
69279 #ifndef SQLITE_OMIT_VIRTUALTABLE
69280 /* Opcode: VDestroy P1 * * P4 *
69281 **
69282 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
69283 ** of that table.
69284 */
69285 case OP_VDestroy: {
69286   p->inVtabMethod = 2;
69287   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69288   p->inVtabMethod = 0;
69289   break;
69290 }
69291 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69292
69293 #ifndef SQLITE_OMIT_VIRTUALTABLE
69294 /* Opcode: VOpen P1 * * P4 *
69295 **
69296 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69297 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
69298 ** table and stores that cursor in P1.
69299 */
69300 case OP_VOpen: {
69301 #if 0  /* local variables moved into u.cl */
69302   VdbeCursor *pCur;
69303   sqlite3_vtab_cursor *pVtabCursor;
69304   sqlite3_vtab *pVtab;
69305   sqlite3_module *pModule;
69306 #endif /* local variables moved into u.cl */
69307
69308   u.cl.pCur = 0;
69309   u.cl.pVtabCursor = 0;
69310   u.cl.pVtab = pOp->p4.pVtab->pVtab;
69311   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
69312   assert(u.cl.pVtab && u.cl.pModule);
69313   rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
69314   importVtabErrMsg(p, u.cl.pVtab);
69315   if( SQLITE_OK==rc ){
69316     /* Initialize sqlite3_vtab_cursor base class */
69317     u.cl.pVtabCursor->pVtab = u.cl.pVtab;
69318
69319     /* Initialise vdbe cursor object */
69320     u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69321     if( u.cl.pCur ){
69322       u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
69323       u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
69324     }else{
69325       db->mallocFailed = 1;
69326       u.cl.pModule->xClose(u.cl.pVtabCursor);
69327     }
69328   }
69329   break;
69330 }
69331 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69332
69333 #ifndef SQLITE_OMIT_VIRTUALTABLE
69334 /* Opcode: VFilter P1 P2 P3 P4 *
69335 **
69336 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
69337 ** the filtered result set is empty.
69338 **
69339 ** P4 is either NULL or a string that was generated by the xBestIndex
69340 ** method of the module.  The interpretation of the P4 string is left
69341 ** to the module implementation.
69342 **
69343 ** This opcode invokes the xFilter method on the virtual table specified
69344 ** by P1.  The integer query plan parameter to xFilter is stored in register
69345 ** P3. Register P3+1 stores the argc parameter to be passed to the
69346 ** xFilter method. Registers P3+2..P3+1+argc are the argc
69347 ** additional parameters which are passed to
69348 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
69349 **
69350 ** A jump is made to P2 if the result set after filtering would be empty.
69351 */
69352 case OP_VFilter: {   /* jump */
69353 #if 0  /* local variables moved into u.cm */
69354   int nArg;
69355   int iQuery;
69356   const sqlite3_module *pModule;
69357   Mem *pQuery;
69358   Mem *pArgc;
69359   sqlite3_vtab_cursor *pVtabCursor;
69360   sqlite3_vtab *pVtab;
69361   VdbeCursor *pCur;
69362   int res;
69363   int i;
69364   Mem **apArg;
69365 #endif /* local variables moved into u.cm */
69366
69367   u.cm.pQuery = &aMem[pOp->p3];
69368   u.cm.pArgc = &u.cm.pQuery[1];
69369   u.cm.pCur = p->apCsr[pOp->p1];
69370   assert( memIsValid(u.cm.pQuery) );
69371   REGISTER_TRACE(pOp->p3, u.cm.pQuery);
69372   assert( u.cm.pCur->pVtabCursor );
69373   u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
69374   u.cm.pVtab = u.cm.pVtabCursor->pVtab;
69375   u.cm.pModule = u.cm.pVtab->pModule;
69376
69377   /* Grab the index number and argc parameters */
69378   assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
69379   u.cm.nArg = (int)u.cm.pArgc->u.i;
69380   u.cm.iQuery = (int)u.cm.pQuery->u.i;
69381
69382   /* Invoke the xFilter method */
69383   {
69384     u.cm.res = 0;
69385     u.cm.apArg = p->apArg;
69386     for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
69387       u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
69388       sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
69389     }
69390
69391     p->inVtabMethod = 1;
69392     rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
69393     p->inVtabMethod = 0;
69394     importVtabErrMsg(p, u.cm.pVtab);
69395     if( rc==SQLITE_OK ){
69396       u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
69397     }
69398
69399     if( u.cm.res ){
69400       pc = pOp->p2 - 1;
69401     }
69402   }
69403   u.cm.pCur->nullRow = 0;
69404
69405   break;
69406 }
69407 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69408
69409 #ifndef SQLITE_OMIT_VIRTUALTABLE
69410 /* Opcode: VColumn P1 P2 P3 * *
69411 **
69412 ** Store the value of the P2-th column of
69413 ** the row of the virtual-table that the 
69414 ** P1 cursor is pointing to into register P3.
69415 */
69416 case OP_VColumn: {
69417 #if 0  /* local variables moved into u.cn */
69418   sqlite3_vtab *pVtab;
69419   const sqlite3_module *pModule;
69420   Mem *pDest;
69421   sqlite3_context sContext;
69422 #endif /* local variables moved into u.cn */
69423
69424   VdbeCursor *pCur = p->apCsr[pOp->p1];
69425   assert( pCur->pVtabCursor );
69426   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69427   u.cn.pDest = &aMem[pOp->p3];
69428   memAboutToChange(p, u.cn.pDest);
69429   if( pCur->nullRow ){
69430     sqlite3VdbeMemSetNull(u.cn.pDest);
69431     break;
69432   }
69433   u.cn.pVtab = pCur->pVtabCursor->pVtab;
69434   u.cn.pModule = u.cn.pVtab->pModule;
69435   assert( u.cn.pModule->xColumn );
69436   memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
69437
69438   /* The output cell may already have a buffer allocated. Move
69439   ** the current contents to u.cn.sContext.s so in case the user-function
69440   ** can use the already allocated buffer instead of allocating a
69441   ** new one.
69442   */
69443   sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
69444   MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
69445
69446   rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
69447   importVtabErrMsg(p, u.cn.pVtab);
69448   if( u.cn.sContext.isError ){
69449     rc = u.cn.sContext.isError;
69450   }
69451
69452   /* Copy the result of the function to the P3 register. We
69453   ** do this regardless of whether or not an error occurred to ensure any
69454   ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
69455   */
69456   sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
69457   sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
69458   REGISTER_TRACE(pOp->p3, u.cn.pDest);
69459   UPDATE_MAX_BLOBSIZE(u.cn.pDest);
69460
69461   if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
69462     goto too_big;
69463   }
69464   break;
69465 }
69466 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69467
69468 #ifndef SQLITE_OMIT_VIRTUALTABLE
69469 /* Opcode: VNext P1 P2 * * *
69470 **
69471 ** Advance virtual table P1 to the next row in its result set and
69472 ** jump to instruction P2.  Or, if the virtual table has reached
69473 ** the end of its result set, then fall through to the next instruction.
69474 */
69475 case OP_VNext: {   /* jump */
69476 #if 0  /* local variables moved into u.co */
69477   sqlite3_vtab *pVtab;
69478   const sqlite3_module *pModule;
69479   int res;
69480   VdbeCursor *pCur;
69481 #endif /* local variables moved into u.co */
69482
69483   u.co.res = 0;
69484   u.co.pCur = p->apCsr[pOp->p1];
69485   assert( u.co.pCur->pVtabCursor );
69486   if( u.co.pCur->nullRow ){
69487     break;
69488   }
69489   u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
69490   u.co.pModule = u.co.pVtab->pModule;
69491   assert( u.co.pModule->xNext );
69492
69493   /* Invoke the xNext() method of the module. There is no way for the
69494   ** underlying implementation to return an error if one occurs during
69495   ** xNext(). Instead, if an error occurs, true is returned (indicating that
69496   ** data is available) and the error code returned when xColumn or
69497   ** some other method is next invoked on the save virtual table cursor.
69498   */
69499   p->inVtabMethod = 1;
69500   rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
69501   p->inVtabMethod = 0;
69502   importVtabErrMsg(p, u.co.pVtab);
69503   if( rc==SQLITE_OK ){
69504     u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
69505   }
69506
69507   if( !u.co.res ){
69508     /* If there is data, jump to P2 */
69509     pc = pOp->p2 - 1;
69510   }
69511   break;
69512 }
69513 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69514
69515 #ifndef SQLITE_OMIT_VIRTUALTABLE
69516 /* Opcode: VRename P1 * * P4 *
69517 **
69518 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69519 ** This opcode invokes the corresponding xRename method. The value
69520 ** in register P1 is passed as the zName argument to the xRename method.
69521 */
69522 case OP_VRename: {
69523 #if 0  /* local variables moved into u.cp */
69524   sqlite3_vtab *pVtab;
69525   Mem *pName;
69526 #endif /* local variables moved into u.cp */
69527
69528   u.cp.pVtab = pOp->p4.pVtab->pVtab;
69529   u.cp.pName = &aMem[pOp->p1];
69530   assert( u.cp.pVtab->pModule->xRename );
69531   assert( memIsValid(u.cp.pName) );
69532   REGISTER_TRACE(pOp->p1, u.cp.pName);
69533   assert( u.cp.pName->flags & MEM_Str );
69534   testcase( u.cp.pName->enc==SQLITE_UTF8 );
69535   testcase( u.cp.pName->enc==SQLITE_UTF16BE );
69536   testcase( u.cp.pName->enc==SQLITE_UTF16LE );
69537   rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
69538   if( rc==SQLITE_OK ){
69539     rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
69540     importVtabErrMsg(p, u.cp.pVtab);
69541     p->expired = 0;
69542   }
69543   break;
69544 }
69545 #endif
69546
69547 #ifndef SQLITE_OMIT_VIRTUALTABLE
69548 /* Opcode: VUpdate P1 P2 P3 P4 *
69549 **
69550 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69551 ** This opcode invokes the corresponding xUpdate method. P2 values
69552 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
69553 ** invocation. The value in register (P3+P2-1) corresponds to the 
69554 ** p2th element of the argv array passed to xUpdate.
69555 **
69556 ** The xUpdate method will do a DELETE or an INSERT or both.
69557 ** The argv[0] element (which corresponds to memory cell P3)
69558 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
69559 ** deletion occurs.  The argv[1] element is the rowid of the new 
69560 ** row.  This can be NULL to have the virtual table select the new 
69561 ** rowid for itself.  The subsequent elements in the array are 
69562 ** the values of columns in the new row.
69563 **
69564 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
69565 ** a row to delete.
69566 **
69567 ** P1 is a boolean flag. If it is set to true and the xUpdate call
69568 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
69569 ** is set to the value of the rowid for the row just inserted.
69570 */
69571 case OP_VUpdate: {
69572 #if 0  /* local variables moved into u.cq */
69573   sqlite3_vtab *pVtab;
69574   sqlite3_module *pModule;
69575   int nArg;
69576   int i;
69577   sqlite_int64 rowid;
69578   Mem **apArg;
69579   Mem *pX;
69580 #endif /* local variables moved into u.cq */
69581
69582   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
69583        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
69584   );
69585   u.cq.pVtab = pOp->p4.pVtab->pVtab;
69586   u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
69587   u.cq.nArg = pOp->p2;
69588   assert( pOp->p4type==P4_VTAB );
69589   if( ALWAYS(u.cq.pModule->xUpdate) ){
69590     u8 vtabOnConflict = db->vtabOnConflict;
69591     u.cq.apArg = p->apArg;
69592     u.cq.pX = &aMem[pOp->p3];
69593     for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
69594       assert( memIsValid(u.cq.pX) );
69595       memAboutToChange(p, u.cq.pX);
69596       sqlite3VdbeMemStoreType(u.cq.pX);
69597       u.cq.apArg[u.cq.i] = u.cq.pX;
69598       u.cq.pX++;
69599     }
69600     db->vtabOnConflict = pOp->p5;
69601     rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
69602     db->vtabOnConflict = vtabOnConflict;
69603     importVtabErrMsg(p, u.cq.pVtab);
69604     if( rc==SQLITE_OK && pOp->p1 ){
69605       assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
69606       db->lastRowid = lastRowid = u.cq.rowid;
69607     }
69608     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
69609       if( pOp->p5==OE_Ignore ){
69610         rc = SQLITE_OK;
69611       }else{
69612         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
69613       }
69614     }else{
69615       p->nChange++;
69616     }
69617   }
69618   break;
69619 }
69620 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69621
69622 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
69623 /* Opcode: Pagecount P1 P2 * * *
69624 **
69625 ** Write the current number of pages in database P1 to memory cell P2.
69626 */
69627 case OP_Pagecount: {            /* out2-prerelease */
69628   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
69629   break;
69630 }
69631 #endif
69632
69633
69634 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
69635 /* Opcode: MaxPgcnt P1 P2 P3 * *
69636 **
69637 ** Try to set the maximum page count for database P1 to the value in P3.
69638 ** Do not let the maximum page count fall below the current page count and
69639 ** do not change the maximum page count value if P3==0.
69640 **
69641 ** Store the maximum page count after the change in register P2.
69642 */
69643 case OP_MaxPgcnt: {            /* out2-prerelease */
69644   unsigned int newMax;
69645   Btree *pBt;
69646
69647   pBt = db->aDb[pOp->p1].pBt;
69648   newMax = 0;
69649   if( pOp->p3 ){
69650     newMax = sqlite3BtreeLastPage(pBt);
69651     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
69652   }
69653   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
69654   break;
69655 }
69656 #endif
69657
69658
69659 #ifndef SQLITE_OMIT_TRACE
69660 /* Opcode: Trace * * * P4 *
69661 **
69662 ** If tracing is enabled (by the sqlite3_trace()) interface, then
69663 ** the UTF-8 string contained in P4 is emitted on the trace callback.
69664 */
69665 case OP_Trace: {
69666 #if 0  /* local variables moved into u.cr */
69667   char *zTrace;
69668   char *z;
69669 #endif /* local variables moved into u.cr */
69670
69671   if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
69672     u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
69673     db->xTrace(db->pTraceArg, u.cr.z);
69674     sqlite3DbFree(db, u.cr.z);
69675   }
69676 #ifdef SQLITE_DEBUG
69677   if( (db->flags & SQLITE_SqlTrace)!=0
69678    && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
69679   ){
69680     sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
69681   }
69682 #endif /* SQLITE_DEBUG */
69683   break;
69684 }
69685 #endif
69686
69687
69688 /* Opcode: Noop * * * * *
69689 **
69690 ** Do nothing.  This instruction is often useful as a jump
69691 ** destination.
69692 */
69693 /*
69694 ** The magic Explain opcode are only inserted when explain==2 (which
69695 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
69696 ** This opcode records information from the optimizer.  It is the
69697 ** the same as a no-op.  This opcodesnever appears in a real VM program.
69698 */
69699 default: {          /* This is really OP_Noop and OP_Explain */
69700   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
69701   break;
69702 }
69703
69704 /*****************************************************************************
69705 ** The cases of the switch statement above this line should all be indented
69706 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
69707 ** readability.  From this point on down, the normal indentation rules are
69708 ** restored.
69709 *****************************************************************************/
69710     }
69711
69712 #ifdef VDBE_PROFILE
69713     {
69714       u64 elapsed = sqlite3Hwtime() - start;
69715       pOp->cycles += elapsed;
69716       pOp->cnt++;
69717 #if 0
69718         fprintf(stdout, "%10llu ", elapsed);
69719         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
69720 #endif
69721     }
69722 #endif
69723
69724     /* The following code adds nothing to the actual functionality
69725     ** of the program.  It is only here for testing and debugging.
69726     ** On the other hand, it does burn CPU cycles every time through
69727     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
69728     */
69729 #ifndef NDEBUG
69730     assert( pc>=-1 && pc<p->nOp );
69731
69732 #ifdef SQLITE_DEBUG
69733     if( p->trace ){
69734       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
69735       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
69736         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
69737       }
69738       if( pOp->opflags & OPFLG_OUT3 ){
69739         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
69740       }
69741     }
69742 #endif  /* SQLITE_DEBUG */
69743 #endif  /* NDEBUG */
69744   }  /* The end of the for(;;) loop the loops through opcodes */
69745
69746   /* If we reach this point, it means that execution is finished with
69747   ** an error of some kind.
69748   */
69749 vdbe_error_halt:
69750   assert( rc );
69751   p->rc = rc;
69752   testcase( sqlite3GlobalConfig.xLog!=0 );
69753   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
69754                    pc, p->zSql, p->zErrMsg);
69755   sqlite3VdbeHalt(p);
69756   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
69757   rc = SQLITE_ERROR;
69758   if( resetSchemaOnFault>0 ){
69759     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
69760   }
69761
69762   /* This is the only way out of this procedure.  We have to
69763   ** release the mutexes on btrees that were acquired at the
69764   ** top. */
69765 vdbe_return:
69766   db->lastRowid = lastRowid;
69767   sqlite3VdbeLeave(p);
69768   return rc;
69769
69770   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
69771   ** is encountered.
69772   */
69773 too_big:
69774   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
69775   rc = SQLITE_TOOBIG;
69776   goto vdbe_error_halt;
69777
69778   /* Jump to here if a malloc() fails.
69779   */
69780 no_mem:
69781   db->mallocFailed = 1;
69782   sqlite3SetString(&p->zErrMsg, db, "out of memory");
69783   rc = SQLITE_NOMEM;
69784   goto vdbe_error_halt;
69785
69786   /* Jump to here for any other kind of fatal error.  The "rc" variable
69787   ** should hold the error number.
69788   */
69789 abort_due_to_error:
69790   assert( p->zErrMsg==0 );
69791   if( db->mallocFailed ) rc = SQLITE_NOMEM;
69792   if( rc!=SQLITE_IOERR_NOMEM ){
69793     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69794   }
69795   goto vdbe_error_halt;
69796
69797   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
69798   ** flag.
69799   */
69800 abort_due_to_interrupt:
69801   assert( db->u1.isInterrupted );
69802   rc = SQLITE_INTERRUPT;
69803   p->rc = rc;
69804   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69805   goto vdbe_error_halt;
69806 }
69807
69808 /************** End of vdbe.c ************************************************/
69809 /************** Begin file vdbeblob.c ****************************************/
69810 /*
69811 ** 2007 May 1
69812 **
69813 ** The author disclaims copyright to this source code.  In place of
69814 ** a legal notice, here is a blessing:
69815 **
69816 **    May you do good and not evil.
69817 **    May you find forgiveness for yourself and forgive others.
69818 **    May you share freely, never taking more than you give.
69819 **
69820 *************************************************************************
69821 **
69822 ** This file contains code used to implement incremental BLOB I/O.
69823 */
69824
69825
69826 #ifndef SQLITE_OMIT_INCRBLOB
69827
69828 /*
69829 ** Valid sqlite3_blob* handles point to Incrblob structures.
69830 */
69831 typedef struct Incrblob Incrblob;
69832 struct Incrblob {
69833   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
69834   int nByte;              /* Size of open blob, in bytes */
69835   int iOffset;            /* Byte offset of blob in cursor data */
69836   int iCol;               /* Table column this handle is open on */
69837   BtCursor *pCsr;         /* Cursor pointing at blob row */
69838   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
69839   sqlite3 *db;            /* The associated database */
69840 };
69841
69842
69843 /*
69844 ** This function is used by both blob_open() and blob_reopen(). It seeks
69845 ** the b-tree cursor associated with blob handle p to point to row iRow.
69846 ** If successful, SQLITE_OK is returned and subsequent calls to
69847 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
69848 **
69849 ** If an error occurs, or if the specified row does not exist or does not
69850 ** contain a value of type TEXT or BLOB in the column nominated when the
69851 ** blob handle was opened, then an error code is returned and *pzErr may
69852 ** be set to point to a buffer containing an error message. It is the
69853 ** responsibility of the caller to free the error message buffer using
69854 ** sqlite3DbFree().
69855 **
69856 ** If an error does occur, then the b-tree cursor is closed. All subsequent
69857 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
69858 ** immediately return SQLITE_ABORT.
69859 */
69860 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
69861   int rc;                         /* Error code */
69862   char *zErr = 0;                 /* Error message */
69863   Vdbe *v = (Vdbe *)p->pStmt;
69864
69865   /* Set the value of the SQL statements only variable to integer iRow. 
69866   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
69867   ** triggering asserts related to mutexes.
69868   */
69869   assert( v->aVar[0].flags&MEM_Int );
69870   v->aVar[0].u.i = iRow;
69871
69872   rc = sqlite3_step(p->pStmt);
69873   if( rc==SQLITE_ROW ){
69874     u32 type = v->apCsr[0]->aType[p->iCol];
69875     if( type<12 ){
69876       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
69877           type==0?"null": type==7?"real": "integer"
69878       );
69879       rc = SQLITE_ERROR;
69880       sqlite3_finalize(p->pStmt);
69881       p->pStmt = 0;
69882     }else{
69883       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
69884       p->nByte = sqlite3VdbeSerialTypeLen(type);
69885       p->pCsr =  v->apCsr[0]->pCursor;
69886       sqlite3BtreeEnterCursor(p->pCsr);
69887       sqlite3BtreeCacheOverflow(p->pCsr);
69888       sqlite3BtreeLeaveCursor(p->pCsr);
69889     }
69890   }
69891
69892   if( rc==SQLITE_ROW ){
69893     rc = SQLITE_OK;
69894   }else if( p->pStmt ){
69895     rc = sqlite3_finalize(p->pStmt);
69896     p->pStmt = 0;
69897     if( rc==SQLITE_OK ){
69898       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
69899       rc = SQLITE_ERROR;
69900     }else{
69901       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
69902     }
69903   }
69904
69905   assert( rc!=SQLITE_OK || zErr==0 );
69906   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
69907
69908   *pzErr = zErr;
69909   return rc;
69910 }
69911
69912 /*
69913 ** Open a blob handle.
69914 */
69915 SQLITE_API int sqlite3_blob_open(
69916   sqlite3* db,            /* The database connection */
69917   const char *zDb,        /* The attached database containing the blob */
69918   const char *zTable,     /* The table containing the blob */
69919   const char *zColumn,    /* The column containing the blob */
69920   sqlite_int64 iRow,      /* The row containing the glob */
69921   int flags,              /* True -> read/write access, false -> read-only */
69922   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
69923 ){
69924   int nAttempt = 0;
69925   int iCol;               /* Index of zColumn in row-record */
69926
69927   /* This VDBE program seeks a btree cursor to the identified 
69928   ** db/table/row entry. The reason for using a vdbe program instead
69929   ** of writing code to use the b-tree layer directly is that the
69930   ** vdbe program will take advantage of the various transaction,
69931   ** locking and error handling infrastructure built into the vdbe.
69932   **
69933   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
69934   ** Code external to the Vdbe then "borrows" the b-tree cursor and
69935   ** uses it to implement the blob_read(), blob_write() and 
69936   ** blob_bytes() functions.
69937   **
69938   ** The sqlite3_blob_close() function finalizes the vdbe program,
69939   ** which closes the b-tree cursor and (possibly) commits the 
69940   ** transaction.
69941   */
69942   static const VdbeOpList openBlob[] = {
69943     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
69944     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
69945     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
69946
69947     /* One of the following two instructions is replaced by an OP_Noop. */
69948     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
69949     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
69950
69951     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
69952     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
69953     {OP_Column, 0, 0, 1},          /* 7  */
69954     {OP_ResultRow, 1, 0, 0},       /* 8  */
69955     {OP_Goto, 0, 5, 0},            /* 9  */
69956     {OP_Close, 0, 0, 0},           /* 10 */
69957     {OP_Halt, 0, 0, 0},            /* 11 */
69958   };
69959
69960   int rc = SQLITE_OK;
69961   char *zErr = 0;
69962   Table *pTab;
69963   Parse *pParse = 0;
69964   Incrblob *pBlob = 0;
69965
69966   flags = !!flags;                /* flags = (flags ? 1 : 0); */
69967   *ppBlob = 0;
69968
69969   sqlite3_mutex_enter(db->mutex);
69970
69971   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
69972   if( !pBlob ) goto blob_open_out;
69973   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
69974   if( !pParse ) goto blob_open_out;
69975
69976   do {
69977     memset(pParse, 0, sizeof(Parse));
69978     pParse->db = db;
69979     sqlite3DbFree(db, zErr);
69980     zErr = 0;
69981
69982     sqlite3BtreeEnterAll(db);
69983     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
69984     if( pTab && IsVirtual(pTab) ){
69985       pTab = 0;
69986       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
69987     }
69988 #ifndef SQLITE_OMIT_VIEW
69989     if( pTab && pTab->pSelect ){
69990       pTab = 0;
69991       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
69992     }
69993 #endif
69994     if( !pTab ){
69995       if( pParse->zErrMsg ){
69996         sqlite3DbFree(db, zErr);
69997         zErr = pParse->zErrMsg;
69998         pParse->zErrMsg = 0;
69999       }
70000       rc = SQLITE_ERROR;
70001       sqlite3BtreeLeaveAll(db);
70002       goto blob_open_out;
70003     }
70004
70005     /* Now search pTab for the exact column. */
70006     for(iCol=0; iCol<pTab->nCol; iCol++) {
70007       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
70008         break;
70009       }
70010     }
70011     if( iCol==pTab->nCol ){
70012       sqlite3DbFree(db, zErr);
70013       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
70014       rc = SQLITE_ERROR;
70015       sqlite3BtreeLeaveAll(db);
70016       goto blob_open_out;
70017     }
70018
70019     /* If the value is being opened for writing, check that the
70020     ** column is not indexed, and that it is not part of a foreign key. 
70021     ** It is against the rules to open a column to which either of these
70022     ** descriptions applies for writing.  */
70023     if( flags ){
70024       const char *zFault = 0;
70025       Index *pIdx;
70026 #ifndef SQLITE_OMIT_FOREIGN_KEY
70027       if( db->flags&SQLITE_ForeignKeys ){
70028         /* Check that the column is not part of an FK child key definition. It
70029         ** is not necessary to check if it is part of a parent key, as parent
70030         ** key columns must be indexed. The check below will pick up this 
70031         ** case.  */
70032         FKey *pFKey;
70033         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
70034           int j;
70035           for(j=0; j<pFKey->nCol; j++){
70036             if( pFKey->aCol[j].iFrom==iCol ){
70037               zFault = "foreign key";
70038             }
70039           }
70040         }
70041       }
70042 #endif
70043       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70044         int j;
70045         for(j=0; j<pIdx->nColumn; j++){
70046           if( pIdx->aiColumn[j]==iCol ){
70047             zFault = "indexed";
70048           }
70049         }
70050       }
70051       if( zFault ){
70052         sqlite3DbFree(db, zErr);
70053         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
70054         rc = SQLITE_ERROR;
70055         sqlite3BtreeLeaveAll(db);
70056         goto blob_open_out;
70057       }
70058     }
70059
70060     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
70061     assert( pBlob->pStmt || db->mallocFailed );
70062     if( pBlob->pStmt ){
70063       Vdbe *v = (Vdbe *)pBlob->pStmt;
70064       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70065
70066       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
70067
70068
70069       /* Configure the OP_Transaction */
70070       sqlite3VdbeChangeP1(v, 0, iDb);
70071       sqlite3VdbeChangeP2(v, 0, flags);
70072
70073       /* Configure the OP_VerifyCookie */
70074       sqlite3VdbeChangeP1(v, 1, iDb);
70075       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
70076       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
70077
70078       /* Make sure a mutex is held on the table to be accessed */
70079       sqlite3VdbeUsesBtree(v, iDb); 
70080
70081       /* Configure the OP_TableLock instruction */
70082 #ifdef SQLITE_OMIT_SHARED_CACHE
70083       sqlite3VdbeChangeToNoop(v, 2);
70084 #else
70085       sqlite3VdbeChangeP1(v, 2, iDb);
70086       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
70087       sqlite3VdbeChangeP3(v, 2, flags);
70088       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
70089 #endif
70090
70091       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
70092       ** parameter of the other to pTab->tnum.  */
70093       sqlite3VdbeChangeToNoop(v, 4 - flags);
70094       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
70095       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
70096
70097       /* Configure the number of columns. Configure the cursor to
70098       ** think that the table has one more column than it really
70099       ** does. An OP_Column to retrieve this imaginary column will
70100       ** always return an SQL NULL. This is useful because it means
70101       ** we can invoke OP_Column to fill in the vdbe cursors type 
70102       ** and offset cache without causing any IO.
70103       */
70104       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
70105       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
70106       if( !db->mallocFailed ){
70107         pParse->nVar = 1;
70108         pParse->nMem = 1;
70109         pParse->nTab = 1;
70110         sqlite3VdbeMakeReady(v, pParse);
70111       }
70112     }
70113    
70114     pBlob->flags = flags;
70115     pBlob->iCol = iCol;
70116     pBlob->db = db;
70117     sqlite3BtreeLeaveAll(db);
70118     if( db->mallocFailed ){
70119       goto blob_open_out;
70120     }
70121     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70122     rc = blobSeekToRow(pBlob, iRow, &zErr);
70123   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70124
70125 blob_open_out:
70126   if( rc==SQLITE_OK && db->mallocFailed==0 ){
70127     *ppBlob = (sqlite3_blob *)pBlob;
70128   }else{
70129     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70130     sqlite3DbFree(db, pBlob);
70131   }
70132   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70133   sqlite3DbFree(db, zErr);
70134   sqlite3StackFree(db, pParse);
70135   rc = sqlite3ApiExit(db, rc);
70136   sqlite3_mutex_leave(db->mutex);
70137   return rc;
70138 }
70139
70140 /*
70141 ** Close a blob handle that was previously created using
70142 ** sqlite3_blob_open().
70143 */
70144 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70145   Incrblob *p = (Incrblob *)pBlob;
70146   int rc;
70147   sqlite3 *db;
70148
70149   if( p ){
70150     db = p->db;
70151     sqlite3_mutex_enter(db->mutex);
70152     rc = sqlite3_finalize(p->pStmt);
70153     sqlite3DbFree(db, p);
70154     sqlite3_mutex_leave(db->mutex);
70155   }else{
70156     rc = SQLITE_OK;
70157   }
70158   return rc;
70159 }
70160
70161 /*
70162 ** Perform a read or write operation on a blob
70163 */
70164 static int blobReadWrite(
70165   sqlite3_blob *pBlob, 
70166   void *z, 
70167   int n, 
70168   int iOffset, 
70169   int (*xCall)(BtCursor*, u32, u32, void*)
70170 ){
70171   int rc;
70172   Incrblob *p = (Incrblob *)pBlob;
70173   Vdbe *v;
70174   sqlite3 *db;
70175
70176   if( p==0 ) return SQLITE_MISUSE_BKPT;
70177   db = p->db;
70178   sqlite3_mutex_enter(db->mutex);
70179   v = (Vdbe*)p->pStmt;
70180
70181   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70182     /* Request is out of range. Return a transient error. */
70183     rc = SQLITE_ERROR;
70184     sqlite3Error(db, SQLITE_ERROR, 0);
70185   }else if( v==0 ){
70186     /* If there is no statement handle, then the blob-handle has
70187     ** already been invalidated. Return SQLITE_ABORT in this case.
70188     */
70189     rc = SQLITE_ABORT;
70190   }else{
70191     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70192     ** returned, clean-up the statement handle.
70193     */
70194     assert( db == v->db );
70195     sqlite3BtreeEnterCursor(p->pCsr);
70196     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70197     sqlite3BtreeLeaveCursor(p->pCsr);
70198     if( rc==SQLITE_ABORT ){
70199       sqlite3VdbeFinalize(v);
70200       p->pStmt = 0;
70201     }else{
70202       db->errCode = rc;
70203       v->rc = rc;
70204     }
70205   }
70206   rc = sqlite3ApiExit(db, rc);
70207   sqlite3_mutex_leave(db->mutex);
70208   return rc;
70209 }
70210
70211 /*
70212 ** Read data from a blob handle.
70213 */
70214 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70215   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70216 }
70217
70218 /*
70219 ** Write data to a blob handle.
70220 */
70221 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70222   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70223 }
70224
70225 /*
70226 ** Query a blob handle for the size of the data.
70227 **
70228 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70229 ** so no mutex is required for access.
70230 */
70231 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70232   Incrblob *p = (Incrblob *)pBlob;
70233   return (p && p->pStmt) ? p->nByte : 0;
70234 }
70235
70236 /*
70237 ** Move an existing blob handle to point to a different row of the same
70238 ** database table.
70239 **
70240 ** If an error occurs, or if the specified row does not exist or does not
70241 ** contain a blob or text value, then an error code is returned and the
70242 ** database handle error code and message set. If this happens, then all 
70243 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
70244 ** immediately return SQLITE_ABORT.
70245 */
70246 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70247   int rc;
70248   Incrblob *p = (Incrblob *)pBlob;
70249   sqlite3 *db;
70250
70251   if( p==0 ) return SQLITE_MISUSE_BKPT;
70252   db = p->db;
70253   sqlite3_mutex_enter(db->mutex);
70254
70255   if( p->pStmt==0 ){
70256     /* If there is no statement handle, then the blob-handle has
70257     ** already been invalidated. Return SQLITE_ABORT in this case.
70258     */
70259     rc = SQLITE_ABORT;
70260   }else{
70261     char *zErr;
70262     rc = blobSeekToRow(p, iRow, &zErr);
70263     if( rc!=SQLITE_OK ){
70264       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70265       sqlite3DbFree(db, zErr);
70266     }
70267     assert( rc!=SQLITE_SCHEMA );
70268   }
70269
70270   rc = sqlite3ApiExit(db, rc);
70271   assert( rc==SQLITE_OK || p->pStmt==0 );
70272   sqlite3_mutex_leave(db->mutex);
70273   return rc;
70274 }
70275
70276 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70277
70278 /************** End of vdbeblob.c ********************************************/
70279 /************** Begin file vdbesort.c ****************************************/
70280 /*
70281 ** 2011 July 9
70282 **
70283 ** The author disclaims copyright to this source code.  In place of
70284 ** a legal notice, here is a blessing:
70285 **
70286 **    May you do good and not evil.
70287 **    May you find forgiveness for yourself and forgive others.
70288 **    May you share freely, never taking more than you give.
70289 **
70290 *************************************************************************
70291 ** This file contains code for the VdbeSorter object, used in concert with
70292 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70293 ** example, by CREATE INDEX statements on tables too large to fit in main
70294 ** memory).
70295 */
70296
70297
70298 #ifndef SQLITE_OMIT_MERGE_SORT
70299
70300 typedef struct VdbeSorterIter VdbeSorterIter;
70301 typedef struct SorterRecord SorterRecord;
70302 typedef struct FileWriter FileWriter;
70303
70304 /*
70305 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70306 **
70307 ** As keys are added to the sorter, they are written to disk in a series
70308 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70309 ** the same as the cache-size allowed for temporary databases. In order
70310 ** to allow the caller to extract keys from the sorter in sorted order,
70311 ** all PMAs currently stored on disk must be merged together. This comment
70312 ** describes the data structure used to do so. The structure supports 
70313 ** merging any number of arrays in a single pass with no redundant comparison 
70314 ** operations.
70315 **
70316 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70317 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
70318 ** the purposes of the paragraphs below, we assume that the array is actually 
70319 ** N elements in size, where N is the smallest power of 2 greater to or equal 
70320 ** to the number of iterators being merged. The extra aIter[] elements are 
70321 ** treated as if they are empty (always at EOF).
70322 **
70323 ** The aTree[] array is also N elements in size. The value of N is stored in
70324 ** the VdbeSorter.nTree variable.
70325 **
70326 ** The final (N/2) elements of aTree[] contain the results of comparing
70327 ** pairs of iterator keys together. Element i contains the result of 
70328 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70329 ** aTree element is set to the index of it. 
70330 **
70331 ** For the purposes of this comparison, EOF is considered greater than any
70332 ** other key value. If the keys are equal (only possible with two EOF
70333 ** values), it doesn't matter which index is stored.
70334 **
70335 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
70336 ** above contains the index of the smallest of each block of 4 iterators.
70337 ** And so on. So that aTree[1] contains the index of the iterator that 
70338 ** currently points to the smallest key value. aTree[0] is unused.
70339 **
70340 ** Example:
70341 **
70342 **     aIter[0] -> Banana
70343 **     aIter[1] -> Feijoa
70344 **     aIter[2] -> Elderberry
70345 **     aIter[3] -> Currant
70346 **     aIter[4] -> Grapefruit
70347 **     aIter[5] -> Apple
70348 **     aIter[6] -> Durian
70349 **     aIter[7] -> EOF
70350 **
70351 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
70352 **
70353 ** The current element is "Apple" (the value of the key indicated by 
70354 ** iterator 5). When the Next() operation is invoked, iterator 5 will
70355 ** be advanced to the next key in its segment. Say the next key is
70356 ** "Eggplant":
70357 **
70358 **     aIter[5] -> Eggplant
70359 **
70360 ** The contents of aTree[] are updated first by comparing the new iterator
70361 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
70362 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
70363 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
70364 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
70365 ** so the value written into element 1 of the array is 0. As follows:
70366 **
70367 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
70368 **
70369 ** In other words, each time we advance to the next sorter element, log2(N)
70370 ** key comparison operations are required, where N is the number of segments
70371 ** being merged (rounded up to the next power of 2).
70372 */
70373 struct VdbeSorter {
70374   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
70375   i64 iReadOff;                   /* Current read offset within file pTemp1 */
70376   int nInMemory;                  /* Current size of pRecord list as PMA */
70377   int nTree;                      /* Used size of aTree/aIter (power of 2) */
70378   int nPMA;                       /* Number of PMAs stored in pTemp1 */
70379   int mnPmaSize;                  /* Minimum PMA size, in bytes */
70380   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
70381   VdbeSorterIter *aIter;          /* Array of iterators to merge */
70382   int *aTree;                     /* Current state of incremental merge */
70383   sqlite3_file *pTemp1;           /* PMA file 1 */
70384   SorterRecord *pRecord;          /* Head of in-memory record list */
70385   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
70386 };
70387
70388 /*
70389 ** The following type is an iterator for a PMA. It caches the current key in 
70390 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
70391 */
70392 struct VdbeSorterIter {
70393   i64 iReadOff;                   /* Current read offset */
70394   i64 iEof;                       /* 1 byte past EOF for this iterator */
70395   int nAlloc;                     /* Bytes of space at aAlloc */
70396   int nKey;                       /* Number of bytes in key */
70397   sqlite3_file *pFile;            /* File iterator is reading from */
70398   u8 *aAlloc;                     /* Allocated space */
70399   u8 *aKey;                       /* Pointer to current key */
70400   u8 *aBuffer;                    /* Current read buffer */
70401   int nBuffer;                    /* Size of read buffer in bytes */
70402 };
70403
70404 /*
70405 ** An instance of this structure is used to organize the stream of records
70406 ** being written to files by the merge-sort code into aligned, page-sized
70407 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
70408 ** faster on many operating systems.
70409 */
70410 struct FileWriter {
70411   int eFWErr;                     /* Non-zero if in an error state */
70412   u8 *aBuffer;                    /* Pointer to write buffer */
70413   int nBuffer;                    /* Size of write buffer in bytes */
70414   int iBufStart;                  /* First byte of buffer to write */
70415   int iBufEnd;                    /* Last byte of buffer to write */
70416   i64 iWriteOff;                  /* Offset of start of buffer in file */
70417   sqlite3_file *pFile;            /* File to write to */
70418 };
70419
70420 /*
70421 ** A structure to store a single record. All in-memory records are connected
70422 ** together into a linked list headed at VdbeSorter.pRecord using the 
70423 ** SorterRecord.pNext pointer.
70424 */
70425 struct SorterRecord {
70426   void *pVal;
70427   int nVal;
70428   SorterRecord *pNext;
70429 };
70430
70431 /* Minimum allowable value for the VdbeSorter.nWorking variable */
70432 #define SORTER_MIN_WORKING 10
70433
70434 /* Maximum number of segments to merge in a single pass. */
70435 #define SORTER_MAX_MERGE_COUNT 16
70436
70437 /*
70438 ** Free all memory belonging to the VdbeSorterIter object passed as the second
70439 ** argument. All structure fields are set to zero before returning.
70440 */
70441 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
70442   sqlite3DbFree(db, pIter->aAlloc);
70443   sqlite3DbFree(db, pIter->aBuffer);
70444   memset(pIter, 0, sizeof(VdbeSorterIter));
70445 }
70446
70447 /*
70448 ** Read nByte bytes of data from the stream of data iterated by object p.
70449 ** If successful, set *ppOut to point to a buffer containing the data
70450 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
70451 ** error code.
70452 **
70453 ** The buffer indicated by *ppOut may only be considered valid until the
70454 ** next call to this function.
70455 */
70456 static int vdbeSorterIterRead(
70457   sqlite3 *db,                    /* Database handle (for malloc) */
70458   VdbeSorterIter *p,              /* Iterator */
70459   int nByte,                      /* Bytes of data to read */
70460   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
70461 ){
70462   int iBuf;                       /* Offset within buffer to read from */
70463   int nAvail;                     /* Bytes of data available in buffer */
70464   assert( p->aBuffer );
70465
70466   /* If there is no more data to be read from the buffer, read the next 
70467   ** p->nBuffer bytes of data from the file into it. Or, if there are less
70468   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
70469   iBuf = p->iReadOff % p->nBuffer;
70470   if( iBuf==0 ){
70471     int nRead;                    /* Bytes to read from disk */
70472     int rc;                       /* sqlite3OsRead() return code */
70473
70474     /* Determine how many bytes of data to read. */
70475     nRead = (int)(p->iEof - p->iReadOff);
70476     if( nRead>p->nBuffer ) nRead = p->nBuffer;
70477     assert( nRead>0 );
70478
70479     /* Read data from the file. Return early if an error occurs. */
70480     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
70481     assert( rc!=SQLITE_IOERR_SHORT_READ );
70482     if( rc!=SQLITE_OK ) return rc;
70483   }
70484   nAvail = p->nBuffer - iBuf; 
70485
70486   if( nByte<=nAvail ){
70487     /* The requested data is available in the in-memory buffer. In this
70488     ** case there is no need to make a copy of the data, just return a 
70489     ** pointer into the buffer to the caller.  */
70490     *ppOut = &p->aBuffer[iBuf];
70491     p->iReadOff += nByte;
70492   }else{
70493     /* The requested data is not all available in the in-memory buffer.
70494     ** In this case, allocate space at p->aAlloc[] to copy the requested
70495     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
70496     int nRem;                     /* Bytes remaining to copy */
70497
70498     /* Extend the p->aAlloc[] allocation if required. */
70499     if( p->nAlloc<nByte ){
70500       int nNew = p->nAlloc*2;
70501       while( nByte>nNew ) nNew = nNew*2;
70502       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
70503       if( !p->aAlloc ) return SQLITE_NOMEM;
70504       p->nAlloc = nNew;
70505     }
70506
70507     /* Copy as much data as is available in the buffer into the start of
70508     ** p->aAlloc[].  */
70509     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
70510     p->iReadOff += nAvail;
70511     nRem = nByte - nAvail;
70512
70513     /* The following loop copies up to p->nBuffer bytes per iteration into
70514     ** the p->aAlloc[] buffer.  */
70515     while( nRem>0 ){
70516       int rc;                     /* vdbeSorterIterRead() return code */
70517       int nCopy;                  /* Number of bytes to copy */
70518       u8 *aNext;                  /* Pointer to buffer to copy data from */
70519
70520       nCopy = nRem;
70521       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
70522       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
70523       if( rc!=SQLITE_OK ) return rc;
70524       assert( aNext!=p->aAlloc );
70525       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
70526       nRem -= nCopy;
70527     }
70528
70529     *ppOut = p->aAlloc;
70530   }
70531
70532   return SQLITE_OK;
70533 }
70534
70535 /*
70536 ** Read a varint from the stream of data accessed by p. Set *pnOut to
70537 ** the value read.
70538 */
70539 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
70540   int iBuf;
70541
70542   iBuf = p->iReadOff % p->nBuffer;
70543   if( iBuf && (p->nBuffer-iBuf)>=9 ){
70544     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
70545   }else{
70546     u8 aVarint[16], *a;
70547     int i = 0, rc;
70548     do{
70549       rc = vdbeSorterIterRead(db, p, 1, &a);
70550       if( rc ) return rc;
70551       aVarint[(i++)&0xf] = a[0];
70552     }while( (a[0]&0x80)!=0 );
70553     sqlite3GetVarint(aVarint, pnOut);
70554   }
70555
70556   return SQLITE_OK;
70557 }
70558
70559
70560 /*
70561 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
70562 ** no error occurs, or an SQLite error code if one does.
70563 */
70564 static int vdbeSorterIterNext(
70565   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
70566   VdbeSorterIter *pIter           /* Iterator to advance */
70567 ){
70568   int rc;                         /* Return Code */
70569   u64 nRec = 0;                   /* Size of record in bytes */
70570
70571   if( pIter->iReadOff>=pIter->iEof ){
70572     /* This is an EOF condition */
70573     vdbeSorterIterZero(db, pIter);
70574     return SQLITE_OK;
70575   }
70576
70577   rc = vdbeSorterIterVarint(db, pIter, &nRec);
70578   if( rc==SQLITE_OK ){
70579     pIter->nKey = (int)nRec;
70580     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
70581   }
70582
70583   return rc;
70584 }
70585
70586 /*
70587 ** Initialize iterator pIter to scan through the PMA stored in file pFile
70588 ** starting at offset iStart and ending at offset iEof-1. This function 
70589 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
70590 ** PMA is empty).
70591 */
70592 static int vdbeSorterIterInit(
70593   sqlite3 *db,                    /* Database handle */
70594   const VdbeSorter *pSorter,      /* Sorter object */
70595   i64 iStart,                     /* Start offset in pFile */
70596   VdbeSorterIter *pIter,          /* Iterator to populate */
70597   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
70598 ){
70599   int rc = SQLITE_OK;
70600   int nBuf;
70601
70602   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
70603
70604   assert( pSorter->iWriteOff>iStart );
70605   assert( pIter->aAlloc==0 );
70606   assert( pIter->aBuffer==0 );
70607   pIter->pFile = pSorter->pTemp1;
70608   pIter->iReadOff = iStart;
70609   pIter->nAlloc = 128;
70610   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
70611   pIter->nBuffer = nBuf;
70612   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
70613
70614   if( !pIter->aBuffer ){
70615     rc = SQLITE_NOMEM;
70616   }else{
70617     int iBuf;
70618
70619     iBuf = iStart % nBuf;
70620     if( iBuf ){
70621       int nRead = nBuf - iBuf;
70622       if( (iStart + nRead) > pSorter->iWriteOff ){
70623         nRead = (int)(pSorter->iWriteOff - iStart);
70624       }
70625       rc = sqlite3OsRead(
70626           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
70627       );
70628       assert( rc!=SQLITE_IOERR_SHORT_READ );
70629     }
70630
70631     if( rc==SQLITE_OK ){
70632       u64 nByte;                       /* Size of PMA in bytes */
70633       pIter->iEof = pSorter->iWriteOff;
70634       rc = vdbeSorterIterVarint(db, pIter, &nByte);
70635       pIter->iEof = pIter->iReadOff + nByte;
70636       *pnByte += nByte;
70637     }
70638   }
70639
70640   if( rc==SQLITE_OK ){
70641     rc = vdbeSorterIterNext(db, pIter);
70642   }
70643   return rc;
70644 }
70645
70646
70647 /*
70648 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
70649 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
70650 ** used by the comparison. If an error occurs, return an SQLite error code.
70651 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
70652 ** value, depending on whether key1 is smaller, equal to or larger than key2.
70653 **
70654 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
70655 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
70656 ** is true and key1 contains even a single NULL value, it is considered to
70657 ** be less than key2. Even if key2 also contains NULL values.
70658 **
70659 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
70660 ** has been allocated and contains an unpacked record that is used as key2.
70661 */
70662 static void vdbeSorterCompare(
70663   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
70664   int bOmitRowid,                 /* Ignore rowid field at end of keys */
70665   const void *pKey1, int nKey1,   /* Left side of comparison */
70666   const void *pKey2, int nKey2,   /* Right side of comparison */
70667   int *pRes                       /* OUT: Result of comparison */
70668 ){
70669   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
70670   VdbeSorter *pSorter = pCsr->pSorter;
70671   UnpackedRecord *r2 = pSorter->pUnpacked;
70672   int i;
70673
70674   if( pKey2 ){
70675     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
70676   }
70677
70678   if( bOmitRowid ){
70679     r2->nField = pKeyInfo->nField;
70680     assert( r2->nField>0 );
70681     for(i=0; i<r2->nField; i++){
70682       if( r2->aMem[i].flags & MEM_Null ){
70683         *pRes = -1;
70684         return;
70685       }
70686     }
70687     r2->flags |= UNPACKED_PREFIX_MATCH;
70688   }
70689
70690   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
70691 }
70692
70693 /*
70694 ** This function is called to compare two iterator keys when merging 
70695 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
70696 ** value to recalculate.
70697 */
70698 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
70699   VdbeSorter *pSorter = pCsr->pSorter;
70700   int i1;
70701   int i2;
70702   int iRes;
70703   VdbeSorterIter *p1;
70704   VdbeSorterIter *p2;
70705
70706   assert( iOut<pSorter->nTree && iOut>0 );
70707
70708   if( iOut>=(pSorter->nTree/2) ){
70709     i1 = (iOut - pSorter->nTree/2) * 2;
70710     i2 = i1 + 1;
70711   }else{
70712     i1 = pSorter->aTree[iOut*2];
70713     i2 = pSorter->aTree[iOut*2+1];
70714   }
70715
70716   p1 = &pSorter->aIter[i1];
70717   p2 = &pSorter->aIter[i2];
70718
70719   if( p1->pFile==0 ){
70720     iRes = i2;
70721   }else if( p2->pFile==0 ){
70722     iRes = i1;
70723   }else{
70724     int res;
70725     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
70726     vdbeSorterCompare(
70727         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
70728     );
70729     if( res<=0 ){
70730       iRes = i1;
70731     }else{
70732       iRes = i2;
70733     }
70734   }
70735
70736   pSorter->aTree[iOut] = iRes;
70737   return SQLITE_OK;
70738 }
70739
70740 /*
70741 ** Initialize the temporary index cursor just opened as a sorter cursor.
70742 */
70743 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
70744   int pgsz;                       /* Page size of main database */
70745   int mxCache;                    /* Cache size */
70746   VdbeSorter *pSorter;            /* The new sorter */
70747   char *d;                        /* Dummy */
70748
70749   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
70750   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
70751   if( pSorter==0 ){
70752     return SQLITE_NOMEM;
70753   }
70754   
70755   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
70756   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
70757   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
70758
70759   if( !sqlite3TempInMemory(db) ){
70760     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
70761     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
70762     mxCache = db->aDb[0].pSchema->cache_size;
70763     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
70764     pSorter->mxPmaSize = mxCache * pgsz;
70765   }
70766
70767   return SQLITE_OK;
70768 }
70769
70770 /*
70771 ** Free the list of sorted records starting at pRecord.
70772 */
70773 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
70774   SorterRecord *p;
70775   SorterRecord *pNext;
70776   for(p=pRecord; p; p=pNext){
70777     pNext = p->pNext;
70778     sqlite3DbFree(db, p);
70779   }
70780 }
70781
70782 /*
70783 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
70784 */
70785 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
70786   VdbeSorter *pSorter = pCsr->pSorter;
70787   if( pSorter ){
70788     if( pSorter->aIter ){
70789       int i;
70790       for(i=0; i<pSorter->nTree; i++){
70791         vdbeSorterIterZero(db, &pSorter->aIter[i]);
70792       }
70793       sqlite3DbFree(db, pSorter->aIter);
70794     }
70795     if( pSorter->pTemp1 ){
70796       sqlite3OsCloseFree(pSorter->pTemp1);
70797     }
70798     vdbeSorterRecordFree(db, pSorter->pRecord);
70799     sqlite3DbFree(db, pSorter->pUnpacked);
70800     sqlite3DbFree(db, pSorter);
70801     pCsr->pSorter = 0;
70802   }
70803 }
70804
70805 /*
70806 ** Allocate space for a file-handle and open a temporary file. If successful,
70807 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
70808 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
70809 */
70810 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
70811   int dummy;
70812   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
70813       SQLITE_OPEN_TEMP_JOURNAL |
70814       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
70815       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
70816   );
70817 }
70818
70819 /*
70820 ** Merge the two sorted lists p1 and p2 into a single list.
70821 ** Set *ppOut to the head of the new list.
70822 */
70823 static void vdbeSorterMerge(
70824   const VdbeCursor *pCsr,         /* For pKeyInfo */
70825   SorterRecord *p1,               /* First list to merge */
70826   SorterRecord *p2,               /* Second list to merge */
70827   SorterRecord **ppOut            /* OUT: Head of merged list */
70828 ){
70829   SorterRecord *pFinal = 0;
70830   SorterRecord **pp = &pFinal;
70831   void *pVal2 = p2 ? p2->pVal : 0;
70832
70833   while( p1 && p2 ){
70834     int res;
70835     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
70836     if( res<=0 ){
70837       *pp = p1;
70838       pp = &p1->pNext;
70839       p1 = p1->pNext;
70840       pVal2 = 0;
70841     }else{
70842       *pp = p2;
70843        pp = &p2->pNext;
70844       p2 = p2->pNext;
70845       if( p2==0 ) break;
70846       pVal2 = p2->pVal;
70847     }
70848   }
70849   *pp = p1 ? p1 : p2;
70850   *ppOut = pFinal;
70851 }
70852
70853 /*
70854 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
70855 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
70856 ** occurs.
70857 */
70858 static int vdbeSorterSort(const VdbeCursor *pCsr){
70859   int i;
70860   SorterRecord **aSlot;
70861   SorterRecord *p;
70862   VdbeSorter *pSorter = pCsr->pSorter;
70863
70864   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
70865   if( !aSlot ){
70866     return SQLITE_NOMEM;
70867   }
70868
70869   p = pSorter->pRecord;
70870   while( p ){
70871     SorterRecord *pNext = p->pNext;
70872     p->pNext = 0;
70873     for(i=0; aSlot[i]; i++){
70874       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70875       aSlot[i] = 0;
70876     }
70877     aSlot[i] = p;
70878     p = pNext;
70879   }
70880
70881   p = 0;
70882   for(i=0; i<64; i++){
70883     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70884   }
70885   pSorter->pRecord = p;
70886
70887   sqlite3_free(aSlot);
70888   return SQLITE_OK;
70889 }
70890
70891 /*
70892 ** Initialize a file-writer object.
70893 */
70894 static void fileWriterInit(
70895   sqlite3 *db,                    /* Database (for malloc) */
70896   sqlite3_file *pFile,            /* File to write to */
70897   FileWriter *p,                  /* Object to populate */
70898   i64 iStart                      /* Offset of pFile to begin writing at */
70899 ){
70900   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
70901
70902   memset(p, 0, sizeof(FileWriter));
70903   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
70904   if( !p->aBuffer ){
70905     p->eFWErr = SQLITE_NOMEM;
70906   }else{
70907     p->iBufEnd = p->iBufStart = (iStart % nBuf);
70908     p->iWriteOff = iStart - p->iBufStart;
70909     p->nBuffer = nBuf;
70910     p->pFile = pFile;
70911   }
70912 }
70913
70914 /*
70915 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
70916 ** if successful, or an SQLite error code if an error occurs.
70917 */
70918 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
70919   int nRem = nData;
70920   while( nRem>0 && p->eFWErr==0 ){
70921     int nCopy = nRem;
70922     if( nCopy>(p->nBuffer - p->iBufEnd) ){
70923       nCopy = p->nBuffer - p->iBufEnd;
70924     }
70925
70926     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
70927     p->iBufEnd += nCopy;
70928     if( p->iBufEnd==p->nBuffer ){
70929       p->eFWErr = sqlite3OsWrite(p->pFile, 
70930           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
70931           p->iWriteOff + p->iBufStart
70932       );
70933       p->iBufStart = p->iBufEnd = 0;
70934       p->iWriteOff += p->nBuffer;
70935     }
70936     assert( p->iBufEnd<p->nBuffer );
70937
70938     nRem -= nCopy;
70939   }
70940 }
70941
70942 /*
70943 ** Flush any buffered data to disk and clean up the file-writer object.
70944 ** The results of using the file-writer after this call are undefined.
70945 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
70946 ** required. Otherwise, return an SQLite error code.
70947 **
70948 ** Before returning, set *piEof to the offset immediately following the
70949 ** last byte written to the file.
70950 */
70951 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
70952   int rc;
70953   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
70954     p->eFWErr = sqlite3OsWrite(p->pFile, 
70955         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
70956         p->iWriteOff + p->iBufStart
70957     );
70958   }
70959   *piEof = (p->iWriteOff + p->iBufEnd);
70960   sqlite3DbFree(db, p->aBuffer);
70961   rc = p->eFWErr;
70962   memset(p, 0, sizeof(FileWriter));
70963   return rc;
70964 }
70965
70966 /*
70967 ** Write value iVal encoded as a varint to the file-write object. Return 
70968 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
70969 */
70970 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
70971   int nByte; 
70972   u8 aByte[10];
70973   nByte = sqlite3PutVarint(aByte, iVal);
70974   fileWriterWrite(p, aByte, nByte);
70975 }
70976
70977 /*
70978 ** Write the current contents of the in-memory linked-list to a PMA. Return
70979 ** SQLITE_OK if successful, or an SQLite error code otherwise.
70980 **
70981 ** The format of a PMA is:
70982 **
70983 **     * A varint. This varint contains the total number of bytes of content
70984 **       in the PMA (not including the varint itself).
70985 **
70986 **     * One or more records packed end-to-end in order of ascending keys. 
70987 **       Each record consists of a varint followed by a blob of data (the 
70988 **       key). The varint is the number of bytes in the blob of data.
70989 */
70990 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
70991   int rc = SQLITE_OK;             /* Return code */
70992   VdbeSorter *pSorter = pCsr->pSorter;
70993   FileWriter writer;
70994
70995   memset(&writer, 0, sizeof(FileWriter));
70996
70997   if( pSorter->nInMemory==0 ){
70998     assert( pSorter->pRecord==0 );
70999     return rc;
71000   }
71001
71002   rc = vdbeSorterSort(pCsr);
71003
71004   /* If the first temporary PMA file has not been opened, open it now. */
71005   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
71006     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
71007     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
71008     assert( pSorter->iWriteOff==0 );
71009     assert( pSorter->nPMA==0 );
71010   }
71011
71012   if( rc==SQLITE_OK ){
71013     SorterRecord *p;
71014     SorterRecord *pNext = 0;
71015
71016     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
71017     pSorter->nPMA++;
71018     fileWriterWriteVarint(&writer, pSorter->nInMemory);
71019     for(p=pSorter->pRecord; p; p=pNext){
71020       pNext = p->pNext;
71021       fileWriterWriteVarint(&writer, p->nVal);
71022       fileWriterWrite(&writer, p->pVal, p->nVal);
71023       sqlite3DbFree(db, p);
71024     }
71025     pSorter->pRecord = p;
71026     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
71027   }
71028
71029   return rc;
71030 }
71031
71032 /*
71033 ** Add a record to the sorter.
71034 */
71035 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
71036   sqlite3 *db,                    /* Database handle */
71037   const VdbeCursor *pCsr,               /* Sorter cursor */
71038   Mem *pVal                       /* Memory cell containing record */
71039 ){
71040   VdbeSorter *pSorter = pCsr->pSorter;
71041   int rc = SQLITE_OK;             /* Return Code */
71042   SorterRecord *pNew;             /* New list element */
71043
71044   assert( pSorter );
71045   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
71046
71047   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
71048   if( pNew==0 ){
71049     rc = SQLITE_NOMEM;
71050   }else{
71051     pNew->pVal = (void *)&pNew[1];
71052     memcpy(pNew->pVal, pVal->z, pVal->n);
71053     pNew->nVal = pVal->n;
71054     pNew->pNext = pSorter->pRecord;
71055     pSorter->pRecord = pNew;
71056   }
71057
71058   /* See if the contents of the sorter should now be written out. They
71059   ** are written out when either of the following are true:
71060   **
71061   **   * The total memory allocated for the in-memory list is greater 
71062   **     than (page-size * cache-size), or
71063   **
71064   **   * The total memory allocated for the in-memory list is greater 
71065   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
71066   */
71067   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
71068         (pSorter->nInMemory>pSorter->mxPmaSize)
71069      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
71070   )){
71071 #ifdef SQLITE_DEBUG
71072     i64 nExpect = pSorter->iWriteOff
71073                 + sqlite3VarintLen(pSorter->nInMemory)
71074                 + pSorter->nInMemory;
71075 #endif
71076     rc = vdbeSorterListToPMA(db, pCsr);
71077     pSorter->nInMemory = 0;
71078     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
71079   }
71080
71081   return rc;
71082 }
71083
71084 /*
71085 ** Helper function for sqlite3VdbeSorterRewind(). 
71086 */
71087 static int vdbeSorterInitMerge(
71088   sqlite3 *db,                    /* Database handle */
71089   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
71090   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
71091 ){
71092   VdbeSorter *pSorter = pCsr->pSorter;
71093   int rc = SQLITE_OK;             /* Return code */
71094   int i;                          /* Used to iterator through aIter[] */
71095   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
71096
71097   /* Initialize the iterators. */
71098   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
71099     VdbeSorterIter *pIter = &pSorter->aIter[i];
71100     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
71101     pSorter->iReadOff = pIter->iEof;
71102     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
71103     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
71104   }
71105
71106   /* Initialize the aTree[] array. */
71107   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
71108     rc = vdbeSorterDoCompare(pCsr, i);
71109   }
71110
71111   *pnByte = nByte;
71112   return rc;
71113 }
71114
71115 /*
71116 ** Once the sorter has been populated, this function is called to prepare
71117 ** for iterating through its contents in sorted order.
71118 */
71119 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71120   VdbeSorter *pSorter = pCsr->pSorter;
71121   int rc;                         /* Return code */
71122   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
71123   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
71124   int nIter;                      /* Number of iterators used */
71125   int nByte;                      /* Bytes of space required for aIter/aTree */
71126   int N = 2;                      /* Power of 2 >= nIter */
71127
71128   assert( pSorter );
71129
71130   /* If no data has been written to disk, then do not do so now. Instead,
71131   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
71132   ** from the in-memory list.  */
71133   if( pSorter->nPMA==0 ){
71134     *pbEof = !pSorter->pRecord;
71135     assert( pSorter->aTree==0 );
71136     return vdbeSorterSort(pCsr);
71137   }
71138
71139   /* Write the current in-memory list to a PMA. */
71140   rc = vdbeSorterListToPMA(db, pCsr);
71141   if( rc!=SQLITE_OK ) return rc;
71142
71143   /* Allocate space for aIter[] and aTree[]. */
71144   nIter = pSorter->nPMA;
71145   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
71146   assert( nIter>0 );
71147   while( N<nIter ) N += N;
71148   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
71149   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
71150   if( !pSorter->aIter ) return SQLITE_NOMEM;
71151   pSorter->aTree = (int *)&pSorter->aIter[N];
71152   pSorter->nTree = N;
71153
71154   do {
71155     int iNew;                     /* Index of new, merged, PMA */
71156
71157     for(iNew=0; 
71158         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
71159         iNew++
71160     ){
71161       int rc2;                    /* Return code from fileWriterFinish() */
71162       FileWriter writer;          /* Object used to write to disk */
71163       i64 nWrite;                 /* Number of bytes in new PMA */
71164
71165       memset(&writer, 0, sizeof(FileWriter));
71166
71167       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
71168       ** initialize an iterator for each of them and break out of the loop.
71169       ** These iterators will be incrementally merged as the VDBE layer calls
71170       ** sqlite3VdbeSorterNext().
71171       **
71172       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
71173       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
71174       ** are merged into a single PMA that is written to file pTemp2.
71175       */
71176       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
71177       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
71178       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71179         break;
71180       }
71181
71182       /* Open the second temp file, if it is not already open. */
71183       if( pTemp2==0 ){
71184         assert( iWrite2==0 );
71185         rc = vdbeSorterOpenTempFile(db, &pTemp2);
71186       }
71187
71188       if( rc==SQLITE_OK ){
71189         int bEof = 0;
71190         fileWriterInit(db, pTemp2, &writer, iWrite2);
71191         fileWriterWriteVarint(&writer, nWrite);
71192         while( rc==SQLITE_OK && bEof==0 ){
71193           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71194           assert( pIter->pFile );
71195
71196           fileWriterWriteVarint(&writer, pIter->nKey);
71197           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
71198           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
71199         }
71200         rc2 = fileWriterFinish(db, &writer, &iWrite2);
71201         if( rc==SQLITE_OK ) rc = rc2;
71202       }
71203     }
71204
71205     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71206       break;
71207     }else{
71208       sqlite3_file *pTmp = pSorter->pTemp1;
71209       pSorter->nPMA = iNew;
71210       pSorter->pTemp1 = pTemp2;
71211       pTemp2 = pTmp;
71212       pSorter->iWriteOff = iWrite2;
71213       pSorter->iReadOff = 0;
71214       iWrite2 = 0;
71215     }
71216   }while( rc==SQLITE_OK );
71217
71218   if( pTemp2 ){
71219     sqlite3OsCloseFree(pTemp2);
71220   }
71221   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71222   return rc;
71223 }
71224
71225 /*
71226 ** Advance to the next element in the sorter.
71227 */
71228 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71229   VdbeSorter *pSorter = pCsr->pSorter;
71230   int rc;                         /* Return code */
71231
71232   if( pSorter->aTree ){
71233     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
71234     int i;                        /* Index of aTree[] to recalculate */
71235
71236     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
71237     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
71238       rc = vdbeSorterDoCompare(pCsr, i);
71239     }
71240
71241     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71242   }else{
71243     SorterRecord *pFree = pSorter->pRecord;
71244     pSorter->pRecord = pFree->pNext;
71245     pFree->pNext = 0;
71246     vdbeSorterRecordFree(db, pFree);
71247     *pbEof = !pSorter->pRecord;
71248     rc = SQLITE_OK;
71249   }
71250   return rc;
71251 }
71252
71253 /*
71254 ** Return a pointer to a buffer owned by the sorter that contains the 
71255 ** current key.
71256 */
71257 static void *vdbeSorterRowkey(
71258   const VdbeSorter *pSorter,      /* Sorter object */
71259   int *pnKey                      /* OUT: Size of current key in bytes */
71260 ){
71261   void *pKey;
71262   if( pSorter->aTree ){
71263     VdbeSorterIter *pIter;
71264     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71265     *pnKey = pIter->nKey;
71266     pKey = pIter->aKey;
71267   }else{
71268     *pnKey = pSorter->pRecord->nVal;
71269     pKey = pSorter->pRecord->pVal;
71270   }
71271   return pKey;
71272 }
71273
71274 /*
71275 ** Copy the current sorter key into the memory cell pOut.
71276 */
71277 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
71278   VdbeSorter *pSorter = pCsr->pSorter;
71279   void *pKey; int nKey;           /* Sorter key to copy into pOut */
71280
71281   pKey = vdbeSorterRowkey(pSorter, &nKey);
71282   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71283     return SQLITE_NOMEM;
71284   }
71285   pOut->n = nKey;
71286   MemSetTypeFlag(pOut, MEM_Blob);
71287   memcpy(pOut->z, pKey, nKey);
71288
71289   return SQLITE_OK;
71290 }
71291
71292 /*
71293 ** Compare the key in memory cell pVal with the key that the sorter cursor
71294 ** passed as the first argument currently points to. For the purposes of
71295 ** the comparison, ignore the rowid field at the end of each record.
71296 **
71297 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71298 ** Otherwise, set *pRes to a negative, zero or positive value if the
71299 ** key in pVal is smaller than, equal to or larger than the current sorter
71300 ** key.
71301 */
71302 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71303   const VdbeCursor *pCsr,         /* Sorter cursor */
71304   Mem *pVal,                      /* Value to compare to current sorter key */
71305   int *pRes                       /* OUT: Result of comparison */
71306 ){
71307   VdbeSorter *pSorter = pCsr->pSorter;
71308   void *pKey; int nKey;           /* Sorter key to compare pVal with */
71309
71310   pKey = vdbeSorterRowkey(pSorter, &nKey);
71311   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71312   return SQLITE_OK;
71313 }
71314
71315 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
71316
71317 /************** End of vdbesort.c ********************************************/
71318 /************** Begin file journal.c *****************************************/
71319 /*
71320 ** 2007 August 22
71321 **
71322 ** The author disclaims copyright to this source code.  In place of
71323 ** a legal notice, here is a blessing:
71324 **
71325 **    May you do good and not evil.
71326 **    May you find forgiveness for yourself and forgive others.
71327 **    May you share freely, never taking more than you give.
71328 **
71329 *************************************************************************
71330 **
71331 ** This file implements a special kind of sqlite3_file object used
71332 ** by SQLite to create journal files if the atomic-write optimization
71333 ** is enabled.
71334 **
71335 ** The distinctive characteristic of this sqlite3_file is that the
71336 ** actual on disk file is created lazily. When the file is created,
71337 ** the caller specifies a buffer size for an in-memory buffer to
71338 ** be used to service read() and write() requests. The actual file
71339 ** on disk is not created or populated until either:
71340 **
71341 **   1) The in-memory representation grows too large for the allocated 
71342 **      buffer, or
71343 **   2) The sqlite3JournalCreate() function is called.
71344 */
71345 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
71346
71347
71348 /*
71349 ** A JournalFile object is a subclass of sqlite3_file used by
71350 ** as an open file handle for journal files.
71351 */
71352 struct JournalFile {
71353   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
71354   int nBuf;                       /* Size of zBuf[] in bytes */
71355   char *zBuf;                     /* Space to buffer journal writes */
71356   int iSize;                      /* Amount of zBuf[] currently used */
71357   int flags;                      /* xOpen flags */
71358   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
71359   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
71360   const char *zJournal;           /* Name of the journal file */
71361 };
71362 typedef struct JournalFile JournalFile;
71363
71364 /*
71365 ** If it does not already exists, create and populate the on-disk file 
71366 ** for JournalFile p.
71367 */
71368 static int createFile(JournalFile *p){
71369   int rc = SQLITE_OK;
71370   if( !p->pReal ){
71371     sqlite3_file *pReal = (sqlite3_file *)&p[1];
71372     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
71373     if( rc==SQLITE_OK ){
71374       p->pReal = pReal;
71375       if( p->iSize>0 ){
71376         assert(p->iSize<=p->nBuf);
71377         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
71378       }
71379     }
71380   }
71381   return rc;
71382 }
71383
71384 /*
71385 ** Close the file.
71386 */
71387 static int jrnlClose(sqlite3_file *pJfd){
71388   JournalFile *p = (JournalFile *)pJfd;
71389   if( p->pReal ){
71390     sqlite3OsClose(p->pReal);
71391   }
71392   sqlite3_free(p->zBuf);
71393   return SQLITE_OK;
71394 }
71395
71396 /*
71397 ** Read data from the file.
71398 */
71399 static int jrnlRead(
71400   sqlite3_file *pJfd,    /* The journal file from which to read */
71401   void *zBuf,            /* Put the results here */
71402   int iAmt,              /* Number of bytes to read */
71403   sqlite_int64 iOfst     /* Begin reading at this offset */
71404 ){
71405   int rc = SQLITE_OK;
71406   JournalFile *p = (JournalFile *)pJfd;
71407   if( p->pReal ){
71408     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
71409   }else if( (iAmt+iOfst)>p->iSize ){
71410     rc = SQLITE_IOERR_SHORT_READ;
71411   }else{
71412     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
71413   }
71414   return rc;
71415 }
71416
71417 /*
71418 ** Write data to the file.
71419 */
71420 static int jrnlWrite(
71421   sqlite3_file *pJfd,    /* The journal file into which to write */
71422   const void *zBuf,      /* Take data to be written from here */
71423   int iAmt,              /* Number of bytes to write */
71424   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
71425 ){
71426   int rc = SQLITE_OK;
71427   JournalFile *p = (JournalFile *)pJfd;
71428   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
71429     rc = createFile(p);
71430   }
71431   if( rc==SQLITE_OK ){
71432     if( p->pReal ){
71433       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
71434     }else{
71435       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
71436       if( p->iSize<(iOfst+iAmt) ){
71437         p->iSize = (iOfst+iAmt);
71438       }
71439     }
71440   }
71441   return rc;
71442 }
71443
71444 /*
71445 ** Truncate the file.
71446 */
71447 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71448   int rc = SQLITE_OK;
71449   JournalFile *p = (JournalFile *)pJfd;
71450   if( p->pReal ){
71451     rc = sqlite3OsTruncate(p->pReal, size);
71452   }else if( size<p->iSize ){
71453     p->iSize = size;
71454   }
71455   return rc;
71456 }
71457
71458 /*
71459 ** Sync the file.
71460 */
71461 static int jrnlSync(sqlite3_file *pJfd, int flags){
71462   int rc;
71463   JournalFile *p = (JournalFile *)pJfd;
71464   if( p->pReal ){
71465     rc = sqlite3OsSync(p->pReal, flags);
71466   }else{
71467     rc = SQLITE_OK;
71468   }
71469   return rc;
71470 }
71471
71472 /*
71473 ** Query the size of the file in bytes.
71474 */
71475 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71476   int rc = SQLITE_OK;
71477   JournalFile *p = (JournalFile *)pJfd;
71478   if( p->pReal ){
71479     rc = sqlite3OsFileSize(p->pReal, pSize);
71480   }else{
71481     *pSize = (sqlite_int64) p->iSize;
71482   }
71483   return rc;
71484 }
71485
71486 /*
71487 ** Table of methods for JournalFile sqlite3_file object.
71488 */
71489 static struct sqlite3_io_methods JournalFileMethods = {
71490   1,             /* iVersion */
71491   jrnlClose,     /* xClose */
71492   jrnlRead,      /* xRead */
71493   jrnlWrite,     /* xWrite */
71494   jrnlTruncate,  /* xTruncate */
71495   jrnlSync,      /* xSync */
71496   jrnlFileSize,  /* xFileSize */
71497   0,             /* xLock */
71498   0,             /* xUnlock */
71499   0,             /* xCheckReservedLock */
71500   0,             /* xFileControl */
71501   0,             /* xSectorSize */
71502   0,             /* xDeviceCharacteristics */
71503   0,             /* xShmMap */
71504   0,             /* xShmLock */
71505   0,             /* xShmBarrier */
71506   0              /* xShmUnmap */
71507 };
71508
71509 /* 
71510 ** Open a journal file.
71511 */
71512 SQLITE_PRIVATE int sqlite3JournalOpen(
71513   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
71514   const char *zName,         /* Name of the journal file */
71515   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
71516   int flags,                 /* Opening flags */
71517   int nBuf                   /* Bytes buffered before opening the file */
71518 ){
71519   JournalFile *p = (JournalFile *)pJfd;
71520   memset(p, 0, sqlite3JournalSize(pVfs));
71521   if( nBuf>0 ){
71522     p->zBuf = sqlite3MallocZero(nBuf);
71523     if( !p->zBuf ){
71524       return SQLITE_NOMEM;
71525     }
71526   }else{
71527     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
71528   }
71529   p->pMethod = &JournalFileMethods;
71530   p->nBuf = nBuf;
71531   p->flags = flags;
71532   p->zJournal = zName;
71533   p->pVfs = pVfs;
71534   return SQLITE_OK;
71535 }
71536
71537 /*
71538 ** If the argument p points to a JournalFile structure, and the underlying
71539 ** file has not yet been created, create it now.
71540 */
71541 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
71542   if( p->pMethods!=&JournalFileMethods ){
71543     return SQLITE_OK;
71544   }
71545   return createFile((JournalFile *)p);
71546 }
71547
71548 /* 
71549 ** Return the number of bytes required to store a JournalFile that uses vfs
71550 ** pVfs to create the underlying on-disk files.
71551 */
71552 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
71553   return (pVfs->szOsFile+sizeof(JournalFile));
71554 }
71555 #endif
71556
71557 /************** End of journal.c *********************************************/
71558 /************** Begin file memjournal.c **************************************/
71559 /*
71560 ** 2008 October 7
71561 **
71562 ** The author disclaims copyright to this source code.  In place of
71563 ** a legal notice, here is a blessing:
71564 **
71565 **    May you do good and not evil.
71566 **    May you find forgiveness for yourself and forgive others.
71567 **    May you share freely, never taking more than you give.
71568 **
71569 *************************************************************************
71570 **
71571 ** This file contains code use to implement an in-memory rollback journal.
71572 ** The in-memory rollback journal is used to journal transactions for
71573 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
71574 */
71575
71576 /* Forward references to internal structures */
71577 typedef struct MemJournal MemJournal;
71578 typedef struct FilePoint FilePoint;
71579 typedef struct FileChunk FileChunk;
71580
71581 /* Space to hold the rollback journal is allocated in increments of
71582 ** this many bytes.
71583 **
71584 ** The size chosen is a little less than a power of two.  That way,
71585 ** the FileChunk object will have a size that almost exactly fills
71586 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
71587 ** memory allocators.
71588 */
71589 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
71590
71591 /* Macro to find the minimum of two numeric values.
71592 */
71593 #ifndef MIN
71594 # define MIN(x,y) ((x)<(y)?(x):(y))
71595 #endif
71596
71597 /*
71598 ** The rollback journal is composed of a linked list of these structures.
71599 */
71600 struct FileChunk {
71601   FileChunk *pNext;               /* Next chunk in the journal */
71602   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
71603 };
71604
71605 /*
71606 ** An instance of this object serves as a cursor into the rollback journal.
71607 ** The cursor can be either for reading or writing.
71608 */
71609 struct FilePoint {
71610   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
71611   FileChunk *pChunk;              /* Specific chunk into which cursor points */
71612 };
71613
71614 /*
71615 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
71616 ** is an instance of this class.
71617 */
71618 struct MemJournal {
71619   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
71620   FileChunk *pFirst;              /* Head of in-memory chunk-list */
71621   FilePoint endpoint;             /* Pointer to the end of the file */
71622   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
71623 };
71624
71625 /*
71626 ** Read data from the in-memory journal file.  This is the implementation
71627 ** of the sqlite3_vfs.xRead method.
71628 */
71629 static int memjrnlRead(
71630   sqlite3_file *pJfd,    /* The journal file from which to read */
71631   void *zBuf,            /* Put the results here */
71632   int iAmt,              /* Number of bytes to read */
71633   sqlite_int64 iOfst     /* Begin reading at this offset */
71634 ){
71635   MemJournal *p = (MemJournal *)pJfd;
71636   u8 *zOut = zBuf;
71637   int nRead = iAmt;
71638   int iChunkOffset;
71639   FileChunk *pChunk;
71640
71641   /* SQLite never tries to read past the end of a rollback journal file */
71642   assert( iOfst+iAmt<=p->endpoint.iOffset );
71643
71644   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
71645     sqlite3_int64 iOff = 0;
71646     for(pChunk=p->pFirst; 
71647         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
71648         pChunk=pChunk->pNext
71649     ){
71650       iOff += JOURNAL_CHUNKSIZE;
71651     }
71652   }else{
71653     pChunk = p->readpoint.pChunk;
71654   }
71655
71656   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
71657   do {
71658     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
71659     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
71660     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
71661     zOut += nCopy;
71662     nRead -= iSpace;
71663     iChunkOffset = 0;
71664   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
71665   p->readpoint.iOffset = iOfst+iAmt;
71666   p->readpoint.pChunk = pChunk;
71667
71668   return SQLITE_OK;
71669 }
71670
71671 /*
71672 ** Write data to the file.
71673 */
71674 static int memjrnlWrite(
71675   sqlite3_file *pJfd,    /* The journal file into which to write */
71676   const void *zBuf,      /* Take data to be written from here */
71677   int iAmt,              /* Number of bytes to write */
71678   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
71679 ){
71680   MemJournal *p = (MemJournal *)pJfd;
71681   int nWrite = iAmt;
71682   u8 *zWrite = (u8 *)zBuf;
71683
71684   /* An in-memory journal file should only ever be appended to. Random
71685   ** access writes are not required by sqlite.
71686   */
71687   assert( iOfst==p->endpoint.iOffset );
71688   UNUSED_PARAMETER(iOfst);
71689
71690   while( nWrite>0 ){
71691     FileChunk *pChunk = p->endpoint.pChunk;
71692     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
71693     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
71694
71695     if( iChunkOffset==0 ){
71696       /* New chunk is required to extend the file. */
71697       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
71698       if( !pNew ){
71699         return SQLITE_IOERR_NOMEM;
71700       }
71701       pNew->pNext = 0;
71702       if( pChunk ){
71703         assert( p->pFirst );
71704         pChunk->pNext = pNew;
71705       }else{
71706         assert( !p->pFirst );
71707         p->pFirst = pNew;
71708       }
71709       p->endpoint.pChunk = pNew;
71710     }
71711
71712     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
71713     zWrite += iSpace;
71714     nWrite -= iSpace;
71715     p->endpoint.iOffset += iSpace;
71716   }
71717
71718   return SQLITE_OK;
71719 }
71720
71721 /*
71722 ** Truncate the file.
71723 */
71724 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71725   MemJournal *p = (MemJournal *)pJfd;
71726   FileChunk *pChunk;
71727   assert(size==0);
71728   UNUSED_PARAMETER(size);
71729   pChunk = p->pFirst;
71730   while( pChunk ){
71731     FileChunk *pTmp = pChunk;
71732     pChunk = pChunk->pNext;
71733     sqlite3_free(pTmp);
71734   }
71735   sqlite3MemJournalOpen(pJfd);
71736   return SQLITE_OK;
71737 }
71738
71739 /*
71740 ** Close the file.
71741 */
71742 static int memjrnlClose(sqlite3_file *pJfd){
71743   memjrnlTruncate(pJfd, 0);
71744   return SQLITE_OK;
71745 }
71746
71747
71748 /*
71749 ** Sync the file.
71750 **
71751 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
71752 ** is never called in a working implementation.  This implementation
71753 ** exists purely as a contingency, in case some malfunction in some other
71754 ** part of SQLite causes Sync to be called by mistake.
71755 */
71756 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
71757   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71758   return SQLITE_OK;
71759 }
71760
71761 /*
71762 ** Query the size of the file in bytes.
71763 */
71764 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71765   MemJournal *p = (MemJournal *)pJfd;
71766   *pSize = (sqlite_int64) p->endpoint.iOffset;
71767   return SQLITE_OK;
71768 }
71769
71770 /*
71771 ** Table of methods for MemJournal sqlite3_file object.
71772 */
71773 static const struct sqlite3_io_methods MemJournalMethods = {
71774   1,                /* iVersion */
71775   memjrnlClose,     /* xClose */
71776   memjrnlRead,      /* xRead */
71777   memjrnlWrite,     /* xWrite */
71778   memjrnlTruncate,  /* xTruncate */
71779   memjrnlSync,      /* xSync */
71780   memjrnlFileSize,  /* xFileSize */
71781   0,                /* xLock */
71782   0,                /* xUnlock */
71783   0,                /* xCheckReservedLock */
71784   0,                /* xFileControl */
71785   0,                /* xSectorSize */
71786   0,                /* xDeviceCharacteristics */
71787   0,                /* xShmMap */
71788   0,                /* xShmLock */
71789   0,                /* xShmBarrier */
71790   0                 /* xShmUnlock */
71791 };
71792
71793 /* 
71794 ** Open a journal file.
71795 */
71796 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
71797   MemJournal *p = (MemJournal *)pJfd;
71798   assert( EIGHT_BYTE_ALIGNMENT(p) );
71799   memset(p, 0, sqlite3MemJournalSize());
71800   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
71801 }
71802
71803 /*
71804 ** Return true if the file-handle passed as an argument is 
71805 ** an in-memory journal 
71806 */
71807 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
71808   return pJfd->pMethods==&MemJournalMethods;
71809 }
71810
71811 /* 
71812 ** Return the number of bytes required to store a MemJournal file descriptor.
71813 */
71814 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
71815   return sizeof(MemJournal);
71816 }
71817
71818 /************** End of memjournal.c ******************************************/
71819 /************** Begin file walker.c ******************************************/
71820 /*
71821 ** 2008 August 16
71822 **
71823 ** The author disclaims copyright to this source code.  In place of
71824 ** a legal notice, here is a blessing:
71825 **
71826 **    May you do good and not evil.
71827 **    May you find forgiveness for yourself and forgive others.
71828 **    May you share freely, never taking more than you give.
71829 **
71830 *************************************************************************
71831 ** This file contains routines used for walking the parser tree for
71832 ** an SQL statement.
71833 */
71834 /* #include <stdlib.h> */
71835 /* #include <string.h> */
71836
71837
71838 /*
71839 ** Walk an expression tree.  Invoke the callback once for each node
71840 ** of the expression, while decending.  (In other words, the callback
71841 ** is invoked before visiting children.)
71842 **
71843 ** The return value from the callback should be one of the WRC_*
71844 ** constants to specify how to proceed with the walk.
71845 **
71846 **    WRC_Continue      Continue descending down the tree.
71847 **
71848 **    WRC_Prune         Do not descend into child nodes.  But allow
71849 **                      the walk to continue with sibling nodes.
71850 **
71851 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
71852 **                      return the top-level walk call.
71853 **
71854 ** The return value from this routine is WRC_Abort to abandon the tree walk
71855 ** and WRC_Continue to continue.
71856 */
71857 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
71858   int rc;
71859   if( pExpr==0 ) return WRC_Continue;
71860   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
71861   testcase( ExprHasProperty(pExpr, EP_Reduced) );
71862   rc = pWalker->xExprCallback(pWalker, pExpr);
71863   if( rc==WRC_Continue
71864               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
71865     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
71866     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
71867     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71868       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
71869     }else{
71870       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
71871     }
71872   }
71873   return rc & WRC_Abort;
71874 }
71875
71876 /*
71877 ** Call sqlite3WalkExpr() for every expression in list p or until
71878 ** an abort request is seen.
71879 */
71880 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
71881   int i;
71882   struct ExprList_item *pItem;
71883   if( p ){
71884     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
71885       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
71886     }
71887   }
71888   return WRC_Continue;
71889 }
71890
71891 /*
71892 ** Walk all expressions associated with SELECT statement p.  Do
71893 ** not invoke the SELECT callback on p, but do (of course) invoke
71894 ** any expr callbacks and SELECT callbacks that come from subqueries.
71895 ** Return WRC_Abort or WRC_Continue.
71896 */
71897 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
71898   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
71899   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
71900   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
71901   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
71902   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
71903   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
71904   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
71905   return WRC_Continue;
71906 }
71907
71908 /*
71909 ** Walk the parse trees associated with all subqueries in the
71910 ** FROM clause of SELECT statement p.  Do not invoke the select
71911 ** callback on p, but do invoke it on each FROM clause subquery
71912 ** and on any subqueries further down in the tree.  Return 
71913 ** WRC_Abort or WRC_Continue;
71914 */
71915 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
71916   SrcList *pSrc;
71917   int i;
71918   struct SrcList_item *pItem;
71919
71920   pSrc = p->pSrc;
71921   if( ALWAYS(pSrc) ){
71922     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
71923       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
71924         return WRC_Abort;
71925       }
71926     }
71927   }
71928   return WRC_Continue;
71929
71930
71931 /*
71932 ** Call sqlite3WalkExpr() for every expression in Select statement p.
71933 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
71934 ** on the compound select chain, p->pPrior.
71935 **
71936 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
71937 ** there is an abort request.
71938 **
71939 ** If the Walker does not have an xSelectCallback() then this routine
71940 ** is a no-op returning WRC_Continue.
71941 */
71942 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
71943   int rc;
71944   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
71945   rc = WRC_Continue;
71946   pWalker->walkerDepth++;
71947   while( p ){
71948     rc = pWalker->xSelectCallback(pWalker, p);
71949     if( rc ) break;
71950     if( sqlite3WalkSelectExpr(pWalker, p)
71951      || sqlite3WalkSelectFrom(pWalker, p)
71952     ){
71953       pWalker->walkerDepth--;
71954       return WRC_Abort;
71955     }
71956     p = p->pPrior;
71957   }
71958   pWalker->walkerDepth--;
71959   return rc & WRC_Abort;
71960 }
71961
71962 /************** End of walker.c **********************************************/
71963 /************** Begin file resolve.c *****************************************/
71964 /*
71965 ** 2008 August 18
71966 **
71967 ** The author disclaims copyright to this source code.  In place of
71968 ** a legal notice, here is a blessing:
71969 **
71970 **    May you do good and not evil.
71971 **    May you find forgiveness for yourself and forgive others.
71972 **    May you share freely, never taking more than you give.
71973 **
71974 *************************************************************************
71975 **
71976 ** This file contains routines used for walking the parser tree and
71977 ** resolve all identifiers by associating them with a particular
71978 ** table and column.
71979 */
71980 /* #include <stdlib.h> */
71981 /* #include <string.h> */
71982
71983 /*
71984 ** Walk the expression tree pExpr and increase the aggregate function
71985 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
71986 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
71987 ** outer query into an inner subquery.
71988 **
71989 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
71990 ** is a helper function - a callback for the tree walker.
71991 */
71992 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
71993   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
71994   return WRC_Continue;
71995 }
71996 static void incrAggFunctionDepth(Expr *pExpr, int N){
71997   if( N>0 ){
71998     Walker w;
71999     memset(&w, 0, sizeof(w));
72000     w.xExprCallback = incrAggDepth;
72001     w.u.i = N;
72002     sqlite3WalkExpr(&w, pExpr);
72003   }
72004 }
72005
72006 /*
72007 ** Turn the pExpr expression into an alias for the iCol-th column of the
72008 ** result set in pEList.
72009 **
72010 ** If the result set column is a simple column reference, then this routine
72011 ** makes an exact copy.  But for any other kind of expression, this
72012 ** routine make a copy of the result set column as the argument to the
72013 ** TK_AS operator.  The TK_AS operator causes the expression to be
72014 ** evaluated just once and then reused for each alias.
72015 **
72016 ** The reason for suppressing the TK_AS term when the expression is a simple
72017 ** column reference is so that the column reference will be recognized as
72018 ** usable by indices within the WHERE clause processing logic. 
72019 **
72020 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
72021 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
72022 **
72023 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
72024 **
72025 ** Is equivalent to:
72026 **
72027 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
72028 **
72029 ** The result of random()%5 in the GROUP BY clause is probably different
72030 ** from the result in the result-set.  We might fix this someday.  Or
72031 ** then again, we might not...
72032 **
72033 ** The nSubquery parameter specifies how many levels of subquery the
72034 ** alias is removed from the original expression.  The usually value is
72035 ** zero but it might be more if the alias is contained within a subquery
72036 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
72037 ** structures must be increased by the nSubquery amount.
72038 */
72039 static void resolveAlias(
72040   Parse *pParse,         /* Parsing context */
72041   ExprList *pEList,      /* A result set */
72042   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
72043   Expr *pExpr,           /* Transform this into an alias to the result set */
72044   const char *zType,     /* "GROUP" or "ORDER" or "" */
72045   int nSubquery          /* Number of subqueries that the label is moving */
72046 ){
72047   Expr *pOrig;           /* The iCol-th column of the result set */
72048   Expr *pDup;            /* Copy of pOrig */
72049   sqlite3 *db;           /* The database connection */
72050
72051   assert( iCol>=0 && iCol<pEList->nExpr );
72052   pOrig = pEList->a[iCol].pExpr;
72053   assert( pOrig!=0 );
72054   assert( pOrig->flags & EP_Resolved );
72055   db = pParse->db;
72056   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
72057     pDup = sqlite3ExprDup(db, pOrig, 0);
72058     incrAggFunctionDepth(pDup, nSubquery);
72059     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
72060     if( pDup==0 ) return;
72061     if( pEList->a[iCol].iAlias==0 ){
72062       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
72063     }
72064     pDup->iTable = pEList->a[iCol].iAlias;
72065   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
72066     pDup = sqlite3ExprDup(db, pOrig, 0);
72067     if( pDup==0 ) return;
72068   }else{
72069     char *zToken = pOrig->u.zToken;
72070     assert( zToken!=0 );
72071     pOrig->u.zToken = 0;
72072     pDup = sqlite3ExprDup(db, pOrig, 0);
72073     pOrig->u.zToken = zToken;
72074     if( pDup==0 ) return;
72075     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
72076     pDup->flags2 |= EP2_MallocedToken;
72077     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
72078   }
72079   if( pExpr->flags & EP_ExpCollate ){
72080     pDup->pColl = pExpr->pColl;
72081     pDup->flags |= EP_ExpCollate;
72082   }
72083
72084   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
72085   ** prevents ExprDelete() from deleting the Expr structure itself,
72086   ** allowing it to be repopulated by the memcpy() on the following line.
72087   */
72088   ExprSetProperty(pExpr, EP_Static);
72089   sqlite3ExprDelete(db, pExpr);
72090   memcpy(pExpr, pDup, sizeof(*pExpr));
72091   sqlite3DbFree(db, pDup);
72092 }
72093
72094
72095 /*
72096 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
72097 **
72098 ** Return FALSE if the USING clause is NULL or if it does not contain
72099 ** zCol.
72100 */
72101 static int nameInUsingClause(IdList *pUsing, const char *zCol){
72102   if( pUsing ){
72103     int k;
72104     for(k=0; k<pUsing->nId; k++){
72105       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
72106     }
72107   }
72108   return 0;
72109 }
72110
72111
72112 /*
72113 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
72114 ** that name in the set of source tables in pSrcList and make the pExpr 
72115 ** expression node refer back to that source column.  The following changes
72116 ** are made to pExpr:
72117 **
72118 **    pExpr->iDb           Set the index in db->aDb[] of the database X
72119 **                         (even if X is implied).
72120 **    pExpr->iTable        Set to the cursor number for the table obtained
72121 **                         from pSrcList.
72122 **    pExpr->pTab          Points to the Table structure of X.Y (even if
72123 **                         X and/or Y are implied.)
72124 **    pExpr->iColumn       Set to the column number within the table.
72125 **    pExpr->op            Set to TK_COLUMN.
72126 **    pExpr->pLeft         Any expression this points to is deleted
72127 **    pExpr->pRight        Any expression this points to is deleted.
72128 **
72129 ** The zDb variable is the name of the database (the "X").  This value may be
72130 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
72131 ** can be used.  The zTable variable is the name of the table (the "Y").  This
72132 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
72133 ** means that the form of the name is Z and that columns from any table
72134 ** can be used.
72135 **
72136 ** If the name cannot be resolved unambiguously, leave an error message
72137 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
72138 */
72139 static int lookupName(
72140   Parse *pParse,       /* The parsing context */
72141   const char *zDb,     /* Name of the database containing table, or NULL */
72142   const char *zTab,    /* Name of table containing column, or NULL */
72143   const char *zCol,    /* Name of the column. */
72144   NameContext *pNC,    /* The name context used to resolve the name */
72145   Expr *pExpr          /* Make this EXPR node point to the selected column */
72146 ){
72147   int i, j;                         /* Loop counters */
72148   int cnt = 0;                      /* Number of matching column names */
72149   int cntTab = 0;                   /* Number of matching table names */
72150   int nSubquery = 0;                /* How many levels of subquery */
72151   sqlite3 *db = pParse->db;         /* The database connection */
72152   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
72153   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
72154   NameContext *pTopNC = pNC;        /* First namecontext in the list */
72155   Schema *pSchema = 0;              /* Schema of the expression */
72156   int isTrigger = 0;
72157
72158   assert( pNC );     /* the name context cannot be NULL. */
72159   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
72160   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72161
72162   /* Initialize the node to no-match */
72163   pExpr->iTable = -1;
72164   pExpr->pTab = 0;
72165   ExprSetIrreducible(pExpr);
72166
72167   /* Start at the inner-most context and move outward until a match is found */
72168   while( pNC && cnt==0 ){
72169     ExprList *pEList;
72170     SrcList *pSrcList = pNC->pSrcList;
72171
72172     if( pSrcList ){
72173       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
72174         Table *pTab;
72175         int iDb;
72176         Column *pCol;
72177   
72178         pTab = pItem->pTab;
72179         assert( pTab!=0 && pTab->zName!=0 );
72180         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72181         assert( pTab->nCol>0 );
72182         if( zTab ){
72183           if( pItem->zAlias ){
72184             char *zTabName = pItem->zAlias;
72185             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
72186           }else{
72187             char *zTabName = pTab->zName;
72188             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
72189               continue;
72190             }
72191             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
72192               continue;
72193             }
72194           }
72195         }
72196         if( 0==(cntTab++) ){
72197           pExpr->iTable = pItem->iCursor;
72198           pExpr->pTab = pTab;
72199           pSchema = pTab->pSchema;
72200           pMatch = pItem;
72201         }
72202         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
72203           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72204             /* If there has been exactly one prior match and this match
72205             ** is for the right-hand table of a NATURAL JOIN or is in a 
72206             ** USING clause, then skip this match.
72207             */
72208             if( cnt==1 ){
72209               if( pItem->jointype & JT_NATURAL ) continue;
72210               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
72211             }
72212             cnt++;
72213             pExpr->iTable = pItem->iCursor;
72214             pExpr->pTab = pTab;
72215             pMatch = pItem;
72216             pSchema = pTab->pSchema;
72217             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
72218             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
72219             break;
72220           }
72221         }
72222       }
72223     }
72224
72225 #ifndef SQLITE_OMIT_TRIGGER
72226     /* If we have not already resolved the name, then maybe 
72227     ** it is a new.* or old.* trigger argument reference
72228     */
72229     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
72230       int op = pParse->eTriggerOp;
72231       Table *pTab = 0;
72232       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
72233       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
72234         pExpr->iTable = 1;
72235         pTab = pParse->pTriggerTab;
72236       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
72237         pExpr->iTable = 0;
72238         pTab = pParse->pTriggerTab;
72239       }
72240
72241       if( pTab ){ 
72242         int iCol;
72243         pSchema = pTab->pSchema;
72244         cntTab++;
72245         for(iCol=0; iCol<pTab->nCol; iCol++){
72246           Column *pCol = &pTab->aCol[iCol];
72247           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72248             if( iCol==pTab->iPKey ){
72249               iCol = -1;
72250             }
72251             break;
72252           }
72253         }
72254         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
72255           iCol = -1;        /* IMP: R-44911-55124 */
72256         }
72257         if( iCol<pTab->nCol ){
72258           cnt++;
72259           if( iCol<0 ){
72260             pExpr->affinity = SQLITE_AFF_INTEGER;
72261           }else if( pExpr->iTable==0 ){
72262             testcase( iCol==31 );
72263             testcase( iCol==32 );
72264             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72265           }else{
72266             testcase( iCol==31 );
72267             testcase( iCol==32 );
72268             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72269           }
72270           pExpr->iColumn = (i16)iCol;
72271           pExpr->pTab = pTab;
72272           isTrigger = 1;
72273         }
72274       }
72275     }
72276 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
72277
72278     /*
72279     ** Perhaps the name is a reference to the ROWID
72280     */
72281     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
72282       cnt = 1;
72283       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
72284       pExpr->affinity = SQLITE_AFF_INTEGER;
72285     }
72286
72287     /*
72288     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
72289     ** might refer to an result-set alias.  This happens, for example, when
72290     ** we are resolving names in the WHERE clause of the following command:
72291     **
72292     **     SELECT a+b AS x FROM table WHERE x<10;
72293     **
72294     ** In cases like this, replace pExpr with a copy of the expression that
72295     ** forms the result set entry ("a+b" in the example) and return immediately.
72296     ** Note that the expression in the result set should have already been
72297     ** resolved by the time the WHERE clause is resolved.
72298     */
72299     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
72300       for(j=0; j<pEList->nExpr; j++){
72301         char *zAs = pEList->a[j].zName;
72302         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72303           Expr *pOrig;
72304           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
72305           assert( pExpr->x.pList==0 );
72306           assert( pExpr->x.pSelect==0 );
72307           pOrig = pEList->a[j].pExpr;
72308           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
72309             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
72310             return WRC_Abort;
72311           }
72312           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
72313           cnt = 1;
72314           pMatch = 0;
72315           assert( zTab==0 && zDb==0 );
72316           goto lookupname_end;
72317         }
72318       } 
72319     }
72320
72321     /* Advance to the next name context.  The loop will exit when either
72322     ** we have a match (cnt>0) or when we run out of name contexts.
72323     */
72324     if( cnt==0 ){
72325       pNC = pNC->pNext;
72326       nSubquery++;
72327     }
72328   }
72329
72330   /*
72331   ** If X and Y are NULL (in other words if only the column name Z is
72332   ** supplied) and the value of Z is enclosed in double-quotes, then
72333   ** Z is a string literal if it doesn't match any column names.  In that
72334   ** case, we need to return right away and not make any changes to
72335   ** pExpr.
72336   **
72337   ** Because no reference was made to outer contexts, the pNC->nRef
72338   ** fields are not changed in any context.
72339   */
72340   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
72341     pExpr->op = TK_STRING;
72342     pExpr->pTab = 0;
72343     return WRC_Prune;
72344   }
72345
72346   /*
72347   ** cnt==0 means there was not match.  cnt>1 means there were two or
72348   ** more matches.  Either way, we have an error.
72349   */
72350   if( cnt!=1 ){
72351     const char *zErr;
72352     zErr = cnt==0 ? "no such column" : "ambiguous column name";
72353     if( zDb ){
72354       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
72355     }else if( zTab ){
72356       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
72357     }else{
72358       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
72359     }
72360     pParse->checkSchema = 1;
72361     pTopNC->nErr++;
72362   }
72363
72364   /* If a column from a table in pSrcList is referenced, then record
72365   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
72366   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
72367   ** column number is greater than the number of bits in the bitmask
72368   ** then set the high-order bit of the bitmask.
72369   */
72370   if( pExpr->iColumn>=0 && pMatch!=0 ){
72371     int n = pExpr->iColumn;
72372     testcase( n==BMS-1 );
72373     if( n>=BMS ){
72374       n = BMS-1;
72375     }
72376     assert( pMatch->iCursor==pExpr->iTable );
72377     pMatch->colUsed |= ((Bitmask)1)<<n;
72378   }
72379
72380   /* Clean up and return
72381   */
72382   sqlite3ExprDelete(db, pExpr->pLeft);
72383   pExpr->pLeft = 0;
72384   sqlite3ExprDelete(db, pExpr->pRight);
72385   pExpr->pRight = 0;
72386   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
72387 lookupname_end:
72388   if( cnt==1 ){
72389     assert( pNC!=0 );
72390     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
72391     /* Increment the nRef value on all name contexts from TopNC up to
72392     ** the point where the name matched. */
72393     for(;;){
72394       assert( pTopNC!=0 );
72395       pTopNC->nRef++;
72396       if( pTopNC==pNC ) break;
72397       pTopNC = pTopNC->pNext;
72398     }
72399     return WRC_Prune;
72400   } else {
72401     return WRC_Abort;
72402   }
72403 }
72404
72405 /*
72406 ** Allocate and return a pointer to an expression to load the column iCol
72407 ** from datasource iSrc in SrcList pSrc.
72408 */
72409 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
72410   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
72411   if( p ){
72412     struct SrcList_item *pItem = &pSrc->a[iSrc];
72413     p->pTab = pItem->pTab;
72414     p->iTable = pItem->iCursor;
72415     if( p->pTab->iPKey==iCol ){
72416       p->iColumn = -1;
72417     }else{
72418       p->iColumn = (ynVar)iCol;
72419       testcase( iCol==BMS );
72420       testcase( iCol==BMS-1 );
72421       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
72422     }
72423     ExprSetProperty(p, EP_Resolved);
72424   }
72425   return p;
72426 }
72427
72428 /*
72429 ** This routine is callback for sqlite3WalkExpr().
72430 **
72431 ** Resolve symbolic names into TK_COLUMN operators for the current
72432 ** node in the expression tree.  Return 0 to continue the search down
72433 ** the tree or 2 to abort the tree walk.
72434 **
72435 ** This routine also does error checking and name resolution for
72436 ** function names.  The operator for aggregate functions is changed
72437 ** to TK_AGG_FUNCTION.
72438 */
72439 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
72440   NameContext *pNC;
72441   Parse *pParse;
72442
72443   pNC = pWalker->u.pNC;
72444   assert( pNC!=0 );
72445   pParse = pNC->pParse;
72446   assert( pParse==pWalker->pParse );
72447
72448   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
72449   ExprSetProperty(pExpr, EP_Resolved);
72450 #ifndef NDEBUG
72451   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
72452     SrcList *pSrcList = pNC->pSrcList;
72453     int i;
72454     for(i=0; i<pNC->pSrcList->nSrc; i++){
72455       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
72456     }
72457   }
72458 #endif
72459   switch( pExpr->op ){
72460
72461 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
72462     /* The special operator TK_ROW means use the rowid for the first
72463     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
72464     ** clause processing on UPDATE and DELETE statements.
72465     */
72466     case TK_ROW: {
72467       SrcList *pSrcList = pNC->pSrcList;
72468       struct SrcList_item *pItem;
72469       assert( pSrcList && pSrcList->nSrc==1 );
72470       pItem = pSrcList->a; 
72471       pExpr->op = TK_COLUMN;
72472       pExpr->pTab = pItem->pTab;
72473       pExpr->iTable = pItem->iCursor;
72474       pExpr->iColumn = -1;
72475       pExpr->affinity = SQLITE_AFF_INTEGER;
72476       break;
72477     }
72478 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
72479
72480     /* A lone identifier is the name of a column.
72481     */
72482     case TK_ID: {
72483       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
72484     }
72485   
72486     /* A table name and column name:     ID.ID
72487     ** Or a database, table and column:  ID.ID.ID
72488     */
72489     case TK_DOT: {
72490       const char *zColumn;
72491       const char *zTable;
72492       const char *zDb;
72493       Expr *pRight;
72494
72495       /* if( pSrcList==0 ) break; */
72496       pRight = pExpr->pRight;
72497       if( pRight->op==TK_ID ){
72498         zDb = 0;
72499         zTable = pExpr->pLeft->u.zToken;
72500         zColumn = pRight->u.zToken;
72501       }else{
72502         assert( pRight->op==TK_DOT );
72503         zDb = pExpr->pLeft->u.zToken;
72504         zTable = pRight->pLeft->u.zToken;
72505         zColumn = pRight->pRight->u.zToken;
72506       }
72507       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
72508     }
72509
72510     /* Resolve function names
72511     */
72512     case TK_CONST_FUNC:
72513     case TK_FUNCTION: {
72514       ExprList *pList = pExpr->x.pList;    /* The argument list */
72515       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
72516       int no_such_func = 0;       /* True if no such function exists */
72517       int wrong_num_args = 0;     /* True if wrong number of arguments */
72518       int is_agg = 0;             /* True if is an aggregate function */
72519       int auth;                   /* Authorization to use the function */
72520       int nId;                    /* Number of characters in function name */
72521       const char *zId;            /* The function name. */
72522       FuncDef *pDef;              /* Information about the function */
72523       u8 enc = ENC(pParse->db);   /* The database encoding */
72524
72525       testcase( pExpr->op==TK_CONST_FUNC );
72526       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72527       zId = pExpr->u.zToken;
72528       nId = sqlite3Strlen30(zId);
72529       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
72530       if( pDef==0 ){
72531         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
72532         if( pDef==0 ){
72533           no_such_func = 1;
72534         }else{
72535           wrong_num_args = 1;
72536         }
72537       }else{
72538         is_agg = pDef->xFunc==0;
72539       }
72540 #ifndef SQLITE_OMIT_AUTHORIZATION
72541       if( pDef ){
72542         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
72543         if( auth!=SQLITE_OK ){
72544           if( auth==SQLITE_DENY ){
72545             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
72546                                     pDef->zName);
72547             pNC->nErr++;
72548           }
72549           pExpr->op = TK_NULL;
72550           return WRC_Prune;
72551         }
72552       }
72553 #endif
72554       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
72555         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
72556         pNC->nErr++;
72557         is_agg = 0;
72558       }else if( no_such_func ){
72559         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
72560         pNC->nErr++;
72561       }else if( wrong_num_args ){
72562         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
72563              nId, zId);
72564         pNC->nErr++;
72565       }
72566       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
72567       sqlite3WalkExprList(pWalker, pList);
72568       if( is_agg ){
72569         NameContext *pNC2 = pNC;
72570         pExpr->op = TK_AGG_FUNCTION;
72571         pExpr->op2 = 0;
72572         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
72573           pExpr->op2++;
72574           pNC2 = pNC2->pNext;
72575         }
72576         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
72577         pNC->ncFlags |= NC_AllowAgg;
72578       }
72579       /* FIX ME:  Compute pExpr->affinity based on the expected return
72580       ** type of the function 
72581       */
72582       return WRC_Prune;
72583     }
72584 #ifndef SQLITE_OMIT_SUBQUERY
72585     case TK_SELECT:
72586     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
72587 #endif
72588     case TK_IN: {
72589       testcase( pExpr->op==TK_IN );
72590       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72591         int nRef = pNC->nRef;
72592 #ifndef SQLITE_OMIT_CHECK
72593         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
72594           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
72595         }
72596 #endif
72597         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
72598         assert( pNC->nRef>=nRef );
72599         if( nRef!=pNC->nRef ){
72600           ExprSetProperty(pExpr, EP_VarSelect);
72601         }
72602       }
72603       break;
72604     }
72605 #ifndef SQLITE_OMIT_CHECK
72606     case TK_VARIABLE: {
72607       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
72608         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
72609       }
72610       break;
72611     }
72612 #endif
72613   }
72614   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
72615 }
72616
72617 /*
72618 ** pEList is a list of expressions which are really the result set of the
72619 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
72620 ** This routine checks to see if pE is a simple identifier which corresponds
72621 ** to the AS-name of one of the terms of the expression list.  If it is,
72622 ** this routine return an integer between 1 and N where N is the number of
72623 ** elements in pEList, corresponding to the matching entry.  If there is
72624 ** no match, or if pE is not a simple identifier, then this routine
72625 ** return 0.
72626 **
72627 ** pEList has been resolved.  pE has not.
72628 */
72629 static int resolveAsName(
72630   Parse *pParse,     /* Parsing context for error messages */
72631   ExprList *pEList,  /* List of expressions to scan */
72632   Expr *pE           /* Expression we are trying to match */
72633 ){
72634   int i;             /* Loop counter */
72635
72636   UNUSED_PARAMETER(pParse);
72637
72638   if( pE->op==TK_ID ){
72639     char *zCol = pE->u.zToken;
72640     for(i=0; i<pEList->nExpr; i++){
72641       char *zAs = pEList->a[i].zName;
72642       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72643         return i+1;
72644       }
72645     }
72646   }
72647   return 0;
72648 }
72649
72650 /*
72651 ** pE is a pointer to an expression which is a single term in the
72652 ** ORDER BY of a compound SELECT.  The expression has not been
72653 ** name resolved.
72654 **
72655 ** At the point this routine is called, we already know that the
72656 ** ORDER BY term is not an integer index into the result set.  That
72657 ** case is handled by the calling routine.
72658 **
72659 ** Attempt to match pE against result set columns in the left-most
72660 ** SELECT statement.  Return the index i of the matching column,
72661 ** as an indication to the caller that it should sort by the i-th column.
72662 ** The left-most column is 1.  In other words, the value returned is the
72663 ** same integer value that would be used in the SQL statement to indicate
72664 ** the column.
72665 **
72666 ** If there is no match, return 0.  Return -1 if an error occurs.
72667 */
72668 static int resolveOrderByTermToExprList(
72669   Parse *pParse,     /* Parsing context for error messages */
72670   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
72671   Expr *pE           /* The specific ORDER BY term */
72672 ){
72673   int i;             /* Loop counter */
72674   ExprList *pEList;  /* The columns of the result set */
72675   NameContext nc;    /* Name context for resolving pE */
72676   sqlite3 *db;       /* Database connection */
72677   int rc;            /* Return code from subprocedures */
72678   u8 savedSuppErr;   /* Saved value of db->suppressErr */
72679
72680   assert( sqlite3ExprIsInteger(pE, &i)==0 );
72681   pEList = pSelect->pEList;
72682
72683   /* Resolve all names in the ORDER BY term expression
72684   */
72685   memset(&nc, 0, sizeof(nc));
72686   nc.pParse = pParse;
72687   nc.pSrcList = pSelect->pSrc;
72688   nc.pEList = pEList;
72689   nc.ncFlags = NC_AllowAgg;
72690   nc.nErr = 0;
72691   db = pParse->db;
72692   savedSuppErr = db->suppressErr;
72693   db->suppressErr = 1;
72694   rc = sqlite3ResolveExprNames(&nc, pE);
72695   db->suppressErr = savedSuppErr;
72696   if( rc ) return 0;
72697
72698   /* Try to match the ORDER BY expression against an expression
72699   ** in the result set.  Return an 1-based index of the matching
72700   ** result-set entry.
72701   */
72702   for(i=0; i<pEList->nExpr; i++){
72703     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
72704       return i+1;
72705     }
72706   }
72707
72708   /* If no match, return 0. */
72709   return 0;
72710 }
72711
72712 /*
72713 ** Generate an ORDER BY or GROUP BY term out-of-range error.
72714 */
72715 static void resolveOutOfRangeError(
72716   Parse *pParse,         /* The error context into which to write the error */
72717   const char *zType,     /* "ORDER" or "GROUP" */
72718   int i,                 /* The index (1-based) of the term out of range */
72719   int mx                 /* Largest permissible value of i */
72720 ){
72721   sqlite3ErrorMsg(pParse, 
72722     "%r %s BY term out of range - should be "
72723     "between 1 and %d", i, zType, mx);
72724 }
72725
72726 /*
72727 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
72728 ** each term of the ORDER BY clause is a constant integer between 1
72729 ** and N where N is the number of columns in the compound SELECT.
72730 **
72731 ** ORDER BY terms that are already an integer between 1 and N are
72732 ** unmodified.  ORDER BY terms that are integers outside the range of
72733 ** 1 through N generate an error.  ORDER BY terms that are expressions
72734 ** are matched against result set expressions of compound SELECT
72735 ** beginning with the left-most SELECT and working toward the right.
72736 ** At the first match, the ORDER BY expression is transformed into
72737 ** the integer column number.
72738 **
72739 ** Return the number of errors seen.
72740 */
72741 static int resolveCompoundOrderBy(
72742   Parse *pParse,        /* Parsing context.  Leave error messages here */
72743   Select *pSelect       /* The SELECT statement containing the ORDER BY */
72744 ){
72745   int i;
72746   ExprList *pOrderBy;
72747   ExprList *pEList;
72748   sqlite3 *db;
72749   int moreToDo = 1;
72750
72751   pOrderBy = pSelect->pOrderBy;
72752   if( pOrderBy==0 ) return 0;
72753   db = pParse->db;
72754 #if SQLITE_MAX_COLUMN
72755   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72756     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
72757     return 1;
72758   }
72759 #endif
72760   for(i=0; i<pOrderBy->nExpr; i++){
72761     pOrderBy->a[i].done = 0;
72762   }
72763   pSelect->pNext = 0;
72764   while( pSelect->pPrior ){
72765     pSelect->pPrior->pNext = pSelect;
72766     pSelect = pSelect->pPrior;
72767   }
72768   while( pSelect && moreToDo ){
72769     struct ExprList_item *pItem;
72770     moreToDo = 0;
72771     pEList = pSelect->pEList;
72772     assert( pEList!=0 );
72773     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72774       int iCol = -1;
72775       Expr *pE, *pDup;
72776       if( pItem->done ) continue;
72777       pE = pItem->pExpr;
72778       if( sqlite3ExprIsInteger(pE, &iCol) ){
72779         if( iCol<=0 || iCol>pEList->nExpr ){
72780           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
72781           return 1;
72782         }
72783       }else{
72784         iCol = resolveAsName(pParse, pEList, pE);
72785         if( iCol==0 ){
72786           pDup = sqlite3ExprDup(db, pE, 0);
72787           if( !db->mallocFailed ){
72788             assert(pDup);
72789             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
72790           }
72791           sqlite3ExprDelete(db, pDup);
72792         }
72793       }
72794       if( iCol>0 ){
72795         CollSeq *pColl = pE->pColl;
72796         int flags = pE->flags & EP_ExpCollate;
72797         sqlite3ExprDelete(db, pE);
72798         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
72799         if( pE==0 ) return 1;
72800         pE->pColl = pColl;
72801         pE->flags |= EP_IntValue | flags;
72802         pE->u.iValue = iCol;
72803         pItem->iOrderByCol = (u16)iCol;
72804         pItem->done = 1;
72805       }else{
72806         moreToDo = 1;
72807       }
72808     }
72809     pSelect = pSelect->pNext;
72810   }
72811   for(i=0; i<pOrderBy->nExpr; i++){
72812     if( pOrderBy->a[i].done==0 ){
72813       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
72814             "column in the result set", i+1);
72815       return 1;
72816     }
72817   }
72818   return 0;
72819 }
72820
72821 /*
72822 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
72823 ** the SELECT statement pSelect.  If any term is reference to a
72824 ** result set expression (as determined by the ExprList.a.iCol field)
72825 ** then convert that term into a copy of the corresponding result set
72826 ** column.
72827 **
72828 ** If any errors are detected, add an error message to pParse and
72829 ** return non-zero.  Return zero if no errors are seen.
72830 */
72831 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
72832   Parse *pParse,        /* Parsing context.  Leave error messages here */
72833   Select *pSelect,      /* The SELECT statement containing the clause */
72834   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
72835   const char *zType     /* "ORDER" or "GROUP" */
72836 ){
72837   int i;
72838   sqlite3 *db = pParse->db;
72839   ExprList *pEList;
72840   struct ExprList_item *pItem;
72841
72842   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
72843 #if SQLITE_MAX_COLUMN
72844   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72845     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
72846     return 1;
72847   }
72848 #endif
72849   pEList = pSelect->pEList;
72850   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
72851   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72852     if( pItem->iOrderByCol ){
72853       if( pItem->iOrderByCol>pEList->nExpr ){
72854         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
72855         return 1;
72856       }
72857       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
72858     }
72859   }
72860   return 0;
72861 }
72862
72863 /*
72864 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
72865 ** The Name context of the SELECT statement is pNC.  zType is either
72866 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
72867 **
72868 ** This routine resolves each term of the clause into an expression.
72869 ** If the order-by term is an integer I between 1 and N (where N is the
72870 ** number of columns in the result set of the SELECT) then the expression
72871 ** in the resolution is a copy of the I-th result-set expression.  If
72872 ** the order-by term is an identify that corresponds to the AS-name of
72873 ** a result-set expression, then the term resolves to a copy of the
72874 ** result-set expression.  Otherwise, the expression is resolved in
72875 ** the usual way - using sqlite3ResolveExprNames().
72876 **
72877 ** This routine returns the number of errors.  If errors occur, then
72878 ** an appropriate error message might be left in pParse.  (OOM errors
72879 ** excepted.)
72880 */
72881 static int resolveOrderGroupBy(
72882   NameContext *pNC,     /* The name context of the SELECT statement */
72883   Select *pSelect,      /* The SELECT statement holding pOrderBy */
72884   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
72885   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
72886 ){
72887   int i, j;                      /* Loop counters */
72888   int iCol;                      /* Column number */
72889   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
72890   Parse *pParse;                 /* Parsing context */
72891   int nResult;                   /* Number of terms in the result set */
72892
72893   if( pOrderBy==0 ) return 0;
72894   nResult = pSelect->pEList->nExpr;
72895   pParse = pNC->pParse;
72896   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72897     Expr *pE = pItem->pExpr;
72898     iCol = resolveAsName(pParse, pSelect->pEList, pE);
72899     if( iCol>0 ){
72900       /* If an AS-name match is found, mark this ORDER BY column as being
72901       ** a copy of the iCol-th result-set column.  The subsequent call to
72902       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
72903       ** copy of the iCol-th result-set expression. */
72904       pItem->iOrderByCol = (u16)iCol;
72905       continue;
72906     }
72907     if( sqlite3ExprIsInteger(pE, &iCol) ){
72908       /* The ORDER BY term is an integer constant.  Again, set the column
72909       ** number so that sqlite3ResolveOrderGroupBy() will convert the
72910       ** order-by term to a copy of the result-set expression */
72911       if( iCol<1 ){
72912         resolveOutOfRangeError(pParse, zType, i+1, nResult);
72913         return 1;
72914       }
72915       pItem->iOrderByCol = (u16)iCol;
72916       continue;
72917     }
72918
72919     /* Otherwise, treat the ORDER BY term as an ordinary expression */
72920     pItem->iOrderByCol = 0;
72921     if( sqlite3ResolveExprNames(pNC, pE) ){
72922       return 1;
72923     }
72924     for(j=0; j<pSelect->pEList->nExpr; j++){
72925       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
72926         pItem->iOrderByCol = j+1;
72927       }
72928     }
72929   }
72930   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
72931 }
72932
72933 /*
72934 ** Resolve names in the SELECT statement p and all of its descendents.
72935 */
72936 static int resolveSelectStep(Walker *pWalker, Select *p){
72937   NameContext *pOuterNC;  /* Context that contains this SELECT */
72938   NameContext sNC;        /* Name context of this SELECT */
72939   int isCompound;         /* True if p is a compound select */
72940   int nCompound;          /* Number of compound terms processed so far */
72941   Parse *pParse;          /* Parsing context */
72942   ExprList *pEList;       /* Result set expression list */
72943   int i;                  /* Loop counter */
72944   ExprList *pGroupBy;     /* The GROUP BY clause */
72945   Select *pLeftmost;      /* Left-most of SELECT of a compound */
72946   sqlite3 *db;            /* Database connection */
72947   
72948
72949   assert( p!=0 );
72950   if( p->selFlags & SF_Resolved ){
72951     return WRC_Prune;
72952   }
72953   pOuterNC = pWalker->u.pNC;
72954   pParse = pWalker->pParse;
72955   db = pParse->db;
72956
72957   /* Normally sqlite3SelectExpand() will be called first and will have
72958   ** already expanded this SELECT.  However, if this is a subquery within
72959   ** an expression, sqlite3ResolveExprNames() will be called without a
72960   ** prior call to sqlite3SelectExpand().  When that happens, let
72961   ** sqlite3SelectPrep() do all of the processing for this SELECT.
72962   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
72963   ** this routine in the correct order.
72964   */
72965   if( (p->selFlags & SF_Expanded)==0 ){
72966     sqlite3SelectPrep(pParse, p, pOuterNC);
72967     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
72968   }
72969
72970   isCompound = p->pPrior!=0;
72971   nCompound = 0;
72972   pLeftmost = p;
72973   while( p ){
72974     assert( (p->selFlags & SF_Expanded)!=0 );
72975     assert( (p->selFlags & SF_Resolved)==0 );
72976     p->selFlags |= SF_Resolved;
72977
72978     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
72979     ** are not allowed to refer to any names, so pass an empty NameContext.
72980     */
72981     memset(&sNC, 0, sizeof(sNC));
72982     sNC.pParse = pParse;
72983     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
72984         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
72985       return WRC_Abort;
72986     }
72987   
72988     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
72989     ** resolve the result-set expression list.
72990     */
72991     sNC.ncFlags = NC_AllowAgg;
72992     sNC.pSrcList = p->pSrc;
72993     sNC.pNext = pOuterNC;
72994   
72995     /* Resolve names in the result set. */
72996     pEList = p->pEList;
72997     assert( pEList!=0 );
72998     for(i=0; i<pEList->nExpr; i++){
72999       Expr *pX = pEList->a[i].pExpr;
73000       if( sqlite3ResolveExprNames(&sNC, pX) ){
73001         return WRC_Abort;
73002       }
73003     }
73004   
73005     /* Recursively resolve names in all subqueries
73006     */
73007     for(i=0; i<p->pSrc->nSrc; i++){
73008       struct SrcList_item *pItem = &p->pSrc->a[i];
73009       if( pItem->pSelect ){
73010         NameContext *pNC;         /* Used to iterate name contexts */
73011         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
73012         const char *zSavedContext = pParse->zAuthContext;
73013
73014         /* Count the total number of references to pOuterNC and all of its
73015         ** parent contexts. After resolving references to expressions in
73016         ** pItem->pSelect, check if this value has changed. If so, then
73017         ** SELECT statement pItem->pSelect must be correlated. Set the
73018         ** pItem->isCorrelated flag if this is the case. */
73019         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
73020
73021         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
73022         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
73023         pParse->zAuthContext = zSavedContext;
73024         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
73025
73026         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
73027         assert( pItem->isCorrelated==0 && nRef<=0 );
73028         pItem->isCorrelated = (nRef!=0);
73029       }
73030     }
73031   
73032     /* If there are no aggregate functions in the result-set, and no GROUP BY 
73033     ** expression, do not allow aggregates in any of the other expressions.
73034     */
73035     assert( (p->selFlags & SF_Aggregate)==0 );
73036     pGroupBy = p->pGroupBy;
73037     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
73038       p->selFlags |= SF_Aggregate;
73039     }else{
73040       sNC.ncFlags &= ~NC_AllowAgg;
73041     }
73042   
73043     /* If a HAVING clause is present, then there must be a GROUP BY clause.
73044     */
73045     if( p->pHaving && !pGroupBy ){
73046       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
73047       return WRC_Abort;
73048     }
73049   
73050     /* Add the expression list to the name-context before parsing the
73051     ** other expressions in the SELECT statement. This is so that
73052     ** expressions in the WHERE clause (etc.) can refer to expressions by
73053     ** aliases in the result set.
73054     **
73055     ** Minor point: If this is the case, then the expression will be
73056     ** re-evaluated for each reference to it.
73057     */
73058     sNC.pEList = p->pEList;
73059     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
73060        sqlite3ResolveExprNames(&sNC, p->pHaving)
73061     ){
73062       return WRC_Abort;
73063     }
73064
73065     /* The ORDER BY and GROUP BY clauses may not refer to terms in
73066     ** outer queries 
73067     */
73068     sNC.pNext = 0;
73069     sNC.ncFlags |= NC_AllowAgg;
73070
73071     /* Process the ORDER BY clause for singleton SELECT statements.
73072     ** The ORDER BY clause for compounds SELECT statements is handled
73073     ** below, after all of the result-sets for all of the elements of
73074     ** the compound have been resolved.
73075     */
73076     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
73077       return WRC_Abort;
73078     }
73079     if( db->mallocFailed ){
73080       return WRC_Abort;
73081     }
73082   
73083     /* Resolve the GROUP BY clause.  At the same time, make sure 
73084     ** the GROUP BY clause does not contain aggregate functions.
73085     */
73086     if( pGroupBy ){
73087       struct ExprList_item *pItem;
73088     
73089       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
73090         return WRC_Abort;
73091       }
73092       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
73093         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
73094           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
73095               "the GROUP BY clause");
73096           return WRC_Abort;
73097         }
73098       }
73099     }
73100
73101     /* Advance to the next term of the compound
73102     */
73103     p = p->pPrior;
73104     nCompound++;
73105   }
73106
73107   /* Resolve the ORDER BY on a compound SELECT after all terms of
73108   ** the compound have been resolved.
73109   */
73110   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
73111     return WRC_Abort;
73112   }
73113
73114   return WRC_Prune;
73115 }
73116
73117 /*
73118 ** This routine walks an expression tree and resolves references to
73119 ** table columns and result-set columns.  At the same time, do error
73120 ** checking on function usage and set a flag if any aggregate functions
73121 ** are seen.
73122 **
73123 ** To resolve table columns references we look for nodes (or subtrees) of the 
73124 ** form X.Y.Z or Y.Z or just Z where
73125 **
73126 **      X:   The name of a database.  Ex:  "main" or "temp" or
73127 **           the symbolic name assigned to an ATTACH-ed database.
73128 **
73129 **      Y:   The name of a table in a FROM clause.  Or in a trigger
73130 **           one of the special names "old" or "new".
73131 **
73132 **      Z:   The name of a column in table Y.
73133 **
73134 ** The node at the root of the subtree is modified as follows:
73135 **
73136 **    Expr.op        Changed to TK_COLUMN
73137 **    Expr.pTab      Points to the Table object for X.Y
73138 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
73139 **    Expr.iTable    The VDBE cursor number for X.Y
73140 **
73141 **
73142 ** To resolve result-set references, look for expression nodes of the
73143 ** form Z (with no X and Y prefix) where the Z matches the right-hand
73144 ** size of an AS clause in the result-set of a SELECT.  The Z expression
73145 ** is replaced by a copy of the left-hand side of the result-set expression.
73146 ** Table-name and function resolution occurs on the substituted expression
73147 ** tree.  For example, in:
73148 **
73149 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
73150 **
73151 ** The "x" term of the order by is replaced by "a+b" to render:
73152 **
73153 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
73154 **
73155 ** Function calls are checked to make sure that the function is 
73156 ** defined and that the correct number of arguments are specified.
73157 ** If the function is an aggregate function, then the NC_HasAgg flag is
73158 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
73159 ** If an expression contains aggregate functions then the EP_Agg
73160 ** property on the expression is set.
73161 **
73162 ** An error message is left in pParse if anything is amiss.  The number
73163 ** if errors is returned.
73164 */
73165 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
73166   NameContext *pNC,       /* Namespace to resolve expressions in. */
73167   Expr *pExpr             /* The expression to be analyzed. */
73168 ){
73169   u8 savedHasAgg;
73170   Walker w;
73171
73172   if( pExpr==0 ) return 0;
73173 #if SQLITE_MAX_EXPR_DEPTH>0
73174   {
73175     Parse *pParse = pNC->pParse;
73176     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
73177       return 1;
73178     }
73179     pParse->nHeight += pExpr->nHeight;
73180   }
73181 #endif
73182   savedHasAgg = pNC->ncFlags & NC_HasAgg;
73183   pNC->ncFlags &= ~NC_HasAgg;
73184   w.xExprCallback = resolveExprStep;
73185   w.xSelectCallback = resolveSelectStep;
73186   w.pParse = pNC->pParse;
73187   w.u.pNC = pNC;
73188   sqlite3WalkExpr(&w, pExpr);
73189 #if SQLITE_MAX_EXPR_DEPTH>0
73190   pNC->pParse->nHeight -= pExpr->nHeight;
73191 #endif
73192   if( pNC->nErr>0 || w.pParse->nErr>0 ){
73193     ExprSetProperty(pExpr, EP_Error);
73194   }
73195   if( pNC->ncFlags & NC_HasAgg ){
73196     ExprSetProperty(pExpr, EP_Agg);
73197   }else if( savedHasAgg ){
73198     pNC->ncFlags |= NC_HasAgg;
73199   }
73200   return ExprHasProperty(pExpr, EP_Error);
73201 }
73202
73203
73204 /*
73205 ** Resolve all names in all expressions of a SELECT and in all
73206 ** decendents of the SELECT, including compounds off of p->pPrior,
73207 ** subqueries in expressions, and subqueries used as FROM clause
73208 ** terms.
73209 **
73210 ** See sqlite3ResolveExprNames() for a description of the kinds of
73211 ** transformations that occur.
73212 **
73213 ** All SELECT statements should have been expanded using
73214 ** sqlite3SelectExpand() prior to invoking this routine.
73215 */
73216 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
73217   Parse *pParse,         /* The parser context */
73218   Select *p,             /* The SELECT statement being coded. */
73219   NameContext *pOuterNC  /* Name context for parent SELECT statement */
73220 ){
73221   Walker w;
73222
73223   assert( p!=0 );
73224   w.xExprCallback = resolveExprStep;
73225   w.xSelectCallback = resolveSelectStep;
73226   w.pParse = pParse;
73227   w.u.pNC = pOuterNC;
73228   sqlite3WalkSelect(&w, p);
73229 }
73230
73231 /************** End of resolve.c *********************************************/
73232 /************** Begin file expr.c ********************************************/
73233 /*
73234 ** 2001 September 15
73235 **
73236 ** The author disclaims copyright to this source code.  In place of
73237 ** a legal notice, here is a blessing:
73238 **
73239 **    May you do good and not evil.
73240 **    May you find forgiveness for yourself and forgive others.
73241 **    May you share freely, never taking more than you give.
73242 **
73243 *************************************************************************
73244 ** This file contains routines used for analyzing expressions and
73245 ** for generating VDBE code that evaluates expressions in SQLite.
73246 */
73247
73248 /*
73249 ** Return the 'affinity' of the expression pExpr if any.
73250 **
73251 ** If pExpr is a column, a reference to a column via an 'AS' alias,
73252 ** or a sub-select with a column as the return value, then the 
73253 ** affinity of that column is returned. Otherwise, 0x00 is returned,
73254 ** indicating no affinity for the expression.
73255 **
73256 ** i.e. the WHERE clause expresssions in the following statements all
73257 ** have an affinity:
73258 **
73259 ** CREATE TABLE t1(a);
73260 ** SELECT * FROM t1 WHERE a;
73261 ** SELECT a AS b FROM t1 WHERE b;
73262 ** SELECT * FROM t1 WHERE (select a from t1);
73263 */
73264 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
73265   int op = pExpr->op;
73266   if( op==TK_SELECT ){
73267     assert( pExpr->flags&EP_xIsSelect );
73268     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
73269   }
73270 #ifndef SQLITE_OMIT_CAST
73271   if( op==TK_CAST ){
73272     assert( !ExprHasProperty(pExpr, EP_IntValue) );
73273     return sqlite3AffinityType(pExpr->u.zToken);
73274   }
73275 #endif
73276   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
73277    && pExpr->pTab!=0
73278   ){
73279     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
73280     ** a TK_COLUMN but was previously evaluated and cached in a register */
73281     int j = pExpr->iColumn;
73282     if( j<0 ) return SQLITE_AFF_INTEGER;
73283     assert( pExpr->pTab && j<pExpr->pTab->nCol );
73284     return pExpr->pTab->aCol[j].affinity;
73285   }
73286   return pExpr->affinity;
73287 }
73288
73289 /*
73290 ** Set the explicit collating sequence for an expression to the
73291 ** collating sequence supplied in the second argument.
73292 */
73293 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
73294   if( pExpr && pColl ){
73295     pExpr->pColl = pColl;
73296     pExpr->flags |= EP_ExpCollate;
73297   }
73298   return pExpr;
73299 }
73300
73301 /*
73302 ** Set the collating sequence for expression pExpr to be the collating
73303 ** sequence named by pToken.   Return a pointer to the revised expression.
73304 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
73305 ** flag.  An explicit collating sequence will override implicit
73306 ** collating sequences.
73307 */
73308 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
73309   char *zColl = 0;            /* Dequoted name of collation sequence */
73310   CollSeq *pColl;
73311   sqlite3 *db = pParse->db;
73312   zColl = sqlite3NameFromToken(db, pCollName);
73313   pColl = sqlite3LocateCollSeq(pParse, zColl);
73314   sqlite3ExprSetColl(pExpr, pColl);
73315   sqlite3DbFree(db, zColl);
73316   return pExpr;
73317 }
73318
73319 /*
73320 ** Return the default collation sequence for the expression pExpr. If
73321 ** there is no default collation type, return 0.
73322 */
73323 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
73324   CollSeq *pColl = 0;
73325   Expr *p = pExpr;
73326   while( p ){
73327     int op;
73328     pColl = p->pColl;
73329     if( pColl ) break;
73330     op = p->op;
73331     if( p->pTab!=0 && (
73332         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
73333     )){
73334       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
73335       ** a TK_COLUMN but was previously evaluated and cached in a register */
73336       const char *zColl;
73337       int j = p->iColumn;
73338       if( j>=0 ){
73339         sqlite3 *db = pParse->db;
73340         zColl = p->pTab->aCol[j].zColl;
73341         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
73342         pExpr->pColl = pColl;
73343       }
73344       break;
73345     }
73346     if( op!=TK_CAST && op!=TK_UPLUS ){
73347       break;
73348     }
73349     p = p->pLeft;
73350   }
73351   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
73352     pColl = 0;
73353   }
73354   return pColl;
73355 }
73356
73357 /*
73358 ** pExpr is an operand of a comparison operator.  aff2 is the
73359 ** type affinity of the other operand.  This routine returns the
73360 ** type affinity that should be used for the comparison operator.
73361 */
73362 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
73363   char aff1 = sqlite3ExprAffinity(pExpr);
73364   if( aff1 && aff2 ){
73365     /* Both sides of the comparison are columns. If one has numeric
73366     ** affinity, use that. Otherwise use no affinity.
73367     */
73368     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
73369       return SQLITE_AFF_NUMERIC;
73370     }else{
73371       return SQLITE_AFF_NONE;
73372     }
73373   }else if( !aff1 && !aff2 ){
73374     /* Neither side of the comparison is a column.  Compare the
73375     ** results directly.
73376     */
73377     return SQLITE_AFF_NONE;
73378   }else{
73379     /* One side is a column, the other is not. Use the columns affinity. */
73380     assert( aff1==0 || aff2==0 );
73381     return (aff1 + aff2);
73382   }
73383 }
73384
73385 /*
73386 ** pExpr is a comparison operator.  Return the type affinity that should
73387 ** be applied to both operands prior to doing the comparison.
73388 */
73389 static char comparisonAffinity(Expr *pExpr){
73390   char aff;
73391   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
73392           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
73393           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
73394   assert( pExpr->pLeft );
73395   aff = sqlite3ExprAffinity(pExpr->pLeft);
73396   if( pExpr->pRight ){
73397     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
73398   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73399     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
73400   }else if( !aff ){
73401     aff = SQLITE_AFF_NONE;
73402   }
73403   return aff;
73404 }
73405
73406 /*
73407 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
73408 ** idx_affinity is the affinity of an indexed column. Return true
73409 ** if the index with affinity idx_affinity may be used to implement
73410 ** the comparison in pExpr.
73411 */
73412 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
73413   char aff = comparisonAffinity(pExpr);
73414   switch( aff ){
73415     case SQLITE_AFF_NONE:
73416       return 1;
73417     case SQLITE_AFF_TEXT:
73418       return idx_affinity==SQLITE_AFF_TEXT;
73419     default:
73420       return sqlite3IsNumericAffinity(idx_affinity);
73421   }
73422 }
73423
73424 /*
73425 ** Return the P5 value that should be used for a binary comparison
73426 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
73427 */
73428 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
73429   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
73430   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
73431   return aff;
73432 }
73433
73434 /*
73435 ** Return a pointer to the collation sequence that should be used by
73436 ** a binary comparison operator comparing pLeft and pRight.
73437 **
73438 ** If the left hand expression has a collating sequence type, then it is
73439 ** used. Otherwise the collation sequence for the right hand expression
73440 ** is used, or the default (BINARY) if neither expression has a collating
73441 ** type.
73442 **
73443 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
73444 ** it is not considered.
73445 */
73446 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
73447   Parse *pParse, 
73448   Expr *pLeft, 
73449   Expr *pRight
73450 ){
73451   CollSeq *pColl;
73452   assert( pLeft );
73453   if( pLeft->flags & EP_ExpCollate ){
73454     assert( pLeft->pColl );
73455     pColl = pLeft->pColl;
73456   }else if( pRight && pRight->flags & EP_ExpCollate ){
73457     assert( pRight->pColl );
73458     pColl = pRight->pColl;
73459   }else{
73460     pColl = sqlite3ExprCollSeq(pParse, pLeft);
73461     if( !pColl ){
73462       pColl = sqlite3ExprCollSeq(pParse, pRight);
73463     }
73464   }
73465   return pColl;
73466 }
73467
73468 /*
73469 ** Generate code for a comparison operator.
73470 */
73471 static int codeCompare(
73472   Parse *pParse,    /* The parsing (and code generating) context */
73473   Expr *pLeft,      /* The left operand */
73474   Expr *pRight,     /* The right operand */
73475   int opcode,       /* The comparison opcode */
73476   int in1, int in2, /* Register holding operands */
73477   int dest,         /* Jump here if true.  */
73478   int jumpIfNull    /* If true, jump if either operand is NULL */
73479 ){
73480   int p5;
73481   int addr;
73482   CollSeq *p4;
73483
73484   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
73485   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
73486   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
73487                            (void*)p4, P4_COLLSEQ);
73488   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
73489   return addr;
73490 }
73491
73492 #if SQLITE_MAX_EXPR_DEPTH>0
73493 /*
73494 ** Check that argument nHeight is less than or equal to the maximum
73495 ** expression depth allowed. If it is not, leave an error message in
73496 ** pParse.
73497 */
73498 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
73499   int rc = SQLITE_OK;
73500   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
73501   if( nHeight>mxHeight ){
73502     sqlite3ErrorMsg(pParse, 
73503        "Expression tree is too large (maximum depth %d)", mxHeight
73504     );
73505     rc = SQLITE_ERROR;
73506   }
73507   return rc;
73508 }
73509
73510 /* The following three functions, heightOfExpr(), heightOfExprList()
73511 ** and heightOfSelect(), are used to determine the maximum height
73512 ** of any expression tree referenced by the structure passed as the
73513 ** first argument.
73514 **
73515 ** If this maximum height is greater than the current value pointed
73516 ** to by pnHeight, the second parameter, then set *pnHeight to that
73517 ** value.
73518 */
73519 static void heightOfExpr(Expr *p, int *pnHeight){
73520   if( p ){
73521     if( p->nHeight>*pnHeight ){
73522       *pnHeight = p->nHeight;
73523     }
73524   }
73525 }
73526 static void heightOfExprList(ExprList *p, int *pnHeight){
73527   if( p ){
73528     int i;
73529     for(i=0; i<p->nExpr; i++){
73530       heightOfExpr(p->a[i].pExpr, pnHeight);
73531     }
73532   }
73533 }
73534 static void heightOfSelect(Select *p, int *pnHeight){
73535   if( p ){
73536     heightOfExpr(p->pWhere, pnHeight);
73537     heightOfExpr(p->pHaving, pnHeight);
73538     heightOfExpr(p->pLimit, pnHeight);
73539     heightOfExpr(p->pOffset, pnHeight);
73540     heightOfExprList(p->pEList, pnHeight);
73541     heightOfExprList(p->pGroupBy, pnHeight);
73542     heightOfExprList(p->pOrderBy, pnHeight);
73543     heightOfSelect(p->pPrior, pnHeight);
73544   }
73545 }
73546
73547 /*
73548 ** Set the Expr.nHeight variable in the structure passed as an 
73549 ** argument. An expression with no children, Expr.pList or 
73550 ** Expr.pSelect member has a height of 1. Any other expression
73551 ** has a height equal to the maximum height of any other 
73552 ** referenced Expr plus one.
73553 */
73554 static void exprSetHeight(Expr *p){
73555   int nHeight = 0;
73556   heightOfExpr(p->pLeft, &nHeight);
73557   heightOfExpr(p->pRight, &nHeight);
73558   if( ExprHasProperty(p, EP_xIsSelect) ){
73559     heightOfSelect(p->x.pSelect, &nHeight);
73560   }else{
73561     heightOfExprList(p->x.pList, &nHeight);
73562   }
73563   p->nHeight = nHeight + 1;
73564 }
73565
73566 /*
73567 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
73568 ** the height is greater than the maximum allowed expression depth,
73569 ** leave an error in pParse.
73570 */
73571 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
73572   exprSetHeight(p);
73573   sqlite3ExprCheckHeight(pParse, p->nHeight);
73574 }
73575
73576 /*
73577 ** Return the maximum height of any expression tree referenced
73578 ** by the select statement passed as an argument.
73579 */
73580 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
73581   int nHeight = 0;
73582   heightOfSelect(p, &nHeight);
73583   return nHeight;
73584 }
73585 #else
73586   #define exprSetHeight(y)
73587 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
73588
73589 /*
73590 ** This routine is the core allocator for Expr nodes.
73591 **
73592 ** Construct a new expression node and return a pointer to it.  Memory
73593 ** for this node and for the pToken argument is a single allocation
73594 ** obtained from sqlite3DbMalloc().  The calling function
73595 ** is responsible for making sure the node eventually gets freed.
73596 **
73597 ** If dequote is true, then the token (if it exists) is dequoted.
73598 ** If dequote is false, no dequoting is performance.  The deQuote
73599 ** parameter is ignored if pToken is NULL or if the token does not
73600 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
73601 ** then the EP_DblQuoted flag is set on the expression node.
73602 **
73603 ** Special case:  If op==TK_INTEGER and pToken points to a string that
73604 ** can be translated into a 32-bit integer, then the token is not
73605 ** stored in u.zToken.  Instead, the integer values is written
73606 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
73607 ** is allocated to hold the integer text and the dequote flag is ignored.
73608 */
73609 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
73610   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
73611   int op,                 /* Expression opcode */
73612   const Token *pToken,    /* Token argument.  Might be NULL */
73613   int dequote             /* True to dequote */
73614 ){
73615   Expr *pNew;
73616   int nExtra = 0;
73617   int iValue = 0;
73618
73619   if( pToken ){
73620     if( op!=TK_INTEGER || pToken->z==0
73621           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
73622       nExtra = pToken->n+1;
73623       assert( iValue>=0 );
73624     }
73625   }
73626   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
73627   if( pNew ){
73628     pNew->op = (u8)op;
73629     pNew->iAgg = -1;
73630     if( pToken ){
73631       if( nExtra==0 ){
73632         pNew->flags |= EP_IntValue;
73633         pNew->u.iValue = iValue;
73634       }else{
73635         int c;
73636         pNew->u.zToken = (char*)&pNew[1];
73637         assert( pToken->z!=0 || pToken->n==0 );
73638         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
73639         pNew->u.zToken[pToken->n] = 0;
73640         if( dequote && nExtra>=3 
73641              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
73642           sqlite3Dequote(pNew->u.zToken);
73643           if( c=='"' ) pNew->flags |= EP_DblQuoted;
73644         }
73645       }
73646     }
73647 #if SQLITE_MAX_EXPR_DEPTH>0
73648     pNew->nHeight = 1;
73649 #endif  
73650   }
73651   return pNew;
73652 }
73653
73654 /*
73655 ** Allocate a new expression node from a zero-terminated token that has
73656 ** already been dequoted.
73657 */
73658 SQLITE_PRIVATE Expr *sqlite3Expr(
73659   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
73660   int op,                 /* Expression opcode */
73661   const char *zToken      /* Token argument.  Might be NULL */
73662 ){
73663   Token x;
73664   x.z = zToken;
73665   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
73666   return sqlite3ExprAlloc(db, op, &x, 0);
73667 }
73668
73669 /*
73670 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
73671 **
73672 ** If pRoot==NULL that means that a memory allocation error has occurred.
73673 ** In that case, delete the subtrees pLeft and pRight.
73674 */
73675 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
73676   sqlite3 *db,
73677   Expr *pRoot,
73678   Expr *pLeft,
73679   Expr *pRight
73680 ){
73681   if( pRoot==0 ){
73682     assert( db->mallocFailed );
73683     sqlite3ExprDelete(db, pLeft);
73684     sqlite3ExprDelete(db, pRight);
73685   }else{
73686     if( pRight ){
73687       pRoot->pRight = pRight;
73688       if( pRight->flags & EP_ExpCollate ){
73689         pRoot->flags |= EP_ExpCollate;
73690         pRoot->pColl = pRight->pColl;
73691       }
73692     }
73693     if( pLeft ){
73694       pRoot->pLeft = pLeft;
73695       if( pLeft->flags & EP_ExpCollate ){
73696         pRoot->flags |= EP_ExpCollate;
73697         pRoot->pColl = pLeft->pColl;
73698       }
73699     }
73700     exprSetHeight(pRoot);
73701   }
73702 }
73703
73704 /*
73705 ** Allocate a Expr node which joins as many as two subtrees.
73706 **
73707 ** One or both of the subtrees can be NULL.  Return a pointer to the new
73708 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
73709 ** free the subtrees and return NULL.
73710 */
73711 SQLITE_PRIVATE Expr *sqlite3PExpr(
73712   Parse *pParse,          /* Parsing context */
73713   int op,                 /* Expression opcode */
73714   Expr *pLeft,            /* Left operand */
73715   Expr *pRight,           /* Right operand */
73716   const Token *pToken     /* Argument token */
73717 ){
73718   Expr *p;
73719   if( op==TK_AND && pLeft && pRight ){
73720     /* Take advantage of short-circuit false optimization for AND */
73721     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
73722   }else{
73723     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
73724     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
73725   }
73726   if( p ) {
73727     sqlite3ExprCheckHeight(pParse, p->nHeight);
73728   }
73729   return p;
73730 }
73731
73732 /*
73733 ** Return 1 if an expression must be FALSE in all cases and 0 if the
73734 ** expression might be true.  This is an optimization.  If is OK to
73735 ** return 0 here even if the expression really is always false (a 
73736 ** false negative).  But it is a bug to return 1 if the expression
73737 ** might be true in some rare circumstances (a false positive.)
73738 **
73739 ** Note that if the expression is part of conditional for a
73740 ** LEFT JOIN, then we cannot determine at compile-time whether or not
73741 ** is it true or false, so always return 0.
73742 */
73743 static int exprAlwaysFalse(Expr *p){
73744   int v = 0;
73745   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
73746   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
73747   return v==0;
73748 }
73749
73750 /*
73751 ** Join two expressions using an AND operator.  If either expression is
73752 ** NULL, then just return the other expression.
73753 **
73754 ** If one side or the other of the AND is known to be false, then instead
73755 ** of returning an AND expression, just return a constant expression with
73756 ** a value of false.
73757 */
73758 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
73759   if( pLeft==0 ){
73760     return pRight;
73761   }else if( pRight==0 ){
73762     return pLeft;
73763   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
73764     sqlite3ExprDelete(db, pLeft);
73765     sqlite3ExprDelete(db, pRight);
73766     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
73767   }else{
73768     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
73769     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
73770     return pNew;
73771   }
73772 }
73773
73774 /*
73775 ** Construct a new expression node for a function with multiple
73776 ** arguments.
73777 */
73778 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
73779   Expr *pNew;
73780   sqlite3 *db = pParse->db;
73781   assert( pToken );
73782   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
73783   if( pNew==0 ){
73784     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
73785     return 0;
73786   }
73787   pNew->x.pList = pList;
73788   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
73789   sqlite3ExprSetHeight(pParse, pNew);
73790   return pNew;
73791 }
73792
73793 /*
73794 ** Assign a variable number to an expression that encodes a wildcard
73795 ** in the original SQL statement.  
73796 **
73797 ** Wildcards consisting of a single "?" are assigned the next sequential
73798 ** variable number.
73799 **
73800 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
73801 ** sure "nnn" is not too be to avoid a denial of service attack when
73802 ** the SQL statement comes from an external source.
73803 **
73804 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
73805 ** as the previous instance of the same wildcard.  Or if this is the first
73806 ** instance of the wildcard, the next sequenial variable number is
73807 ** assigned.
73808 */
73809 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
73810   sqlite3 *db = pParse->db;
73811   const char *z;
73812
73813   if( pExpr==0 ) return;
73814   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
73815   z = pExpr->u.zToken;
73816   assert( z!=0 );
73817   assert( z[0]!=0 );
73818   if( z[1]==0 ){
73819     /* Wildcard of the form "?".  Assign the next variable number */
73820     assert( z[0]=='?' );
73821     pExpr->iColumn = (ynVar)(++pParse->nVar);
73822   }else{
73823     ynVar x = 0;
73824     u32 n = sqlite3Strlen30(z);
73825     if( z[0]=='?' ){
73826       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
73827       ** use it as the variable number */
73828       i64 i;
73829       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
73830       pExpr->iColumn = x = (ynVar)i;
73831       testcase( i==0 );
73832       testcase( i==1 );
73833       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
73834       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
73835       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73836         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
73837             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
73838         x = 0;
73839       }
73840       if( i>pParse->nVar ){
73841         pParse->nVar = (int)i;
73842       }
73843     }else{
73844       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
73845       ** number as the prior appearance of the same name, or if the name
73846       ** has never appeared before, reuse the same variable number
73847       */
73848       ynVar i;
73849       for(i=0; i<pParse->nzVar; i++){
73850         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
73851           pExpr->iColumn = x = (ynVar)i+1;
73852           break;
73853         }
73854       }
73855       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
73856     }
73857     if( x>0 ){
73858       if( x>pParse->nzVar ){
73859         char **a;
73860         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
73861         if( a==0 ) return;  /* Error reported through db->mallocFailed */
73862         pParse->azVar = a;
73863         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
73864         pParse->nzVar = x;
73865       }
73866       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
73867         sqlite3DbFree(db, pParse->azVar[x-1]);
73868         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
73869       }
73870     }
73871   } 
73872   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73873     sqlite3ErrorMsg(pParse, "too many SQL variables");
73874   }
73875 }
73876
73877 /*
73878 ** Recursively delete an expression tree.
73879 */
73880 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
73881   if( p==0 ) return;
73882   /* Sanity check: Assert that the IntValue is non-negative if it exists */
73883   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
73884   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
73885     sqlite3ExprDelete(db, p->pLeft);
73886     sqlite3ExprDelete(db, p->pRight);
73887     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
73888       sqlite3DbFree(db, p->u.zToken);
73889     }
73890     if( ExprHasProperty(p, EP_xIsSelect) ){
73891       sqlite3SelectDelete(db, p->x.pSelect);
73892     }else{
73893       sqlite3ExprListDelete(db, p->x.pList);
73894     }
73895   }
73896   if( !ExprHasProperty(p, EP_Static) ){
73897     sqlite3DbFree(db, p);
73898   }
73899 }
73900
73901 /*
73902 ** Return the number of bytes allocated for the expression structure 
73903 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
73904 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
73905 */
73906 static int exprStructSize(Expr *p){
73907   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
73908   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
73909   return EXPR_FULLSIZE;
73910 }
73911
73912 /*
73913 ** The dupedExpr*Size() routines each return the number of bytes required
73914 ** to store a copy of an expression or expression tree.  They differ in
73915 ** how much of the tree is measured.
73916 **
73917 **     dupedExprStructSize()     Size of only the Expr structure 
73918 **     dupedExprNodeSize()       Size of Expr + space for token
73919 **     dupedExprSize()           Expr + token + subtree components
73920 **
73921 ***************************************************************************
73922 **
73923 ** The dupedExprStructSize() function returns two values OR-ed together:  
73924 ** (1) the space required for a copy of the Expr structure only and 
73925 ** (2) the EP_xxx flags that indicate what the structure size should be.
73926 ** The return values is always one of:
73927 **
73928 **      EXPR_FULLSIZE
73929 **      EXPR_REDUCEDSIZE   | EP_Reduced
73930 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
73931 **
73932 ** The size of the structure can be found by masking the return value
73933 ** of this routine with 0xfff.  The flags can be found by masking the
73934 ** return value with EP_Reduced|EP_TokenOnly.
73935 **
73936 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
73937 ** (unreduced) Expr objects as they or originally constructed by the parser.
73938 ** During expression analysis, extra information is computed and moved into
73939 ** later parts of teh Expr object and that extra information might get chopped
73940 ** off if the expression is reduced.  Note also that it does not work to
73941 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
73942 ** to reduce a pristine expression tree from the parser.  The implementation
73943 ** of dupedExprStructSize() contain multiple assert() statements that attempt
73944 ** to enforce this constraint.
73945 */
73946 static int dupedExprStructSize(Expr *p, int flags){
73947   int nSize;
73948   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
73949   if( 0==(flags&EXPRDUP_REDUCE) ){
73950     nSize = EXPR_FULLSIZE;
73951   }else{
73952     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
73953     assert( !ExprHasProperty(p, EP_FromJoin) ); 
73954     assert( (p->flags2 & EP2_MallocedToken)==0 );
73955     assert( (p->flags2 & EP2_Irreducible)==0 );
73956     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
73957       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
73958     }else{
73959       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
73960     }
73961   }
73962   return nSize;
73963 }
73964
73965 /*
73966 ** This function returns the space in bytes required to store the copy 
73967 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
73968 ** string is defined.)
73969 */
73970 static int dupedExprNodeSize(Expr *p, int flags){
73971   int nByte = dupedExprStructSize(p, flags) & 0xfff;
73972   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
73973     nByte += sqlite3Strlen30(p->u.zToken)+1;
73974   }
73975   return ROUND8(nByte);
73976 }
73977
73978 /*
73979 ** Return the number of bytes required to create a duplicate of the 
73980 ** expression passed as the first argument. The second argument is a
73981 ** mask containing EXPRDUP_XXX flags.
73982 **
73983 ** The value returned includes space to create a copy of the Expr struct
73984 ** itself and the buffer referred to by Expr.u.zToken, if any.
73985 **
73986 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
73987 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
73988 ** and Expr.pRight variables (but not for any structures pointed to or 
73989 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
73990 */
73991 static int dupedExprSize(Expr *p, int flags){
73992   int nByte = 0;
73993   if( p ){
73994     nByte = dupedExprNodeSize(p, flags);
73995     if( flags&EXPRDUP_REDUCE ){
73996       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
73997     }
73998   }
73999   return nByte;
74000 }
74001
74002 /*
74003 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
74004 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
74005 ** to store the copy of expression p, the copies of p->u.zToken
74006 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
74007 ** if any. Before returning, *pzBuffer is set to the first byte passed the
74008 ** portion of the buffer copied into by this function.
74009 */
74010 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
74011   Expr *pNew = 0;                      /* Value to return */
74012   if( p ){
74013     const int isReduced = (flags&EXPRDUP_REDUCE);
74014     u8 *zAlloc;
74015     u32 staticFlag = 0;
74016
74017     assert( pzBuffer==0 || isReduced );
74018
74019     /* Figure out where to write the new Expr structure. */
74020     if( pzBuffer ){
74021       zAlloc = *pzBuffer;
74022       staticFlag = EP_Static;
74023     }else{
74024       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
74025     }
74026     pNew = (Expr *)zAlloc;
74027
74028     if( pNew ){
74029       /* Set nNewSize to the size allocated for the structure pointed to
74030       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
74031       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
74032       ** by the copy of the p->u.zToken string (if any).
74033       */
74034       const unsigned nStructSize = dupedExprStructSize(p, flags);
74035       const int nNewSize = nStructSize & 0xfff;
74036       int nToken;
74037       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74038         nToken = sqlite3Strlen30(p->u.zToken) + 1;
74039       }else{
74040         nToken = 0;
74041       }
74042       if( isReduced ){
74043         assert( ExprHasProperty(p, EP_Reduced)==0 );
74044         memcpy(zAlloc, p, nNewSize);
74045       }else{
74046         int nSize = exprStructSize(p);
74047         memcpy(zAlloc, p, nSize);
74048         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
74049       }
74050
74051       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
74052       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
74053       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
74054       pNew->flags |= staticFlag;
74055
74056       /* Copy the p->u.zToken string, if any. */
74057       if( nToken ){
74058         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
74059         memcpy(zToken, p->u.zToken, nToken);
74060       }
74061
74062       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
74063         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
74064         if( ExprHasProperty(p, EP_xIsSelect) ){
74065           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
74066         }else{
74067           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
74068         }
74069       }
74070
74071       /* Fill in pNew->pLeft and pNew->pRight. */
74072       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
74073         zAlloc += dupedExprNodeSize(p, flags);
74074         if( ExprHasProperty(pNew, EP_Reduced) ){
74075           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
74076           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
74077         }
74078         if( pzBuffer ){
74079           *pzBuffer = zAlloc;
74080         }
74081       }else{
74082         pNew->flags2 = 0;
74083         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74084           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
74085           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
74086         }
74087       }
74088
74089     }
74090   }
74091   return pNew;
74092 }
74093
74094 /*
74095 ** The following group of routines make deep copies of expressions,
74096 ** expression lists, ID lists, and select statements.  The copies can
74097 ** be deleted (by being passed to their respective ...Delete() routines)
74098 ** without effecting the originals.
74099 **
74100 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
74101 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
74102 ** by subsequent calls to sqlite*ListAppend() routines.
74103 **
74104 ** Any tables that the SrcList might point to are not duplicated.
74105 **
74106 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
74107 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
74108 ** truncated version of the usual Expr structure that will be stored as
74109 ** part of the in-memory representation of the database schema.
74110 */
74111 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
74112   return exprDup(db, p, flags, 0);
74113 }
74114 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
74115   ExprList *pNew;
74116   struct ExprList_item *pItem, *pOldItem;
74117   int i;
74118   if( p==0 ) return 0;
74119   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74120   if( pNew==0 ) return 0;
74121   pNew->iECursor = 0;
74122   pNew->nExpr = i = p->nExpr;
74123   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
74124   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
74125   if( pItem==0 ){
74126     sqlite3DbFree(db, pNew);
74127     return 0;
74128   } 
74129   pOldItem = p->a;
74130   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
74131     Expr *pOldExpr = pOldItem->pExpr;
74132     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
74133     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74134     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
74135     pItem->sortOrder = pOldItem->sortOrder;
74136     pItem->done = 0;
74137     pItem->iOrderByCol = pOldItem->iOrderByCol;
74138     pItem->iAlias = pOldItem->iAlias;
74139   }
74140   return pNew;
74141 }
74142
74143 /*
74144 ** If cursors, triggers, views and subqueries are all omitted from
74145 ** the build, then none of the following routines, except for 
74146 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
74147 ** called with a NULL argument.
74148 */
74149 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
74150  || !defined(SQLITE_OMIT_SUBQUERY)
74151 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
74152   SrcList *pNew;
74153   int i;
74154   int nByte;
74155   if( p==0 ) return 0;
74156   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
74157   pNew = sqlite3DbMallocRaw(db, nByte );
74158   if( pNew==0 ) return 0;
74159   pNew->nSrc = pNew->nAlloc = p->nSrc;
74160   for(i=0; i<p->nSrc; i++){
74161     struct SrcList_item *pNewItem = &pNew->a[i];
74162     struct SrcList_item *pOldItem = &p->a[i];
74163     Table *pTab;
74164     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
74165     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74166     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
74167     pNewItem->jointype = pOldItem->jointype;
74168     pNewItem->iCursor = pOldItem->iCursor;
74169     pNewItem->addrFillSub = pOldItem->addrFillSub;
74170     pNewItem->regReturn = pOldItem->regReturn;
74171     pNewItem->isCorrelated = pOldItem->isCorrelated;
74172     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
74173     pNewItem->notIndexed = pOldItem->notIndexed;
74174     pNewItem->pIndex = pOldItem->pIndex;
74175     pTab = pNewItem->pTab = pOldItem->pTab;
74176     if( pTab ){
74177       pTab->nRef++;
74178     }
74179     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
74180     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
74181     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
74182     pNewItem->colUsed = pOldItem->colUsed;
74183   }
74184   return pNew;
74185 }
74186 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
74187   IdList *pNew;
74188   int i;
74189   if( p==0 ) return 0;
74190   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74191   if( pNew==0 ) return 0;
74192   pNew->nId = p->nId;
74193   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
74194   if( pNew->a==0 ){
74195     sqlite3DbFree(db, pNew);
74196     return 0;
74197   }
74198   /* Note that because the size of the allocation for p->a[] is not
74199   ** necessarily a power of two, sqlite3IdListAppend() may not be called
74200   ** on the duplicate created by this function. */
74201   for(i=0; i<p->nId; i++){
74202     struct IdList_item *pNewItem = &pNew->a[i];
74203     struct IdList_item *pOldItem = &p->a[i];
74204     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74205     pNewItem->idx = pOldItem->idx;
74206   }
74207   return pNew;
74208 }
74209 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74210   Select *pNew, *pPrior;
74211   if( p==0 ) return 0;
74212   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
74213   if( pNew==0 ) return 0;
74214   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
74215   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
74216   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
74217   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
74218   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
74219   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
74220   pNew->op = p->op;
74221   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
74222   if( pPrior ) pPrior->pNext = pNew;
74223   pNew->pNext = 0;
74224   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
74225   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
74226   pNew->iLimit = 0;
74227   pNew->iOffset = 0;
74228   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
74229   pNew->pRightmost = 0;
74230   pNew->addrOpenEphm[0] = -1;
74231   pNew->addrOpenEphm[1] = -1;
74232   pNew->addrOpenEphm[2] = -1;
74233   return pNew;
74234 }
74235 #else
74236 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74237   assert( p==0 );
74238   return 0;
74239 }
74240 #endif
74241
74242
74243 /*
74244 ** Add a new element to the end of an expression list.  If pList is
74245 ** initially NULL, then create a new expression list.
74246 **
74247 ** If a memory allocation error occurs, the entire list is freed and
74248 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
74249 ** that the new entry was successfully appended.
74250 */
74251 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
74252   Parse *pParse,          /* Parsing context */
74253   ExprList *pList,        /* List to which to append. Might be NULL */
74254   Expr *pExpr             /* Expression to be appended. Might be NULL */
74255 ){
74256   sqlite3 *db = pParse->db;
74257   if( pList==0 ){
74258     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
74259     if( pList==0 ){
74260       goto no_mem;
74261     }
74262     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
74263     if( pList->a==0 ) goto no_mem;
74264   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
74265     struct ExprList_item *a;
74266     assert( pList->nExpr>0 );
74267     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
74268     if( a==0 ){
74269       goto no_mem;
74270     }
74271     pList->a = a;
74272   }
74273   assert( pList->a!=0 );
74274   if( 1 ){
74275     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
74276     memset(pItem, 0, sizeof(*pItem));
74277     pItem->pExpr = pExpr;
74278   }
74279   return pList;
74280
74281 no_mem:     
74282   /* Avoid leaking memory if malloc has failed. */
74283   sqlite3ExprDelete(db, pExpr);
74284   sqlite3ExprListDelete(db, pList);
74285   return 0;
74286 }
74287
74288 /*
74289 ** Set the ExprList.a[].zName element of the most recently added item
74290 ** on the expression list.
74291 **
74292 ** pList might be NULL following an OOM error.  But pName should never be
74293 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74294 ** is set.
74295 */
74296 SQLITE_PRIVATE void sqlite3ExprListSetName(
74297   Parse *pParse,          /* Parsing context */
74298   ExprList *pList,        /* List to which to add the span. */
74299   Token *pName,           /* Name to be added */
74300   int dequote             /* True to cause the name to be dequoted */
74301 ){
74302   assert( pList!=0 || pParse->db->mallocFailed!=0 );
74303   if( pList ){
74304     struct ExprList_item *pItem;
74305     assert( pList->nExpr>0 );
74306     pItem = &pList->a[pList->nExpr-1];
74307     assert( pItem->zName==0 );
74308     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
74309     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
74310   }
74311 }
74312
74313 /*
74314 ** Set the ExprList.a[].zSpan element of the most recently added item
74315 ** on the expression list.
74316 **
74317 ** pList might be NULL following an OOM error.  But pSpan should never be
74318 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74319 ** is set.
74320 */
74321 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
74322   Parse *pParse,          /* Parsing context */
74323   ExprList *pList,        /* List to which to add the span. */
74324   ExprSpan *pSpan         /* The span to be added */
74325 ){
74326   sqlite3 *db = pParse->db;
74327   assert( pList!=0 || db->mallocFailed!=0 );
74328   if( pList ){
74329     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
74330     assert( pList->nExpr>0 );
74331     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
74332     sqlite3DbFree(db, pItem->zSpan);
74333     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
74334                                     (int)(pSpan->zEnd - pSpan->zStart));
74335   }
74336 }
74337
74338 /*
74339 ** If the expression list pEList contains more than iLimit elements,
74340 ** leave an error message in pParse.
74341 */
74342 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
74343   Parse *pParse,
74344   ExprList *pEList,
74345   const char *zObject
74346 ){
74347   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
74348   testcase( pEList && pEList->nExpr==mx );
74349   testcase( pEList && pEList->nExpr==mx+1 );
74350   if( pEList && pEList->nExpr>mx ){
74351     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
74352   }
74353 }
74354
74355 /*
74356 ** Delete an entire expression list.
74357 */
74358 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
74359   int i;
74360   struct ExprList_item *pItem;
74361   if( pList==0 ) return;
74362   assert( pList->a!=0 || pList->nExpr==0 );
74363   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74364     sqlite3ExprDelete(db, pItem->pExpr);
74365     sqlite3DbFree(db, pItem->zName);
74366     sqlite3DbFree(db, pItem->zSpan);
74367   }
74368   sqlite3DbFree(db, pList->a);
74369   sqlite3DbFree(db, pList);
74370 }
74371
74372 /*
74373 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
74374 ** to an integer.  These routines are checking an expression to see
74375 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
74376 ** not constant.
74377 **
74378 ** These callback routines are used to implement the following:
74379 **
74380 **     sqlite3ExprIsConstant()
74381 **     sqlite3ExprIsConstantNotJoin()
74382 **     sqlite3ExprIsConstantOrFunction()
74383 **
74384 */
74385 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
74386
74387   /* If pWalker->u.i is 3 then any term of the expression that comes from
74388   ** the ON or USING clauses of a join disqualifies the expression
74389   ** from being considered constant. */
74390   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
74391     pWalker->u.i = 0;
74392     return WRC_Abort;
74393   }
74394
74395   switch( pExpr->op ){
74396     /* Consider functions to be constant if all their arguments are constant
74397     ** and pWalker->u.i==2 */
74398     case TK_FUNCTION:
74399       if( pWalker->u.i==2 ) return 0;
74400       /* Fall through */
74401     case TK_ID:
74402     case TK_COLUMN:
74403     case TK_AGG_FUNCTION:
74404     case TK_AGG_COLUMN:
74405       testcase( pExpr->op==TK_ID );
74406       testcase( pExpr->op==TK_COLUMN );
74407       testcase( pExpr->op==TK_AGG_FUNCTION );
74408       testcase( pExpr->op==TK_AGG_COLUMN );
74409       pWalker->u.i = 0;
74410       return WRC_Abort;
74411     default:
74412       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
74413       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
74414       return WRC_Continue;
74415   }
74416 }
74417 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
74418   UNUSED_PARAMETER(NotUsed);
74419   pWalker->u.i = 0;
74420   return WRC_Abort;
74421 }
74422 static int exprIsConst(Expr *p, int initFlag){
74423   Walker w;
74424   w.u.i = initFlag;
74425   w.xExprCallback = exprNodeIsConstant;
74426   w.xSelectCallback = selectNodeIsConstant;
74427   sqlite3WalkExpr(&w, p);
74428   return w.u.i;
74429 }
74430
74431 /*
74432 ** Walk an expression tree.  Return 1 if the expression is constant
74433 ** and 0 if it involves variables or function calls.
74434 **
74435 ** For the purposes of this function, a double-quoted string (ex: "abc")
74436 ** is considered a variable but a single-quoted string (ex: 'abc') is
74437 ** a constant.
74438 */
74439 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
74440   return exprIsConst(p, 1);
74441 }
74442
74443 /*
74444 ** Walk an expression tree.  Return 1 if the expression is constant
74445 ** that does no originate from the ON or USING clauses of a join.
74446 ** Return 0 if it involves variables or function calls or terms from
74447 ** an ON or USING clause.
74448 */
74449 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
74450   return exprIsConst(p, 3);
74451 }
74452
74453 /*
74454 ** Walk an expression tree.  Return 1 if the expression is constant
74455 ** or a function call with constant arguments.  Return and 0 if there
74456 ** are any variables.
74457 **
74458 ** For the purposes of this function, a double-quoted string (ex: "abc")
74459 ** is considered a variable but a single-quoted string (ex: 'abc') is
74460 ** a constant.
74461 */
74462 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
74463   return exprIsConst(p, 2);
74464 }
74465
74466 /*
74467 ** If the expression p codes a constant integer that is small enough
74468 ** to fit in a 32-bit integer, return 1 and put the value of the integer
74469 ** in *pValue.  If the expression is not an integer or if it is too big
74470 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
74471 */
74472 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
74473   int rc = 0;
74474
74475   /* If an expression is an integer literal that fits in a signed 32-bit
74476   ** integer, then the EP_IntValue flag will have already been set */
74477   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
74478            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
74479
74480   if( p->flags & EP_IntValue ){
74481     *pValue = p->u.iValue;
74482     return 1;
74483   }
74484   switch( p->op ){
74485     case TK_UPLUS: {
74486       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
74487       break;
74488     }
74489     case TK_UMINUS: {
74490       int v;
74491       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
74492         *pValue = -v;
74493         rc = 1;
74494       }
74495       break;
74496     }
74497     default: break;
74498   }
74499   return rc;
74500 }
74501
74502 /*
74503 ** Return FALSE if there is no chance that the expression can be NULL.
74504 **
74505 ** If the expression might be NULL or if the expression is too complex
74506 ** to tell return TRUE.  
74507 **
74508 ** This routine is used as an optimization, to skip OP_IsNull opcodes
74509 ** when we know that a value cannot be NULL.  Hence, a false positive
74510 ** (returning TRUE when in fact the expression can never be NULL) might
74511 ** be a small performance hit but is otherwise harmless.  On the other
74512 ** hand, a false negative (returning FALSE when the result could be NULL)
74513 ** will likely result in an incorrect answer.  So when in doubt, return
74514 ** TRUE.
74515 */
74516 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
74517   u8 op;
74518   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74519   op = p->op;
74520   if( op==TK_REGISTER ) op = p->op2;
74521   switch( op ){
74522     case TK_INTEGER:
74523     case TK_STRING:
74524     case TK_FLOAT:
74525     case TK_BLOB:
74526       return 0;
74527     default:
74528       return 1;
74529   }
74530 }
74531
74532 /*
74533 ** Generate an OP_IsNull instruction that tests register iReg and jumps
74534 ** to location iDest if the value in iReg is NULL.  The value in iReg 
74535 ** was computed by pExpr.  If we can look at pExpr at compile-time and
74536 ** determine that it can never generate a NULL, then the OP_IsNull operation
74537 ** can be omitted.
74538 */
74539 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
74540   Vdbe *v,            /* The VDBE under construction */
74541   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
74542   int iReg,           /* Test the value in this register for NULL */
74543   int iDest           /* Jump here if the value is null */
74544 ){
74545   if( sqlite3ExprCanBeNull(pExpr) ){
74546     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
74547   }
74548 }
74549
74550 /*
74551 ** Return TRUE if the given expression is a constant which would be
74552 ** unchanged by OP_Affinity with the affinity given in the second
74553 ** argument.
74554 **
74555 ** This routine is used to determine if the OP_Affinity operation
74556 ** can be omitted.  When in doubt return FALSE.  A false negative
74557 ** is harmless.  A false positive, however, can result in the wrong
74558 ** answer.
74559 */
74560 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
74561   u8 op;
74562   if( aff==SQLITE_AFF_NONE ) return 1;
74563   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74564   op = p->op;
74565   if( op==TK_REGISTER ) op = p->op2;
74566   switch( op ){
74567     case TK_INTEGER: {
74568       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
74569     }
74570     case TK_FLOAT: {
74571       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
74572     }
74573     case TK_STRING: {
74574       return aff==SQLITE_AFF_TEXT;
74575     }
74576     case TK_BLOB: {
74577       return 1;
74578     }
74579     case TK_COLUMN: {
74580       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
74581       return p->iColumn<0
74582           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
74583     }
74584     default: {
74585       return 0;
74586     }
74587   }
74588 }
74589
74590 /*
74591 ** Return TRUE if the given string is a row-id column name.
74592 */
74593 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
74594   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
74595   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
74596   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
74597   return 0;
74598 }
74599
74600 /*
74601 ** Return true if we are able to the IN operator optimization on a
74602 ** query of the form
74603 **
74604 **       x IN (SELECT ...)
74605 **
74606 ** Where the SELECT... clause is as specified by the parameter to this
74607 ** routine.
74608 **
74609 ** The Select object passed in has already been preprocessed and no
74610 ** errors have been found.
74611 */
74612 #ifndef SQLITE_OMIT_SUBQUERY
74613 static int isCandidateForInOpt(Select *p){
74614   SrcList *pSrc;
74615   ExprList *pEList;
74616   Table *pTab;
74617   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
74618   if( p->pPrior ) return 0;              /* Not a compound SELECT */
74619   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
74620     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
74621     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
74622     return 0; /* No DISTINCT keyword and no aggregate functions */
74623   }
74624   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
74625   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
74626   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
74627   if( p->pWhere ) return 0;              /* Has no WHERE clause */
74628   pSrc = p->pSrc;
74629   assert( pSrc!=0 );
74630   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
74631   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
74632   pTab = pSrc->a[0].pTab;
74633   if( NEVER(pTab==0) ) return 0;
74634   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
74635   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
74636   pEList = p->pEList;
74637   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
74638   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
74639   return 1;
74640 }
74641 #endif /* SQLITE_OMIT_SUBQUERY */
74642
74643 /*
74644 ** Code an OP_Once instruction and allocate space for its flag. Return the 
74645 ** address of the new instruction.
74646 */
74647 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
74648   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
74649   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
74650 }
74651
74652 /*
74653 ** This function is used by the implementation of the IN (...) operator.
74654 ** It's job is to find or create a b-tree structure that may be used
74655 ** either to test for membership of the (...) set or to iterate through
74656 ** its members, skipping duplicates.
74657 **
74658 ** The index of the cursor opened on the b-tree (database table, database index 
74659 ** or ephermal table) is stored in pX->iTable before this function returns.
74660 ** The returned value of this function indicates the b-tree type, as follows:
74661 **
74662 **   IN_INDEX_ROWID - The cursor was opened on a database table.
74663 **   IN_INDEX_INDEX - The cursor was opened on a database index.
74664 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
74665 **                    populated epheremal table.
74666 **
74667 ** An existing b-tree may only be used if the SELECT is of the simple
74668 ** form:
74669 **
74670 **     SELECT <column> FROM <table>
74671 **
74672 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
74673 ** through the set members, skipping any duplicates. In this case an
74674 ** epheremal table must be used unless the selected <column> is guaranteed
74675 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
74676 ** has a UNIQUE constraint or UNIQUE index.
74677 **
74678 ** If the prNotFound parameter is not 0, then the b-tree will be used 
74679 ** for fast set membership tests. In this case an epheremal table must 
74680 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
74681 ** be found with <column> as its left-most column.
74682 **
74683 ** When the b-tree is being used for membership tests, the calling function
74684 ** needs to know whether or not the structure contains an SQL NULL 
74685 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
74686 ** If there is any chance that the (...) might contain a NULL value at
74687 ** runtime, then a register is allocated and the register number written
74688 ** to *prNotFound. If there is no chance that the (...) contains a
74689 ** NULL value, then *prNotFound is left unchanged.
74690 **
74691 ** If a register is allocated and its location stored in *prNotFound, then
74692 ** its initial value is NULL.  If the (...) does not remain constant
74693 ** for the duration of the query (i.e. the SELECT within the (...)
74694 ** is a correlated subquery) then the value of the allocated register is
74695 ** reset to NULL each time the subquery is rerun. This allows the
74696 ** caller to use vdbe code equivalent to the following:
74697 **
74698 **   if( register==NULL ){
74699 **     has_null = <test if data structure contains null>
74700 **     register = 1
74701 **   }
74702 **
74703 ** in order to avoid running the <test if data structure contains null>
74704 ** test more often than is necessary.
74705 */
74706 #ifndef SQLITE_OMIT_SUBQUERY
74707 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
74708   Select *p;                            /* SELECT to the right of IN operator */
74709   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
74710   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
74711   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
74712   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
74713
74714   assert( pX->op==TK_IN );
74715
74716   /* Check to see if an existing table or index can be used to
74717   ** satisfy the query.  This is preferable to generating a new 
74718   ** ephemeral table.
74719   */
74720   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
74721   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
74722     sqlite3 *db = pParse->db;              /* Database connection */
74723     Table *pTab;                           /* Table <table>. */
74724     Expr *pExpr;                           /* Expression <column> */
74725     int iCol;                              /* Index of column <column> */
74726     int iDb;                               /* Database idx for pTab */
74727
74728     assert( p );                        /* Because of isCandidateForInOpt(p) */
74729     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
74730     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
74731     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
74732     pTab = p->pSrc->a[0].pTab;
74733     pExpr = p->pEList->a[0].pExpr;
74734     iCol = pExpr->iColumn;
74735    
74736     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
74737     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74738     sqlite3CodeVerifySchema(pParse, iDb);
74739     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
74740
74741     /* This function is only called from two places. In both cases the vdbe
74742     ** has already been allocated. So assume sqlite3GetVdbe() is always
74743     ** successful here.
74744     */
74745     assert(v);
74746     if( iCol<0 ){
74747       int iAddr;
74748
74749       iAddr = sqlite3CodeOnce(pParse);
74750
74751       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
74752       eType = IN_INDEX_ROWID;
74753
74754       sqlite3VdbeJumpHere(v, iAddr);
74755     }else{
74756       Index *pIdx;                         /* Iterator variable */
74757
74758       /* The collation sequence used by the comparison. If an index is to
74759       ** be used in place of a temp-table, it must be ordered according
74760       ** to this collation sequence.  */
74761       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
74762
74763       /* Check that the affinity that will be used to perform the 
74764       ** comparison is the same as the affinity of the column. If
74765       ** it is not, it is not possible to use any index.
74766       */
74767       char aff = comparisonAffinity(pX);
74768       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
74769
74770       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
74771         if( (pIdx->aiColumn[0]==iCol)
74772          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
74773          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
74774         ){
74775           int iAddr;
74776           char *pKey;
74777   
74778           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
74779           iAddr = sqlite3CodeOnce(pParse);
74780   
74781           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
74782                                pKey,P4_KEYINFO_HANDOFF);
74783           VdbeComment((v, "%s", pIdx->zName));
74784           eType = IN_INDEX_INDEX;
74785
74786           sqlite3VdbeJumpHere(v, iAddr);
74787           if( prNotFound && !pTab->aCol[iCol].notNull ){
74788             *prNotFound = ++pParse->nMem;
74789             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
74790           }
74791         }
74792       }
74793     }
74794   }
74795
74796   if( eType==0 ){
74797     /* Could not found an existing table or index to use as the RHS b-tree.
74798     ** We will have to generate an ephemeral table to do the job.
74799     */
74800     double savedNQueryLoop = pParse->nQueryLoop;
74801     int rMayHaveNull = 0;
74802     eType = IN_INDEX_EPH;
74803     if( prNotFound ){
74804       *prNotFound = rMayHaveNull = ++pParse->nMem;
74805       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
74806     }else{
74807       testcase( pParse->nQueryLoop>(double)1 );
74808       pParse->nQueryLoop = (double)1;
74809       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
74810         eType = IN_INDEX_ROWID;
74811       }
74812     }
74813     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
74814     pParse->nQueryLoop = savedNQueryLoop;
74815   }else{
74816     pX->iTable = iTab;
74817   }
74818   return eType;
74819 }
74820 #endif
74821
74822 /*
74823 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
74824 ** or IN operators.  Examples:
74825 **
74826 **     (SELECT a FROM b)          -- subquery
74827 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
74828 **     x IN (4,5,11)              -- IN operator with list on right-hand side
74829 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
74830 **
74831 ** The pExpr parameter describes the expression that contains the IN
74832 ** operator or subquery.
74833 **
74834 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
74835 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
74836 ** to some integer key column of a table B-Tree. In this case, use an
74837 ** intkey B-Tree to store the set of IN(...) values instead of the usual
74838 ** (slower) variable length keys B-Tree.
74839 **
74840 ** If rMayHaveNull is non-zero, that means that the operation is an IN
74841 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
74842 ** Furthermore, the IN is in a WHERE clause and that we really want
74843 ** to iterate over the RHS of the IN operator in order to quickly locate
74844 ** all corresponding LHS elements.  All this routine does is initialize
74845 ** the register given by rMayHaveNull to NULL.  Calling routines will take
74846 ** care of changing this register value to non-NULL if the RHS is NULL-free.
74847 **
74848 ** If rMayHaveNull is zero, that means that the subquery is being used
74849 ** for membership testing only.  There is no need to initialize any
74850 ** registers to indicate the presense or absence of NULLs on the RHS.
74851 **
74852 ** For a SELECT or EXISTS operator, return the register that holds the
74853 ** result.  For IN operators or if an error occurs, the return value is 0.
74854 */
74855 #ifndef SQLITE_OMIT_SUBQUERY
74856 SQLITE_PRIVATE int sqlite3CodeSubselect(
74857   Parse *pParse,          /* Parsing context */
74858   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
74859   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
74860   int isRowid             /* If true, LHS of IN operator is a rowid */
74861 ){
74862   int testAddr = -1;                      /* One-time test address */
74863   int rReg = 0;                           /* Register storing resulting */
74864   Vdbe *v = sqlite3GetVdbe(pParse);
74865   if( NEVER(v==0) ) return 0;
74866   sqlite3ExprCachePush(pParse);
74867
74868   /* This code must be run in its entirety every time it is encountered
74869   ** if any of the following is true:
74870   **
74871   **    *  The right-hand side is a correlated subquery
74872   **    *  The right-hand side is an expression list containing variables
74873   **    *  We are inside a trigger
74874   **
74875   ** If all of the above are false, then we can run this code just once
74876   ** save the results, and reuse the same result on subsequent invocations.
74877   */
74878   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
74879     testAddr = sqlite3CodeOnce(pParse);
74880   }
74881
74882 #ifndef SQLITE_OMIT_EXPLAIN
74883   if( pParse->explain==2 ){
74884     char *zMsg = sqlite3MPrintf(
74885         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
74886         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
74887     );
74888     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
74889   }
74890 #endif
74891
74892   switch( pExpr->op ){
74893     case TK_IN: {
74894       char affinity;              /* Affinity of the LHS of the IN */
74895       KeyInfo keyInfo;            /* Keyinfo for the generated table */
74896       int addr;                   /* Address of OP_OpenEphemeral instruction */
74897       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
74898
74899       if( rMayHaveNull ){
74900         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
74901       }
74902
74903       affinity = sqlite3ExprAffinity(pLeft);
74904
74905       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
74906       ** expression it is handled the same way.  An ephemeral table is 
74907       ** filled with single-field index keys representing the results
74908       ** from the SELECT or the <exprlist>.
74909       **
74910       ** If the 'x' expression is a column value, or the SELECT...
74911       ** statement returns a column value, then the affinity of that
74912       ** column is used to build the index keys. If both 'x' and the
74913       ** SELECT... statement are columns, then numeric affinity is used
74914       ** if either column has NUMERIC or INTEGER affinity. If neither
74915       ** 'x' nor the SELECT... statement are columns, then numeric affinity
74916       ** is used.
74917       */
74918       pExpr->iTable = pParse->nTab++;
74919       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
74920       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
74921       memset(&keyInfo, 0, sizeof(keyInfo));
74922       keyInfo.nField = 1;
74923
74924       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74925         /* Case 1:     expr IN (SELECT ...)
74926         **
74927         ** Generate code to write the results of the select into the temporary
74928         ** table allocated and opened above.
74929         */
74930         SelectDest dest;
74931         ExprList *pEList;
74932
74933         assert( !isRowid );
74934         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
74935         dest.affSdst = (u8)affinity;
74936         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
74937         pExpr->x.pSelect->iLimit = 0;
74938         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
74939           return 0;
74940         }
74941         pEList = pExpr->x.pSelect->pEList;
74942         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
74943           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
74944               pEList->a[0].pExpr);
74945         }
74946       }else if( ALWAYS(pExpr->x.pList!=0) ){
74947         /* Case 2:     expr IN (exprlist)
74948         **
74949         ** For each expression, build an index key from the evaluation and
74950         ** store it in the temporary table. If <expr> is a column, then use
74951         ** that columns affinity when building index keys. If <expr> is not
74952         ** a column, use numeric affinity.
74953         */
74954         int i;
74955         ExprList *pList = pExpr->x.pList;
74956         struct ExprList_item *pItem;
74957         int r1, r2, r3;
74958
74959         if( !affinity ){
74960           affinity = SQLITE_AFF_NONE;
74961         }
74962         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
74963
74964         /* Loop through each expression in <exprlist>. */
74965         r1 = sqlite3GetTempReg(pParse);
74966         r2 = sqlite3GetTempReg(pParse);
74967         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
74968         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
74969           Expr *pE2 = pItem->pExpr;
74970           int iValToIns;
74971
74972           /* If the expression is not constant then we will need to
74973           ** disable the test that was generated above that makes sure
74974           ** this code only executes once.  Because for a non-constant
74975           ** expression we need to rerun this code each time.
74976           */
74977           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
74978             sqlite3VdbeChangeToNoop(v, testAddr);
74979             testAddr = -1;
74980           }
74981
74982           /* Evaluate the expression and insert it into the temp table */
74983           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
74984             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
74985           }else{
74986             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
74987             if( isRowid ){
74988               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
74989                                 sqlite3VdbeCurrentAddr(v)+2);
74990               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
74991             }else{
74992               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
74993               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
74994               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
74995             }
74996           }
74997         }
74998         sqlite3ReleaseTempReg(pParse, r1);
74999         sqlite3ReleaseTempReg(pParse, r2);
75000       }
75001       if( !isRowid ){
75002         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
75003       }
75004       break;
75005     }
75006
75007     case TK_EXISTS:
75008     case TK_SELECT:
75009     default: {
75010       /* If this has to be a scalar SELECT.  Generate code to put the
75011       ** value of this select in a memory cell and record the number
75012       ** of the memory cell in iColumn.  If this is an EXISTS, write
75013       ** an integer 0 (not exists) or 1 (exists) into a memory cell
75014       ** and record that memory cell in iColumn.
75015       */
75016       Select *pSel;                         /* SELECT statement to encode */
75017       SelectDest dest;                      /* How to deal with SELECt result */
75018
75019       testcase( pExpr->op==TK_EXISTS );
75020       testcase( pExpr->op==TK_SELECT );
75021       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
75022
75023       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
75024       pSel = pExpr->x.pSelect;
75025       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
75026       if( pExpr->op==TK_SELECT ){
75027         dest.eDest = SRT_Mem;
75028         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
75029         VdbeComment((v, "Init subquery result"));
75030       }else{
75031         dest.eDest = SRT_Exists;
75032         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
75033         VdbeComment((v, "Init EXISTS result"));
75034       }
75035       sqlite3ExprDelete(pParse->db, pSel->pLimit);
75036       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
75037                                   &sqlite3IntTokens[1]);
75038       pSel->iLimit = 0;
75039       if( sqlite3Select(pParse, pSel, &dest) ){
75040         return 0;
75041       }
75042       rReg = dest.iSDParm;
75043       ExprSetIrreducible(pExpr);
75044       break;
75045     }
75046   }
75047
75048   if( testAddr>=0 ){
75049     sqlite3VdbeJumpHere(v, testAddr);
75050   }
75051   sqlite3ExprCachePop(pParse, 1);
75052
75053   return rReg;
75054 }
75055 #endif /* SQLITE_OMIT_SUBQUERY */
75056
75057 #ifndef SQLITE_OMIT_SUBQUERY
75058 /*
75059 ** Generate code for an IN expression.
75060 **
75061 **      x IN (SELECT ...)
75062 **      x IN (value, value, ...)
75063 **
75064 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
75065 ** is an array of zero or more values.  The expression is true if the LHS is
75066 ** contained within the RHS.  The value of the expression is unknown (NULL)
75067 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
75068 ** RHS contains one or more NULL values.
75069 **
75070 ** This routine generates code will jump to destIfFalse if the LHS is not 
75071 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
75072 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
75073 ** within the RHS then fall through.
75074 */
75075 static void sqlite3ExprCodeIN(
75076   Parse *pParse,        /* Parsing and code generating context */
75077   Expr *pExpr,          /* The IN expression */
75078   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
75079   int destIfNull        /* Jump here if the results are unknown due to NULLs */
75080 ){
75081   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
75082   char affinity;        /* Comparison affinity to use */
75083   int eType;            /* Type of the RHS */
75084   int r1;               /* Temporary use register */
75085   Vdbe *v;              /* Statement under construction */
75086
75087   /* Compute the RHS.   After this step, the table with cursor
75088   ** pExpr->iTable will contains the values that make up the RHS.
75089   */
75090   v = pParse->pVdbe;
75091   assert( v!=0 );       /* OOM detected prior to this routine */
75092   VdbeNoopComment((v, "begin IN expr"));
75093   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
75094
75095   /* Figure out the affinity to use to create a key from the results
75096   ** of the expression. affinityStr stores a static string suitable for
75097   ** P4 of OP_MakeRecord.
75098   */
75099   affinity = comparisonAffinity(pExpr);
75100
75101   /* Code the LHS, the <expr> from "<expr> IN (...)".
75102   */
75103   sqlite3ExprCachePush(pParse);
75104   r1 = sqlite3GetTempReg(pParse);
75105   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
75106
75107   /* If the LHS is NULL, then the result is either false or NULL depending
75108   ** on whether the RHS is empty or not, respectively.
75109   */
75110   if( destIfNull==destIfFalse ){
75111     /* Shortcut for the common case where the false and NULL outcomes are
75112     ** the same. */
75113     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
75114   }else{
75115     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
75116     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
75117     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
75118     sqlite3VdbeJumpHere(v, addr1);
75119   }
75120
75121   if( eType==IN_INDEX_ROWID ){
75122     /* In this case, the RHS is the ROWID of table b-tree
75123     */
75124     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
75125     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
75126   }else{
75127     /* In this case, the RHS is an index b-tree.
75128     */
75129     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
75130
75131     /* If the set membership test fails, then the result of the 
75132     ** "x IN (...)" expression must be either 0 or NULL. If the set
75133     ** contains no NULL values, then the result is 0. If the set 
75134     ** contains one or more NULL values, then the result of the
75135     ** expression is also NULL.
75136     */
75137     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
75138       /* This branch runs if it is known at compile time that the RHS
75139       ** cannot contain NULL values. This happens as the result
75140       ** of a "NOT NULL" constraint in the database schema.
75141       **
75142       ** Also run this branch if NULL is equivalent to FALSE
75143       ** for this particular IN operator.
75144       */
75145       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
75146
75147     }else{
75148       /* In this branch, the RHS of the IN might contain a NULL and
75149       ** the presence of a NULL on the RHS makes a difference in the
75150       ** outcome.
75151       */
75152       int j1, j2, j3;
75153
75154       /* First check to see if the LHS is contained in the RHS.  If so,
75155       ** then the presence of NULLs in the RHS does not matter, so jump
75156       ** over all of the code that follows.
75157       */
75158       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
75159
75160       /* Here we begin generating code that runs if the LHS is not
75161       ** contained within the RHS.  Generate additional code that
75162       ** tests the RHS for NULLs.  If the RHS contains a NULL then
75163       ** jump to destIfNull.  If there are no NULLs in the RHS then
75164       ** jump to destIfFalse.
75165       */
75166       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
75167       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
75168       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
75169       sqlite3VdbeJumpHere(v, j3);
75170       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
75171       sqlite3VdbeJumpHere(v, j2);
75172
75173       /* Jump to the appropriate target depending on whether or not
75174       ** the RHS contains a NULL
75175       */
75176       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
75177       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
75178
75179       /* The OP_Found at the top of this branch jumps here when true, 
75180       ** causing the overall IN expression evaluation to fall through.
75181       */
75182       sqlite3VdbeJumpHere(v, j1);
75183     }
75184   }
75185   sqlite3ReleaseTempReg(pParse, r1);
75186   sqlite3ExprCachePop(pParse, 1);
75187   VdbeComment((v, "end IN expr"));
75188 }
75189 #endif /* SQLITE_OMIT_SUBQUERY */
75190
75191 /*
75192 ** Duplicate an 8-byte value
75193 */
75194 static char *dup8bytes(Vdbe *v, const char *in){
75195   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
75196   if( out ){
75197     memcpy(out, in, 8);
75198   }
75199   return out;
75200 }
75201
75202 #ifndef SQLITE_OMIT_FLOATING_POINT
75203 /*
75204 ** Generate an instruction that will put the floating point
75205 ** value described by z[0..n-1] into register iMem.
75206 **
75207 ** The z[] string will probably not be zero-terminated.  But the 
75208 ** z[n] character is guaranteed to be something that does not look
75209 ** like the continuation of the number.
75210 */
75211 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
75212   if( ALWAYS(z!=0) ){
75213     double value;
75214     char *zV;
75215     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
75216     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
75217     if( negateFlag ) value = -value;
75218     zV = dup8bytes(v, (char*)&value);
75219     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
75220   }
75221 }
75222 #endif
75223
75224
75225 /*
75226 ** Generate an instruction that will put the integer describe by
75227 ** text z[0..n-1] into register iMem.
75228 **
75229 ** Expr.u.zToken is always UTF8 and zero-terminated.
75230 */
75231 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
75232   Vdbe *v = pParse->pVdbe;
75233   if( pExpr->flags & EP_IntValue ){
75234     int i = pExpr->u.iValue;
75235     assert( i>=0 );
75236     if( negFlag ) i = -i;
75237     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
75238   }else{
75239     int c;
75240     i64 value;
75241     const char *z = pExpr->u.zToken;
75242     assert( z!=0 );
75243     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
75244     if( c==0 || (c==2 && negFlag) ){
75245       char *zV;
75246       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
75247       zV = dup8bytes(v, (char*)&value);
75248       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
75249     }else{
75250 #ifdef SQLITE_OMIT_FLOATING_POINT
75251       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
75252 #else
75253       codeReal(v, z, negFlag, iMem);
75254 #endif
75255     }
75256   }
75257 }
75258
75259 /*
75260 ** Clear a cache entry.
75261 */
75262 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
75263   if( p->tempReg ){
75264     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
75265       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
75266     }
75267     p->tempReg = 0;
75268   }
75269 }
75270
75271
75272 /*
75273 ** Record in the column cache that a particular column from a
75274 ** particular table is stored in a particular register.
75275 */
75276 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
75277   int i;
75278   int minLru;
75279   int idxLru;
75280   struct yColCache *p;
75281
75282   assert( iReg>0 );  /* Register numbers are always positive */
75283   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
75284
75285   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
75286   ** for testing only - to verify that SQLite always gets the same answer
75287   ** with and without the column cache.
75288   */
75289   if( pParse->db->flags & SQLITE_ColumnCache ) return;
75290
75291   /* First replace any existing entry.
75292   **
75293   ** Actually, the way the column cache is currently used, we are guaranteed
75294   ** that the object will never already be in cache.  Verify this guarantee.
75295   */
75296 #ifndef NDEBUG
75297   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75298     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
75299   }
75300 #endif
75301
75302   /* Find an empty slot and replace it */
75303   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75304     if( p->iReg==0 ){
75305       p->iLevel = pParse->iCacheLevel;
75306       p->iTable = iTab;
75307       p->iColumn = iCol;
75308       p->iReg = iReg;
75309       p->tempReg = 0;
75310       p->lru = pParse->iCacheCnt++;
75311       return;
75312     }
75313   }
75314
75315   /* Replace the last recently used */
75316   minLru = 0x7fffffff;
75317   idxLru = -1;
75318   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75319     if( p->lru<minLru ){
75320       idxLru = i;
75321       minLru = p->lru;
75322     }
75323   }
75324   if( ALWAYS(idxLru>=0) ){
75325     p = &pParse->aColCache[idxLru];
75326     p->iLevel = pParse->iCacheLevel;
75327     p->iTable = iTab;
75328     p->iColumn = iCol;
75329     p->iReg = iReg;
75330     p->tempReg = 0;
75331     p->lru = pParse->iCacheCnt++;
75332     return;
75333   }
75334 }
75335
75336 /*
75337 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
75338 ** Purge the range of registers from the column cache.
75339 */
75340 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
75341   int i;
75342   int iLast = iReg + nReg - 1;
75343   struct yColCache *p;
75344   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75345     int r = p->iReg;
75346     if( r>=iReg && r<=iLast ){
75347       cacheEntryClear(pParse, p);
75348       p->iReg = 0;
75349     }
75350   }
75351 }
75352
75353 /*
75354 ** Remember the current column cache context.  Any new entries added
75355 ** added to the column cache after this call are removed when the
75356 ** corresponding pop occurs.
75357 */
75358 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
75359   pParse->iCacheLevel++;
75360 }
75361
75362 /*
75363 ** Remove from the column cache any entries that were added since the
75364 ** the previous N Push operations.  In other words, restore the cache
75365 ** to the state it was in N Pushes ago.
75366 */
75367 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
75368   int i;
75369   struct yColCache *p;
75370   assert( N>0 );
75371   assert( pParse->iCacheLevel>=N );
75372   pParse->iCacheLevel -= N;
75373   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75374     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
75375       cacheEntryClear(pParse, p);
75376       p->iReg = 0;
75377     }
75378   }
75379 }
75380
75381 /*
75382 ** When a cached column is reused, make sure that its register is
75383 ** no longer available as a temp register.  ticket #3879:  that same
75384 ** register might be in the cache in multiple places, so be sure to
75385 ** get them all.
75386 */
75387 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
75388   int i;
75389   struct yColCache *p;
75390   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75391     if( p->iReg==iReg ){
75392       p->tempReg = 0;
75393     }
75394   }
75395 }
75396
75397 /*
75398 ** Generate code to extract the value of the iCol-th column of a table.
75399 */
75400 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
75401   Vdbe *v,        /* The VDBE under construction */
75402   Table *pTab,    /* The table containing the value */
75403   int iTabCur,    /* The cursor for this table */
75404   int iCol,       /* Index of the column to extract */
75405   int regOut      /* Extract the valud into this register */
75406 ){
75407   if( iCol<0 || iCol==pTab->iPKey ){
75408     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
75409   }else{
75410     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
75411     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
75412   }
75413   if( iCol>=0 ){
75414     sqlite3ColumnDefault(v, pTab, iCol, regOut);
75415   }
75416 }
75417
75418 /*
75419 ** Generate code that will extract the iColumn-th column from
75420 ** table pTab and store the column value in a register.  An effort
75421 ** is made to store the column value in register iReg, but this is
75422 ** not guaranteed.  The location of the column value is returned.
75423 **
75424 ** There must be an open cursor to pTab in iTable when this routine
75425 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
75426 */
75427 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
75428   Parse *pParse,   /* Parsing and code generating context */
75429   Table *pTab,     /* Description of the table we are reading from */
75430   int iColumn,     /* Index of the table column */
75431   int iTable,      /* The cursor pointing to the table */
75432   int iReg,        /* Store results here */
75433   u8 p5            /* P5 value for OP_Column */
75434 ){
75435   Vdbe *v = pParse->pVdbe;
75436   int i;
75437   struct yColCache *p;
75438
75439   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75440     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
75441       p->lru = pParse->iCacheCnt++;
75442       sqlite3ExprCachePinRegister(pParse, p->iReg);
75443       return p->iReg;
75444     }
75445   }  
75446   assert( v!=0 );
75447   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
75448   if( p5 ){
75449     sqlite3VdbeChangeP5(v, p5);
75450   }else{   
75451     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
75452   }
75453   return iReg;
75454 }
75455
75456 /*
75457 ** Clear all column cache entries.
75458 */
75459 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
75460   int i;
75461   struct yColCache *p;
75462
75463   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75464     if( p->iReg ){
75465       cacheEntryClear(pParse, p);
75466       p->iReg = 0;
75467     }
75468   }
75469 }
75470
75471 /*
75472 ** Record the fact that an affinity change has occurred on iCount
75473 ** registers starting with iStart.
75474 */
75475 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
75476   sqlite3ExprCacheRemove(pParse, iStart, iCount);
75477 }
75478
75479 /*
75480 ** Generate code to move content from registers iFrom...iFrom+nReg-1
75481 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
75482 */
75483 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
75484   int i;
75485   struct yColCache *p;
75486   if( NEVER(iFrom==iTo) ) return;
75487   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
75488   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75489     int x = p->iReg;
75490     if( x>=iFrom && x<iFrom+nReg ){
75491       p->iReg += iTo-iFrom;
75492     }
75493   }
75494 }
75495
75496 /*
75497 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
75498 ** over to iTo..iTo+nReg-1.
75499 */
75500 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
75501   int i;
75502   if( NEVER(iFrom==iTo) ) return;
75503   for(i=0; i<nReg; i++){
75504     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
75505   }
75506 }
75507
75508 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
75509 /*
75510 ** Return true if any register in the range iFrom..iTo (inclusive)
75511 ** is used as part of the column cache.
75512 **
75513 ** This routine is used within assert() and testcase() macros only
75514 ** and does not appear in a normal build.
75515 */
75516 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
75517   int i;
75518   struct yColCache *p;
75519   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75520     int r = p->iReg;
75521     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
75522   }
75523   return 0;
75524 }
75525 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
75526
75527 /*
75528 ** Generate code into the current Vdbe to evaluate the given
75529 ** expression.  Attempt to store the results in register "target".
75530 ** Return the register where results are stored.
75531 **
75532 ** With this routine, there is no guarantee that results will
75533 ** be stored in target.  The result might be stored in some other
75534 ** register if it is convenient to do so.  The calling function
75535 ** must check the return code and move the results to the desired
75536 ** register.
75537 */
75538 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
75539   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
75540   int op;                   /* The opcode being coded */
75541   int inReg = target;       /* Results stored in register inReg */
75542   int regFree1 = 0;         /* If non-zero free this temporary register */
75543   int regFree2 = 0;         /* If non-zero free this temporary register */
75544   int r1, r2, r3, r4;       /* Various register numbers */
75545   sqlite3 *db = pParse->db; /* The database connection */
75546
75547   assert( target>0 && target<=pParse->nMem );
75548   if( v==0 ){
75549     assert( pParse->db->mallocFailed );
75550     return 0;
75551   }
75552
75553   if( pExpr==0 ){
75554     op = TK_NULL;
75555   }else{
75556     op = pExpr->op;
75557   }
75558   switch( op ){
75559     case TK_AGG_COLUMN: {
75560       AggInfo *pAggInfo = pExpr->pAggInfo;
75561       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
75562       if( !pAggInfo->directMode ){
75563         assert( pCol->iMem>0 );
75564         inReg = pCol->iMem;
75565         break;
75566       }else if( pAggInfo->useSortingIdx ){
75567         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
75568                               pCol->iSorterColumn, target);
75569         break;
75570       }
75571       /* Otherwise, fall thru into the TK_COLUMN case */
75572     }
75573     case TK_COLUMN: {
75574       if( pExpr->iTable<0 ){
75575         /* This only happens when coding check constraints */
75576         assert( pParse->ckBase>0 );
75577         inReg = pExpr->iColumn + pParse->ckBase;
75578       }else{
75579         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
75580                                  pExpr->iColumn, pExpr->iTable, target,
75581                                  pExpr->op2);
75582       }
75583       break;
75584     }
75585     case TK_INTEGER: {
75586       codeInteger(pParse, pExpr, 0, target);
75587       break;
75588     }
75589 #ifndef SQLITE_OMIT_FLOATING_POINT
75590     case TK_FLOAT: {
75591       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75592       codeReal(v, pExpr->u.zToken, 0, target);
75593       break;
75594     }
75595 #endif
75596     case TK_STRING: {
75597       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75598       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
75599       break;
75600     }
75601     case TK_NULL: {
75602       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75603       break;
75604     }
75605 #ifndef SQLITE_OMIT_BLOB_LITERAL
75606     case TK_BLOB: {
75607       int n;
75608       const char *z;
75609       char *zBlob;
75610       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75611       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
75612       assert( pExpr->u.zToken[1]=='\'' );
75613       z = &pExpr->u.zToken[2];
75614       n = sqlite3Strlen30(z) - 1;
75615       assert( z[n]=='\'' );
75616       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
75617       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
75618       break;
75619     }
75620 #endif
75621     case TK_VARIABLE: {
75622       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75623       assert( pExpr->u.zToken!=0 );
75624       assert( pExpr->u.zToken[0]!=0 );
75625       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
75626       if( pExpr->u.zToken[1]!=0 ){
75627         assert( pExpr->u.zToken[0]=='?' 
75628              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
75629         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
75630       }
75631       break;
75632     }
75633     case TK_REGISTER: {
75634       inReg = pExpr->iTable;
75635       break;
75636     }
75637     case TK_AS: {
75638       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75639       break;
75640     }
75641 #ifndef SQLITE_OMIT_CAST
75642     case TK_CAST: {
75643       /* Expressions of the form:   CAST(pLeft AS token) */
75644       int aff, to_op;
75645       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75646       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75647       aff = sqlite3AffinityType(pExpr->u.zToken);
75648       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
75649       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
75650       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
75651       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
75652       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
75653       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
75654       testcase( to_op==OP_ToText );
75655       testcase( to_op==OP_ToBlob );
75656       testcase( to_op==OP_ToNumeric );
75657       testcase( to_op==OP_ToInt );
75658       testcase( to_op==OP_ToReal );
75659       if( inReg!=target ){
75660         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
75661         inReg = target;
75662       }
75663       sqlite3VdbeAddOp1(v, to_op, inReg);
75664       testcase( usedAsColumnCache(pParse, inReg, inReg) );
75665       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
75666       break;
75667     }
75668 #endif /* SQLITE_OMIT_CAST */
75669     case TK_LT:
75670     case TK_LE:
75671     case TK_GT:
75672     case TK_GE:
75673     case TK_NE:
75674     case TK_EQ: {
75675       assert( TK_LT==OP_Lt );
75676       assert( TK_LE==OP_Le );
75677       assert( TK_GT==OP_Gt );
75678       assert( TK_GE==OP_Ge );
75679       assert( TK_EQ==OP_Eq );
75680       assert( TK_NE==OP_Ne );
75681       testcase( op==TK_LT );
75682       testcase( op==TK_LE );
75683       testcase( op==TK_GT );
75684       testcase( op==TK_GE );
75685       testcase( op==TK_EQ );
75686       testcase( op==TK_NE );
75687       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75688       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75689       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75690                   r1, r2, inReg, SQLITE_STOREP2);
75691       testcase( regFree1==0 );
75692       testcase( regFree2==0 );
75693       break;
75694     }
75695     case TK_IS:
75696     case TK_ISNOT: {
75697       testcase( op==TK_IS );
75698       testcase( op==TK_ISNOT );
75699       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75700       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75701       op = (op==TK_IS) ? TK_EQ : TK_NE;
75702       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75703                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
75704       testcase( regFree1==0 );
75705       testcase( regFree2==0 );
75706       break;
75707     }
75708     case TK_AND:
75709     case TK_OR:
75710     case TK_PLUS:
75711     case TK_STAR:
75712     case TK_MINUS:
75713     case TK_REM:
75714     case TK_BITAND:
75715     case TK_BITOR:
75716     case TK_SLASH:
75717     case TK_LSHIFT:
75718     case TK_RSHIFT: 
75719     case TK_CONCAT: {
75720       assert( TK_AND==OP_And );
75721       assert( TK_OR==OP_Or );
75722       assert( TK_PLUS==OP_Add );
75723       assert( TK_MINUS==OP_Subtract );
75724       assert( TK_REM==OP_Remainder );
75725       assert( TK_BITAND==OP_BitAnd );
75726       assert( TK_BITOR==OP_BitOr );
75727       assert( TK_SLASH==OP_Divide );
75728       assert( TK_LSHIFT==OP_ShiftLeft );
75729       assert( TK_RSHIFT==OP_ShiftRight );
75730       assert( TK_CONCAT==OP_Concat );
75731       testcase( op==TK_AND );
75732       testcase( op==TK_OR );
75733       testcase( op==TK_PLUS );
75734       testcase( op==TK_MINUS );
75735       testcase( op==TK_REM );
75736       testcase( op==TK_BITAND );
75737       testcase( op==TK_BITOR );
75738       testcase( op==TK_SLASH );
75739       testcase( op==TK_LSHIFT );
75740       testcase( op==TK_RSHIFT );
75741       testcase( op==TK_CONCAT );
75742       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75743       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75744       sqlite3VdbeAddOp3(v, op, r2, r1, target);
75745       testcase( regFree1==0 );
75746       testcase( regFree2==0 );
75747       break;
75748     }
75749     case TK_UMINUS: {
75750       Expr *pLeft = pExpr->pLeft;
75751       assert( pLeft );
75752       if( pLeft->op==TK_INTEGER ){
75753         codeInteger(pParse, pLeft, 1, target);
75754 #ifndef SQLITE_OMIT_FLOATING_POINT
75755       }else if( pLeft->op==TK_FLOAT ){
75756         assert( !ExprHasProperty(pExpr, EP_IntValue) );
75757         codeReal(v, pLeft->u.zToken, 1, target);
75758 #endif
75759       }else{
75760         regFree1 = r1 = sqlite3GetTempReg(pParse);
75761         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
75762         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
75763         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
75764         testcase( regFree2==0 );
75765       }
75766       inReg = target;
75767       break;
75768     }
75769     case TK_BITNOT:
75770     case TK_NOT: {
75771       assert( TK_BITNOT==OP_BitNot );
75772       assert( TK_NOT==OP_Not );
75773       testcase( op==TK_BITNOT );
75774       testcase( op==TK_NOT );
75775       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75776       testcase( regFree1==0 );
75777       inReg = target;
75778       sqlite3VdbeAddOp2(v, op, r1, inReg);
75779       break;
75780     }
75781     case TK_ISNULL:
75782     case TK_NOTNULL: {
75783       int addr;
75784       assert( TK_ISNULL==OP_IsNull );
75785       assert( TK_NOTNULL==OP_NotNull );
75786       testcase( op==TK_ISNULL );
75787       testcase( op==TK_NOTNULL );
75788       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75789       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75790       testcase( regFree1==0 );
75791       addr = sqlite3VdbeAddOp1(v, op, r1);
75792       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
75793       sqlite3VdbeJumpHere(v, addr);
75794       break;
75795     }
75796     case TK_AGG_FUNCTION: {
75797       AggInfo *pInfo = pExpr->pAggInfo;
75798       if( pInfo==0 ){
75799         assert( !ExprHasProperty(pExpr, EP_IntValue) );
75800         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
75801       }else{
75802         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
75803       }
75804       break;
75805     }
75806     case TK_CONST_FUNC:
75807     case TK_FUNCTION: {
75808       ExprList *pFarg;       /* List of function arguments */
75809       int nFarg;             /* Number of function arguments */
75810       FuncDef *pDef;         /* The function definition object */
75811       int nId;               /* Length of the function name in bytes */
75812       const char *zId;       /* The function name */
75813       int constMask = 0;     /* Mask of function arguments that are constant */
75814       int i;                 /* Loop counter */
75815       u8 enc = ENC(db);      /* The text encoding used by this database */
75816       CollSeq *pColl = 0;    /* A collating sequence */
75817
75818       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
75819       testcase( op==TK_CONST_FUNC );
75820       testcase( op==TK_FUNCTION );
75821       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
75822         pFarg = 0;
75823       }else{
75824         pFarg = pExpr->x.pList;
75825       }
75826       nFarg = pFarg ? pFarg->nExpr : 0;
75827       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75828       zId = pExpr->u.zToken;
75829       nId = sqlite3Strlen30(zId);
75830       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
75831       if( pDef==0 ){
75832         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
75833         break;
75834       }
75835
75836       /* Attempt a direct implementation of the built-in COALESCE() and
75837       ** IFNULL() functions.  This avoids unnecessary evalation of
75838       ** arguments past the first non-NULL argument.
75839       */
75840       if( pDef->flags & SQLITE_FUNC_COALESCE ){
75841         int endCoalesce = sqlite3VdbeMakeLabel(v);
75842         assert( nFarg>=2 );
75843         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
75844         for(i=1; i<nFarg; i++){
75845           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
75846           sqlite3ExprCacheRemove(pParse, target, 1);
75847           sqlite3ExprCachePush(pParse);
75848           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
75849           sqlite3ExprCachePop(pParse, 1);
75850         }
75851         sqlite3VdbeResolveLabel(v, endCoalesce);
75852         break;
75853       }
75854
75855
75856       if( pFarg ){
75857         r1 = sqlite3GetTempRange(pParse, nFarg);
75858
75859         /* For length() and typeof() functions with a column argument,
75860         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
75861         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
75862         ** loading.
75863         */
75864         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
75865           u8 exprOp;
75866           assert( nFarg==1 );
75867           assert( pFarg->a[0].pExpr!=0 );
75868           exprOp = pFarg->a[0].pExpr->op;
75869           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
75870             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
75871             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
75872             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
75873             pFarg->a[0].pExpr->op2 = pDef->flags;
75874           }
75875         }
75876
75877         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
75878         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
75879         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
75880       }else{
75881         r1 = 0;
75882       }
75883 #ifndef SQLITE_OMIT_VIRTUALTABLE
75884       /* Possibly overload the function if the first argument is
75885       ** a virtual table column.
75886       **
75887       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
75888       ** second argument, not the first, as the argument to test to
75889       ** see if it is a column in a virtual table.  This is done because
75890       ** the left operand of infix functions (the operand we want to
75891       ** control overloading) ends up as the second argument to the
75892       ** function.  The expression "A glob B" is equivalent to 
75893       ** "glob(B,A).  We want to use the A in "A glob B" to test
75894       ** for function overloading.  But we use the B term in "glob(B,A)".
75895       */
75896       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
75897         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
75898       }else if( nFarg>0 ){
75899         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
75900       }
75901 #endif
75902       for(i=0; i<nFarg; i++){
75903         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
75904           constMask |= (1<<i);
75905         }
75906         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
75907           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
75908         }
75909       }
75910       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
75911         if( !pColl ) pColl = db->pDfltColl; 
75912         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
75913       }
75914       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
75915                         (char*)pDef, P4_FUNCDEF);
75916       sqlite3VdbeChangeP5(v, (u8)nFarg);
75917       if( nFarg ){
75918         sqlite3ReleaseTempRange(pParse, r1, nFarg);
75919       }
75920       break;
75921     }
75922 #ifndef SQLITE_OMIT_SUBQUERY
75923     case TK_EXISTS:
75924     case TK_SELECT: {
75925       testcase( op==TK_EXISTS );
75926       testcase( op==TK_SELECT );
75927       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
75928       break;
75929     }
75930     case TK_IN: {
75931       int destIfFalse = sqlite3VdbeMakeLabel(v);
75932       int destIfNull = sqlite3VdbeMakeLabel(v);
75933       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75934       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
75935       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75936       sqlite3VdbeResolveLabel(v, destIfFalse);
75937       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
75938       sqlite3VdbeResolveLabel(v, destIfNull);
75939       break;
75940     }
75941 #endif /* SQLITE_OMIT_SUBQUERY */
75942
75943
75944     /*
75945     **    x BETWEEN y AND z
75946     **
75947     ** This is equivalent to
75948     **
75949     **    x>=y AND x<=z
75950     **
75951     ** X is stored in pExpr->pLeft.
75952     ** Y is stored in pExpr->pList->a[0].pExpr.
75953     ** Z is stored in pExpr->pList->a[1].pExpr.
75954     */
75955     case TK_BETWEEN: {
75956       Expr *pLeft = pExpr->pLeft;
75957       struct ExprList_item *pLItem = pExpr->x.pList->a;
75958       Expr *pRight = pLItem->pExpr;
75959
75960       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
75961       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75962       testcase( regFree1==0 );
75963       testcase( regFree2==0 );
75964       r3 = sqlite3GetTempReg(pParse);
75965       r4 = sqlite3GetTempReg(pParse);
75966       codeCompare(pParse, pLeft, pRight, OP_Ge,
75967                   r1, r2, r3, SQLITE_STOREP2);
75968       pLItem++;
75969       pRight = pLItem->pExpr;
75970       sqlite3ReleaseTempReg(pParse, regFree2);
75971       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75972       testcase( regFree2==0 );
75973       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
75974       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
75975       sqlite3ReleaseTempReg(pParse, r3);
75976       sqlite3ReleaseTempReg(pParse, r4);
75977       break;
75978     }
75979     case TK_UPLUS: {
75980       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75981       break;
75982     }
75983
75984     case TK_TRIGGER: {
75985       /* If the opcode is TK_TRIGGER, then the expression is a reference
75986       ** to a column in the new.* or old.* pseudo-tables available to
75987       ** trigger programs. In this case Expr.iTable is set to 1 for the
75988       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
75989       ** is set to the column of the pseudo-table to read, or to -1 to
75990       ** read the rowid field.
75991       **
75992       ** The expression is implemented using an OP_Param opcode. The p1
75993       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
75994       ** to reference another column of the old.* pseudo-table, where 
75995       ** i is the index of the column. For a new.rowid reference, p1 is
75996       ** set to (n+1), where n is the number of columns in each pseudo-table.
75997       ** For a reference to any other column in the new.* pseudo-table, p1
75998       ** is set to (n+2+i), where n and i are as defined previously. For
75999       ** example, if the table on which triggers are being fired is
76000       ** declared as:
76001       **
76002       **   CREATE TABLE t1(a, b);
76003       **
76004       ** Then p1 is interpreted as follows:
76005       **
76006       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
76007       **   p1==1   ->    old.a         p1==4   ->    new.a
76008       **   p1==2   ->    old.b         p1==5   ->    new.b       
76009       */
76010       Table *pTab = pExpr->pTab;
76011       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
76012
76013       assert( pExpr->iTable==0 || pExpr->iTable==1 );
76014       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
76015       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
76016       assert( p1>=0 && p1<(pTab->nCol*2+2) );
76017
76018       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
76019       VdbeComment((v, "%s.%s -> $%d",
76020         (pExpr->iTable ? "new" : "old"),
76021         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
76022         target
76023       ));
76024
76025 #ifndef SQLITE_OMIT_FLOATING_POINT
76026       /* If the column has REAL affinity, it may currently be stored as an
76027       ** integer. Use OP_RealAffinity to make sure it is really real.  */
76028       if( pExpr->iColumn>=0 
76029        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
76030       ){
76031         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
76032       }
76033 #endif
76034       break;
76035     }
76036
76037
76038     /*
76039     ** Form A:
76040     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76041     **
76042     ** Form B:
76043     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76044     **
76045     ** Form A is can be transformed into the equivalent form B as follows:
76046     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
76047     **        WHEN x=eN THEN rN ELSE y END
76048     **
76049     ** X (if it exists) is in pExpr->pLeft.
76050     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
76051     ** ELSE clause and no other term matches, then the result of the
76052     ** exprssion is NULL.
76053     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
76054     **
76055     ** The result of the expression is the Ri for the first matching Ei,
76056     ** or if there is no matching Ei, the ELSE term Y, or if there is
76057     ** no ELSE term, NULL.
76058     */
76059     default: assert( op==TK_CASE ); {
76060       int endLabel;                     /* GOTO label for end of CASE stmt */
76061       int nextCase;                     /* GOTO label for next WHEN clause */
76062       int nExpr;                        /* 2x number of WHEN terms */
76063       int i;                            /* Loop counter */
76064       ExprList *pEList;                 /* List of WHEN terms */
76065       struct ExprList_item *aListelem;  /* Array of WHEN terms */
76066       Expr opCompare;                   /* The X==Ei expression */
76067       Expr cacheX;                      /* Cached expression X */
76068       Expr *pX;                         /* The X expression */
76069       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
76070       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
76071
76072       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
76073       assert((pExpr->x.pList->nExpr % 2) == 0);
76074       assert(pExpr->x.pList->nExpr > 0);
76075       pEList = pExpr->x.pList;
76076       aListelem = pEList->a;
76077       nExpr = pEList->nExpr;
76078       endLabel = sqlite3VdbeMakeLabel(v);
76079       if( (pX = pExpr->pLeft)!=0 ){
76080         cacheX = *pX;
76081         testcase( pX->op==TK_COLUMN );
76082         testcase( pX->op==TK_REGISTER );
76083         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
76084         testcase( regFree1==0 );
76085         cacheX.op = TK_REGISTER;
76086         opCompare.op = TK_EQ;
76087         opCompare.pLeft = &cacheX;
76088         pTest = &opCompare;
76089         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
76090         ** The value in regFree1 might get SCopy-ed into the file result.
76091         ** So make sure that the regFree1 register is not reused for other
76092         ** purposes and possibly overwritten.  */
76093         regFree1 = 0;
76094       }
76095       for(i=0; i<nExpr; i=i+2){
76096         sqlite3ExprCachePush(pParse);
76097         if( pX ){
76098           assert( pTest!=0 );
76099           opCompare.pRight = aListelem[i].pExpr;
76100         }else{
76101           pTest = aListelem[i].pExpr;
76102         }
76103         nextCase = sqlite3VdbeMakeLabel(v);
76104         testcase( pTest->op==TK_COLUMN );
76105         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
76106         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
76107         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
76108         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
76109         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
76110         sqlite3ExprCachePop(pParse, 1);
76111         sqlite3VdbeResolveLabel(v, nextCase);
76112       }
76113       if( pExpr->pRight ){
76114         sqlite3ExprCachePush(pParse);
76115         sqlite3ExprCode(pParse, pExpr->pRight, target);
76116         sqlite3ExprCachePop(pParse, 1);
76117       }else{
76118         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76119       }
76120       assert( db->mallocFailed || pParse->nErr>0 
76121            || pParse->iCacheLevel==iCacheLevel );
76122       sqlite3VdbeResolveLabel(v, endLabel);
76123       break;
76124     }
76125 #ifndef SQLITE_OMIT_TRIGGER
76126     case TK_RAISE: {
76127       assert( pExpr->affinity==OE_Rollback 
76128            || pExpr->affinity==OE_Abort
76129            || pExpr->affinity==OE_Fail
76130            || pExpr->affinity==OE_Ignore
76131       );
76132       if( !pParse->pTriggerTab ){
76133         sqlite3ErrorMsg(pParse,
76134                        "RAISE() may only be used within a trigger-program");
76135         return 0;
76136       }
76137       if( pExpr->affinity==OE_Abort ){
76138         sqlite3MayAbort(pParse);
76139       }
76140       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76141       if( pExpr->affinity==OE_Ignore ){
76142         sqlite3VdbeAddOp4(
76143             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
76144       }else{
76145         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
76146       }
76147
76148       break;
76149     }
76150 #endif
76151   }
76152   sqlite3ReleaseTempReg(pParse, regFree1);
76153   sqlite3ReleaseTempReg(pParse, regFree2);
76154   return inReg;
76155 }
76156
76157 /*
76158 ** Generate code to evaluate an expression and store the results
76159 ** into a register.  Return the register number where the results
76160 ** are stored.
76161 **
76162 ** If the register is a temporary register that can be deallocated,
76163 ** then write its number into *pReg.  If the result register is not
76164 ** a temporary, then set *pReg to zero.
76165 */
76166 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
76167   int r1 = sqlite3GetTempReg(pParse);
76168   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76169   if( r2==r1 ){
76170     *pReg = r1;
76171   }else{
76172     sqlite3ReleaseTempReg(pParse, r1);
76173     *pReg = 0;
76174   }
76175   return r2;
76176 }
76177
76178 /*
76179 ** Generate code that will evaluate expression pExpr and store the
76180 ** results in register target.  The results are guaranteed to appear
76181 ** in register target.
76182 */
76183 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
76184   int inReg;
76185
76186   assert( target>0 && target<=pParse->nMem );
76187   if( pExpr && pExpr->op==TK_REGISTER ){
76188     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
76189   }else{
76190     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
76191     assert( pParse->pVdbe || pParse->db->mallocFailed );
76192     if( inReg!=target && pParse->pVdbe ){
76193       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
76194     }
76195   }
76196   return target;
76197 }
76198
76199 /*
76200 ** Generate code that evalutes the given expression and puts the result
76201 ** in register target.
76202 **
76203 ** Also make a copy of the expression results into another "cache" register
76204 ** and modify the expression so that the next time it is evaluated,
76205 ** the result is a copy of the cache register.
76206 **
76207 ** This routine is used for expressions that are used multiple 
76208 ** times.  They are evaluated once and the results of the expression
76209 ** are reused.
76210 */
76211 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
76212   Vdbe *v = pParse->pVdbe;
76213   int inReg;
76214   inReg = sqlite3ExprCode(pParse, pExpr, target);
76215   assert( target>0 );
76216   /* This routine is called for terms to INSERT or UPDATE.  And the only
76217   ** other place where expressions can be converted into TK_REGISTER is
76218   ** in WHERE clause processing.  So as currently implemented, there is
76219   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
76220   ** keep the ALWAYS() in case the conditions above change with future
76221   ** modifications or enhancements. */
76222   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
76223     int iMem;
76224     iMem = ++pParse->nMem;
76225     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
76226     pExpr->iTable = iMem;
76227     pExpr->op2 = pExpr->op;
76228     pExpr->op = TK_REGISTER;
76229   }
76230   return inReg;
76231 }
76232
76233 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
76234 /*
76235 ** Generate a human-readable explanation of an expression tree.
76236 */
76237 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
76238   int op;                   /* The opcode being coded */
76239   const char *zBinOp = 0;   /* Binary operator */
76240   const char *zUniOp = 0;   /* Unary operator */
76241   if( pExpr==0 ){
76242     op = TK_NULL;
76243   }else{
76244     op = pExpr->op;
76245   }
76246   switch( op ){
76247     case TK_AGG_COLUMN: {
76248       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
76249             pExpr->iTable, pExpr->iColumn);
76250       break;
76251     }
76252     case TK_COLUMN: {
76253       if( pExpr->iTable<0 ){
76254         /* This only happens when coding check constraints */
76255         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
76256       }else{
76257         sqlite3ExplainPrintf(pOut, "{%d:%d}",
76258                              pExpr->iTable, pExpr->iColumn);
76259       }
76260       break;
76261     }
76262     case TK_INTEGER: {
76263       if( pExpr->flags & EP_IntValue ){
76264         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
76265       }else{
76266         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
76267       }
76268       break;
76269     }
76270 #ifndef SQLITE_OMIT_FLOATING_POINT
76271     case TK_FLOAT: {
76272       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
76273       break;
76274     }
76275 #endif
76276     case TK_STRING: {
76277       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
76278       break;
76279     }
76280     case TK_NULL: {
76281       sqlite3ExplainPrintf(pOut,"NULL");
76282       break;
76283     }
76284 #ifndef SQLITE_OMIT_BLOB_LITERAL
76285     case TK_BLOB: {
76286       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
76287       break;
76288     }
76289 #endif
76290     case TK_VARIABLE: {
76291       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
76292                            pExpr->u.zToken, pExpr->iColumn);
76293       break;
76294     }
76295     case TK_REGISTER: {
76296       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
76297       break;
76298     }
76299     case TK_AS: {
76300       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76301       break;
76302     }
76303 #ifndef SQLITE_OMIT_CAST
76304     case TK_CAST: {
76305       /* Expressions of the form:   CAST(pLeft AS token) */
76306       const char *zAff = "unk";
76307       switch( sqlite3AffinityType(pExpr->u.zToken) ){
76308         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
76309         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
76310         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
76311         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
76312         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
76313       }
76314       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
76315       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76316       sqlite3ExplainPrintf(pOut, ")");
76317       break;
76318     }
76319 #endif /* SQLITE_OMIT_CAST */
76320     case TK_LT:      zBinOp = "LT";     break;
76321     case TK_LE:      zBinOp = "LE";     break;
76322     case TK_GT:      zBinOp = "GT";     break;
76323     case TK_GE:      zBinOp = "GE";     break;
76324     case TK_NE:      zBinOp = "NE";     break;
76325     case TK_EQ:      zBinOp = "EQ";     break;
76326     case TK_IS:      zBinOp = "IS";     break;
76327     case TK_ISNOT:   zBinOp = "ISNOT";  break;
76328     case TK_AND:     zBinOp = "AND";    break;
76329     case TK_OR:      zBinOp = "OR";     break;
76330     case TK_PLUS:    zBinOp = "ADD";    break;
76331     case TK_STAR:    zBinOp = "MUL";    break;
76332     case TK_MINUS:   zBinOp = "SUB";    break;
76333     case TK_REM:     zBinOp = "REM";    break;
76334     case TK_BITAND:  zBinOp = "BITAND"; break;
76335     case TK_BITOR:   zBinOp = "BITOR";  break;
76336     case TK_SLASH:   zBinOp = "DIV";    break;
76337     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
76338     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
76339     case TK_CONCAT:  zBinOp = "CONCAT"; break;
76340
76341     case TK_UMINUS:  zUniOp = "UMINUS"; break;
76342     case TK_UPLUS:   zUniOp = "UPLUS";  break;
76343     case TK_BITNOT:  zUniOp = "BITNOT"; break;
76344     case TK_NOT:     zUniOp = "NOT";    break;
76345     case TK_ISNULL:  zUniOp = "ISNULL"; break;
76346     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
76347
76348     case TK_AGG_FUNCTION:
76349     case TK_CONST_FUNC:
76350     case TK_FUNCTION: {
76351       ExprList *pFarg;       /* List of function arguments */
76352       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76353         pFarg = 0;
76354       }else{
76355         pFarg = pExpr->x.pList;
76356       }
76357       if( op==TK_AGG_FUNCTION ){
76358         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
76359                              pExpr->op2, pExpr->u.zToken);
76360       }else{
76361         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
76362       }
76363       if( pFarg ){
76364         sqlite3ExplainExprList(pOut, pFarg);
76365       }
76366       sqlite3ExplainPrintf(pOut, ")");
76367       break;
76368     }
76369 #ifndef SQLITE_OMIT_SUBQUERY
76370     case TK_EXISTS: {
76371       sqlite3ExplainPrintf(pOut, "EXISTS(");
76372       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76373       sqlite3ExplainPrintf(pOut,")");
76374       break;
76375     }
76376     case TK_SELECT: {
76377       sqlite3ExplainPrintf(pOut, "(");
76378       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76379       sqlite3ExplainPrintf(pOut, ")");
76380       break;
76381     }
76382     case TK_IN: {
76383       sqlite3ExplainPrintf(pOut, "IN(");
76384       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76385       sqlite3ExplainPrintf(pOut, ",");
76386       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76387         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76388       }else{
76389         sqlite3ExplainExprList(pOut, pExpr->x.pList);
76390       }
76391       sqlite3ExplainPrintf(pOut, ")");
76392       break;
76393     }
76394 #endif /* SQLITE_OMIT_SUBQUERY */
76395
76396     /*
76397     **    x BETWEEN y AND z
76398     **
76399     ** This is equivalent to
76400     **
76401     **    x>=y AND x<=z
76402     **
76403     ** X is stored in pExpr->pLeft.
76404     ** Y is stored in pExpr->pList->a[0].pExpr.
76405     ** Z is stored in pExpr->pList->a[1].pExpr.
76406     */
76407     case TK_BETWEEN: {
76408       Expr *pX = pExpr->pLeft;
76409       Expr *pY = pExpr->x.pList->a[0].pExpr;
76410       Expr *pZ = pExpr->x.pList->a[1].pExpr;
76411       sqlite3ExplainPrintf(pOut, "BETWEEN(");
76412       sqlite3ExplainExpr(pOut, pX);
76413       sqlite3ExplainPrintf(pOut, ",");
76414       sqlite3ExplainExpr(pOut, pY);
76415       sqlite3ExplainPrintf(pOut, ",");
76416       sqlite3ExplainExpr(pOut, pZ);
76417       sqlite3ExplainPrintf(pOut, ")");
76418       break;
76419     }
76420     case TK_TRIGGER: {
76421       /* If the opcode is TK_TRIGGER, then the expression is a reference
76422       ** to a column in the new.* or old.* pseudo-tables available to
76423       ** trigger programs. In this case Expr.iTable is set to 1 for the
76424       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
76425       ** is set to the column of the pseudo-table to read, or to -1 to
76426       ** read the rowid field.
76427       */
76428       sqlite3ExplainPrintf(pOut, "%s(%d)", 
76429           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
76430       break;
76431     }
76432     case TK_CASE: {
76433       sqlite3ExplainPrintf(pOut, "CASE(");
76434       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76435       sqlite3ExplainPrintf(pOut, ",");
76436       sqlite3ExplainExprList(pOut, pExpr->x.pList);
76437       break;
76438     }
76439 #ifndef SQLITE_OMIT_TRIGGER
76440     case TK_RAISE: {
76441       const char *zType = "unk";
76442       switch( pExpr->affinity ){
76443         case OE_Rollback:   zType = "rollback";  break;
76444         case OE_Abort:      zType = "abort";     break;
76445         case OE_Fail:       zType = "fail";      break;
76446         case OE_Ignore:     zType = "ignore";    break;
76447       }
76448       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
76449       break;
76450     }
76451 #endif
76452   }
76453   if( zBinOp ){
76454     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
76455     sqlite3ExplainExpr(pOut, pExpr->pLeft);
76456     sqlite3ExplainPrintf(pOut,",");
76457     sqlite3ExplainExpr(pOut, pExpr->pRight);
76458     sqlite3ExplainPrintf(pOut,")");
76459   }else if( zUniOp ){
76460     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
76461     sqlite3ExplainExpr(pOut, pExpr->pLeft);
76462     sqlite3ExplainPrintf(pOut,")");
76463   }
76464 }
76465 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
76466
76467 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
76468 /*
76469 ** Generate a human-readable explanation of an expression list.
76470 */
76471 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
76472   int i;
76473   if( pList==0 || pList->nExpr==0 ){
76474     sqlite3ExplainPrintf(pOut, "(empty-list)");
76475     return;
76476   }else if( pList->nExpr==1 ){
76477     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
76478   }else{
76479     sqlite3ExplainPush(pOut);
76480     for(i=0; i<pList->nExpr; i++){
76481       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
76482       sqlite3ExplainPush(pOut);
76483       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
76484       sqlite3ExplainPop(pOut);
76485       if( i<pList->nExpr-1 ){
76486         sqlite3ExplainNL(pOut);
76487       }
76488     }
76489     sqlite3ExplainPop(pOut);
76490   }
76491 }
76492 #endif /* SQLITE_DEBUG */
76493
76494 /*
76495 ** Return TRUE if pExpr is an constant expression that is appropriate
76496 ** for factoring out of a loop.  Appropriate expressions are:
76497 **
76498 **    *  Any expression that evaluates to two or more opcodes.
76499 **
76500 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
76501 **       or OP_Variable that does not need to be placed in a 
76502 **       specific register.
76503 **
76504 ** There is no point in factoring out single-instruction constant
76505 ** expressions that need to be placed in a particular register.  
76506 ** We could factor them out, but then we would end up adding an
76507 ** OP_SCopy instruction to move the value into the correct register
76508 ** later.  We might as well just use the original instruction and
76509 ** avoid the OP_SCopy.
76510 */
76511 static int isAppropriateForFactoring(Expr *p){
76512   if( !sqlite3ExprIsConstantNotJoin(p) ){
76513     return 0;  /* Only constant expressions are appropriate for factoring */
76514   }
76515   if( (p->flags & EP_FixedDest)==0 ){
76516     return 1;  /* Any constant without a fixed destination is appropriate */
76517   }
76518   while( p->op==TK_UPLUS ) p = p->pLeft;
76519   switch( p->op ){
76520 #ifndef SQLITE_OMIT_BLOB_LITERAL
76521     case TK_BLOB:
76522 #endif
76523     case TK_VARIABLE:
76524     case TK_INTEGER:
76525     case TK_FLOAT:
76526     case TK_NULL:
76527     case TK_STRING: {
76528       testcase( p->op==TK_BLOB );
76529       testcase( p->op==TK_VARIABLE );
76530       testcase( p->op==TK_INTEGER );
76531       testcase( p->op==TK_FLOAT );
76532       testcase( p->op==TK_NULL );
76533       testcase( p->op==TK_STRING );
76534       /* Single-instruction constants with a fixed destination are
76535       ** better done in-line.  If we factor them, they will just end
76536       ** up generating an OP_SCopy to move the value to the destination
76537       ** register. */
76538       return 0;
76539     }
76540     case TK_UMINUS: {
76541       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
76542         return 0;
76543       }
76544       break;
76545     }
76546     default: {
76547       break;
76548     }
76549   }
76550   return 1;
76551 }
76552
76553 /*
76554 ** If pExpr is a constant expression that is appropriate for
76555 ** factoring out of a loop, then evaluate the expression
76556 ** into a register and convert the expression into a TK_REGISTER
76557 ** expression.
76558 */
76559 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
76560   Parse *pParse = pWalker->pParse;
76561   switch( pExpr->op ){
76562     case TK_IN:
76563     case TK_REGISTER: {
76564       return WRC_Prune;
76565     }
76566     case TK_FUNCTION:
76567     case TK_AGG_FUNCTION:
76568     case TK_CONST_FUNC: {
76569       /* The arguments to a function have a fixed destination.
76570       ** Mark them this way to avoid generated unneeded OP_SCopy
76571       ** instructions. 
76572       */
76573       ExprList *pList = pExpr->x.pList;
76574       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76575       if( pList ){
76576         int i = pList->nExpr;
76577         struct ExprList_item *pItem = pList->a;
76578         for(; i>0; i--, pItem++){
76579           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
76580         }
76581       }
76582       break;
76583     }
76584   }
76585   if( isAppropriateForFactoring(pExpr) ){
76586     int r1 = ++pParse->nMem;
76587     int r2;
76588     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76589     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
76590     pExpr->op2 = pExpr->op;
76591     pExpr->op = TK_REGISTER;
76592     pExpr->iTable = r2;
76593     return WRC_Prune;
76594   }
76595   return WRC_Continue;
76596 }
76597
76598 /*
76599 ** Preevaluate constant subexpressions within pExpr and store the
76600 ** results in registers.  Modify pExpr so that the constant subexpresions
76601 ** are TK_REGISTER opcodes that refer to the precomputed values.
76602 **
76603 ** This routine is a no-op if the jump to the cookie-check code has
76604 ** already occur.  Since the cookie-check jump is generated prior to
76605 ** any other serious processing, this check ensures that there is no
76606 ** way to accidently bypass the constant initializations.
76607 **
76608 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
76609 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
76610 ** interface.  This allows test logic to verify that the same answer is
76611 ** obtained for queries regardless of whether or not constants are
76612 ** precomputed into registers or if they are inserted in-line.
76613 */
76614 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
76615   Walker w;
76616   if( pParse->cookieGoto ) return;
76617   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
76618   w.xExprCallback = evalConstExpr;
76619   w.xSelectCallback = 0;
76620   w.pParse = pParse;
76621   sqlite3WalkExpr(&w, pExpr);
76622 }
76623
76624
76625 /*
76626 ** Generate code that pushes the value of every element of the given
76627 ** expression list into a sequence of registers beginning at target.
76628 **
76629 ** Return the number of elements evaluated.
76630 */
76631 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
76632   Parse *pParse,     /* Parsing context */
76633   ExprList *pList,   /* The expression list to be coded */
76634   int target,        /* Where to write results */
76635   int doHardCopy     /* Make a hard copy of every element */
76636 ){
76637   struct ExprList_item *pItem;
76638   int i, n;
76639   assert( pList!=0 );
76640   assert( target>0 );
76641   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
76642   n = pList->nExpr;
76643   for(pItem=pList->a, i=0; i<n; i++, pItem++){
76644     Expr *pExpr = pItem->pExpr;
76645     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
76646     if( inReg!=target+i ){
76647       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
76648                         inReg, target+i);
76649     }
76650   }
76651   return n;
76652 }
76653
76654 /*
76655 ** Generate code for a BETWEEN operator.
76656 **
76657 **    x BETWEEN y AND z
76658 **
76659 ** The above is equivalent to 
76660 **
76661 **    x>=y AND x<=z
76662 **
76663 ** Code it as such, taking care to do the common subexpression
76664 ** elementation of x.
76665 */
76666 static void exprCodeBetween(
76667   Parse *pParse,    /* Parsing and code generating context */
76668   Expr *pExpr,      /* The BETWEEN expression */
76669   int dest,         /* Jump here if the jump is taken */
76670   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
76671   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
76672 ){
76673   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
76674   Expr compLeft;    /* The  x>=y  term */
76675   Expr compRight;   /* The  x<=z  term */
76676   Expr exprX;       /* The  x  subexpression */
76677   int regFree1 = 0; /* Temporary use register */
76678
76679   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76680   exprX = *pExpr->pLeft;
76681   exprAnd.op = TK_AND;
76682   exprAnd.pLeft = &compLeft;
76683   exprAnd.pRight = &compRight;
76684   compLeft.op = TK_GE;
76685   compLeft.pLeft = &exprX;
76686   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
76687   compRight.op = TK_LE;
76688   compRight.pLeft = &exprX;
76689   compRight.pRight = pExpr->x.pList->a[1].pExpr;
76690   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
76691   exprX.op = TK_REGISTER;
76692   if( jumpIfTrue ){
76693     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
76694   }else{
76695     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
76696   }
76697   sqlite3ReleaseTempReg(pParse, regFree1);
76698
76699   /* Ensure adequate test coverage */
76700   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
76701   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
76702   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
76703   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
76704   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
76705   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
76706   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
76707   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
76708 }
76709
76710 /*
76711 ** Generate code for a boolean expression such that a jump is made
76712 ** to the label "dest" if the expression is true but execution
76713 ** continues straight thru if the expression is false.
76714 **
76715 ** If the expression evaluates to NULL (neither true nor false), then
76716 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
76717 **
76718 ** This code depends on the fact that certain token values (ex: TK_EQ)
76719 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
76720 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
76721 ** the make process cause these values to align.  Assert()s in the code
76722 ** below verify that the numbers are aligned correctly.
76723 */
76724 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76725   Vdbe *v = pParse->pVdbe;
76726   int op = 0;
76727   int regFree1 = 0;
76728   int regFree2 = 0;
76729   int r1, r2;
76730
76731   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76732   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
76733   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
76734   op = pExpr->op;
76735   switch( op ){
76736     case TK_AND: {
76737       int d2 = sqlite3VdbeMakeLabel(v);
76738       testcase( jumpIfNull==0 );
76739       sqlite3ExprCachePush(pParse);
76740       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
76741       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76742       sqlite3VdbeResolveLabel(v, d2);
76743       sqlite3ExprCachePop(pParse, 1);
76744       break;
76745     }
76746     case TK_OR: {
76747       testcase( jumpIfNull==0 );
76748       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76749       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76750       break;
76751     }
76752     case TK_NOT: {
76753       testcase( jumpIfNull==0 );
76754       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76755       break;
76756     }
76757     case TK_LT:
76758     case TK_LE:
76759     case TK_GT:
76760     case TK_GE:
76761     case TK_NE:
76762     case TK_EQ: {
76763       assert( TK_LT==OP_Lt );
76764       assert( TK_LE==OP_Le );
76765       assert( TK_GT==OP_Gt );
76766       assert( TK_GE==OP_Ge );
76767       assert( TK_EQ==OP_Eq );
76768       assert( TK_NE==OP_Ne );
76769       testcase( op==TK_LT );
76770       testcase( op==TK_LE );
76771       testcase( op==TK_GT );
76772       testcase( op==TK_GE );
76773       testcase( op==TK_EQ );
76774       testcase( op==TK_NE );
76775       testcase( jumpIfNull==0 );
76776       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76777       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76778       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76779                   r1, r2, dest, jumpIfNull);
76780       testcase( regFree1==0 );
76781       testcase( regFree2==0 );
76782       break;
76783     }
76784     case TK_IS:
76785     case TK_ISNOT: {
76786       testcase( op==TK_IS );
76787       testcase( op==TK_ISNOT );
76788       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76789       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76790       op = (op==TK_IS) ? TK_EQ : TK_NE;
76791       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76792                   r1, r2, dest, SQLITE_NULLEQ);
76793       testcase( regFree1==0 );
76794       testcase( regFree2==0 );
76795       break;
76796     }
76797     case TK_ISNULL:
76798     case TK_NOTNULL: {
76799       assert( TK_ISNULL==OP_IsNull );
76800       assert( TK_NOTNULL==OP_NotNull );
76801       testcase( op==TK_ISNULL );
76802       testcase( op==TK_NOTNULL );
76803       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76804       sqlite3VdbeAddOp2(v, op, r1, dest);
76805       testcase( regFree1==0 );
76806       break;
76807     }
76808     case TK_BETWEEN: {
76809       testcase( jumpIfNull==0 );
76810       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
76811       break;
76812     }
76813 #ifndef SQLITE_OMIT_SUBQUERY
76814     case TK_IN: {
76815       int destIfFalse = sqlite3VdbeMakeLabel(v);
76816       int destIfNull = jumpIfNull ? dest : destIfFalse;
76817       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76818       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
76819       sqlite3VdbeResolveLabel(v, destIfFalse);
76820       break;
76821     }
76822 #endif
76823     default: {
76824       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76825       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
76826       testcase( regFree1==0 );
76827       testcase( jumpIfNull==0 );
76828       break;
76829     }
76830   }
76831   sqlite3ReleaseTempReg(pParse, regFree1);
76832   sqlite3ReleaseTempReg(pParse, regFree2);  
76833 }
76834
76835 /*
76836 ** Generate code for a boolean expression such that a jump is made
76837 ** to the label "dest" if the expression is false but execution
76838 ** continues straight thru if the expression is true.
76839 **
76840 ** If the expression evaluates to NULL (neither true nor false) then
76841 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
76842 ** is 0.
76843 */
76844 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76845   Vdbe *v = pParse->pVdbe;
76846   int op = 0;
76847   int regFree1 = 0;
76848   int regFree2 = 0;
76849   int r1, r2;
76850
76851   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76852   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
76853   if( pExpr==0 )    return;
76854
76855   /* The value of pExpr->op and op are related as follows:
76856   **
76857   **       pExpr->op            op
76858   **       ---------          ----------
76859   **       TK_ISNULL          OP_NotNull
76860   **       TK_NOTNULL         OP_IsNull
76861   **       TK_NE              OP_Eq
76862   **       TK_EQ              OP_Ne
76863   **       TK_GT              OP_Le
76864   **       TK_LE              OP_Gt
76865   **       TK_GE              OP_Lt
76866   **       TK_LT              OP_Ge
76867   **
76868   ** For other values of pExpr->op, op is undefined and unused.
76869   ** The value of TK_ and OP_ constants are arranged such that we
76870   ** can compute the mapping above using the following expression.
76871   ** Assert()s verify that the computation is correct.
76872   */
76873   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
76874
76875   /* Verify correct alignment of TK_ and OP_ constants
76876   */
76877   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
76878   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
76879   assert( pExpr->op!=TK_NE || op==OP_Eq );
76880   assert( pExpr->op!=TK_EQ || op==OP_Ne );
76881   assert( pExpr->op!=TK_LT || op==OP_Ge );
76882   assert( pExpr->op!=TK_LE || op==OP_Gt );
76883   assert( pExpr->op!=TK_GT || op==OP_Le );
76884   assert( pExpr->op!=TK_GE || op==OP_Lt );
76885
76886   switch( pExpr->op ){
76887     case TK_AND: {
76888       testcase( jumpIfNull==0 );
76889       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76890       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76891       break;
76892     }
76893     case TK_OR: {
76894       int d2 = sqlite3VdbeMakeLabel(v);
76895       testcase( jumpIfNull==0 );
76896       sqlite3ExprCachePush(pParse);
76897       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
76898       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76899       sqlite3VdbeResolveLabel(v, d2);
76900       sqlite3ExprCachePop(pParse, 1);
76901       break;
76902     }
76903     case TK_NOT: {
76904       testcase( jumpIfNull==0 );
76905       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76906       break;
76907     }
76908     case TK_LT:
76909     case TK_LE:
76910     case TK_GT:
76911     case TK_GE:
76912     case TK_NE:
76913     case TK_EQ: {
76914       testcase( op==TK_LT );
76915       testcase( op==TK_LE );
76916       testcase( op==TK_GT );
76917       testcase( op==TK_GE );
76918       testcase( op==TK_EQ );
76919       testcase( op==TK_NE );
76920       testcase( jumpIfNull==0 );
76921       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76922       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76923       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76924                   r1, r2, dest, jumpIfNull);
76925       testcase( regFree1==0 );
76926       testcase( regFree2==0 );
76927       break;
76928     }
76929     case TK_IS:
76930     case TK_ISNOT: {
76931       testcase( pExpr->op==TK_IS );
76932       testcase( pExpr->op==TK_ISNOT );
76933       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76934       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76935       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
76936       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76937                   r1, r2, dest, SQLITE_NULLEQ);
76938       testcase( regFree1==0 );
76939       testcase( regFree2==0 );
76940       break;
76941     }
76942     case TK_ISNULL:
76943     case TK_NOTNULL: {
76944       testcase( op==TK_ISNULL );
76945       testcase( op==TK_NOTNULL );
76946       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76947       sqlite3VdbeAddOp2(v, op, r1, dest);
76948       testcase( regFree1==0 );
76949       break;
76950     }
76951     case TK_BETWEEN: {
76952       testcase( jumpIfNull==0 );
76953       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
76954       break;
76955     }
76956 #ifndef SQLITE_OMIT_SUBQUERY
76957     case TK_IN: {
76958       if( jumpIfNull ){
76959         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
76960       }else{
76961         int destIfNull = sqlite3VdbeMakeLabel(v);
76962         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
76963         sqlite3VdbeResolveLabel(v, destIfNull);
76964       }
76965       break;
76966     }
76967 #endif
76968     default: {
76969       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76970       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
76971       testcase( regFree1==0 );
76972       testcase( jumpIfNull==0 );
76973       break;
76974     }
76975   }
76976   sqlite3ReleaseTempReg(pParse, regFree1);
76977   sqlite3ReleaseTempReg(pParse, regFree2);
76978 }
76979
76980 /*
76981 ** Do a deep comparison of two expression trees.  Return 0 if the two
76982 ** expressions are completely identical.  Return 1 if they differ only
76983 ** by a COLLATE operator at the top level.  Return 2 if there are differences
76984 ** other than the top-level COLLATE operator.
76985 **
76986 ** Sometimes this routine will return 2 even if the two expressions
76987 ** really are equivalent.  If we cannot prove that the expressions are
76988 ** identical, we return 2 just to be safe.  So if this routine
76989 ** returns 2, then you do not really know for certain if the two
76990 ** expressions are the same.  But if you get a 0 or 1 return, then you
76991 ** can be sure the expressions are the same.  In the places where
76992 ** this routine is used, it does not hurt to get an extra 2 - that
76993 ** just might result in some slightly slower code.  But returning
76994 ** an incorrect 0 or 1 could lead to a malfunction.
76995 */
76996 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
76997   if( pA==0||pB==0 ){
76998     return pB==pA ? 0 : 2;
76999   }
77000   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77001   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77002   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77003     return 2;
77004   }
77005   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77006   if( pA->op!=pB->op ) return 2;
77007   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77008   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77009   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77010   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77011   if( ExprHasProperty(pA, EP_IntValue) ){
77012     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77013       return 2;
77014     }
77015   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
77016     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77017     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77018       return 2;
77019     }
77020   }
77021   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
77022   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
77023   return 0;
77024 }
77025
77026 /*
77027 ** Compare two ExprList objects.  Return 0 if they are identical and 
77028 ** non-zero if they differ in any way.
77029 **
77030 ** This routine might return non-zero for equivalent ExprLists.  The
77031 ** only consequence will be disabled optimizations.  But this routine
77032 ** must never return 0 if the two ExprList objects are different, or
77033 ** a malfunction will result.
77034 **
77035 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77036 ** always differs from a non-NULL pointer.
77037 */
77038 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
77039   int i;
77040   if( pA==0 && pB==0 ) return 0;
77041   if( pA==0 || pB==0 ) return 1;
77042   if( pA->nExpr!=pB->nExpr ) return 1;
77043   for(i=0; i<pA->nExpr; i++){
77044     Expr *pExprA = pA->a[i].pExpr;
77045     Expr *pExprB = pB->a[i].pExpr;
77046     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77047     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
77048   }
77049   return 0;
77050 }
77051
77052 /*
77053 ** An instance of the following structure is used by the tree walker
77054 ** to count references to table columns in the arguments of an 
77055 ** aggregate function, in order to implement the
77056 ** sqlite3FunctionThisSrc() routine.
77057 */
77058 struct SrcCount {
77059   SrcList *pSrc;   /* One particular FROM clause in a nested query */
77060   int nThis;       /* Number of references to columns in pSrcList */
77061   int nOther;      /* Number of references to columns in other FROM clauses */
77062 };
77063
77064 /*
77065 ** Count the number of references to columns.
77066 */
77067 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
77068   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
77069   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
77070   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
77071   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
77072   ** NEVER() will need to be removed. */
77073   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
77074     int i;
77075     struct SrcCount *p = pWalker->u.pSrcCount;
77076     SrcList *pSrc = p->pSrc;
77077     for(i=0; i<pSrc->nSrc; i++){
77078       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
77079     }
77080     if( i<pSrc->nSrc ){
77081       p->nThis++;
77082     }else{
77083       p->nOther++;
77084     }
77085   }
77086   return WRC_Continue;
77087 }
77088
77089 /*
77090 ** Determine if any of the arguments to the pExpr Function reference
77091 ** pSrcList.  Return true if they do.  Also return true if the function
77092 ** has no arguments or has only constant arguments.  Return false if pExpr
77093 ** references columns but not columns of tables found in pSrcList.
77094 */
77095 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
77096   Walker w;
77097   struct SrcCount cnt;
77098   assert( pExpr->op==TK_AGG_FUNCTION );
77099   memset(&w, 0, sizeof(w));
77100   w.xExprCallback = exprSrcCount;
77101   w.u.pSrcCount = &cnt;
77102   cnt.pSrc = pSrcList;
77103   cnt.nThis = 0;
77104   cnt.nOther = 0;
77105   sqlite3WalkExprList(&w, pExpr->x.pList);
77106   return cnt.nThis>0 || cnt.nOther==0;
77107 }
77108
77109 /*
77110 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77111 ** the new element.  Return a negative number if malloc fails.
77112 */
77113 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
77114   int i;
77115   pInfo->aCol = sqlite3ArrayAllocate(
77116        db,
77117        pInfo->aCol,
77118        sizeof(pInfo->aCol[0]),
77119        &pInfo->nColumn,
77120        &i
77121   );
77122   return i;
77123 }    
77124
77125 /*
77126 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77127 ** the new element.  Return a negative number if malloc fails.
77128 */
77129 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
77130   int i;
77131   pInfo->aFunc = sqlite3ArrayAllocate(
77132        db, 
77133        pInfo->aFunc,
77134        sizeof(pInfo->aFunc[0]),
77135        &pInfo->nFunc,
77136        &i
77137   );
77138   return i;
77139 }    
77140
77141 /*
77142 ** This is the xExprCallback for a tree walker.  It is used to
77143 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
77144 ** for additional information.
77145 */
77146 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77147   int i;
77148   NameContext *pNC = pWalker->u.pNC;
77149   Parse *pParse = pNC->pParse;
77150   SrcList *pSrcList = pNC->pSrcList;
77151   AggInfo *pAggInfo = pNC->pAggInfo;
77152
77153   switch( pExpr->op ){
77154     case TK_AGG_COLUMN:
77155     case TK_COLUMN: {
77156       testcase( pExpr->op==TK_AGG_COLUMN );
77157       testcase( pExpr->op==TK_COLUMN );
77158       /* Check to see if the column is in one of the tables in the FROM
77159       ** clause of the aggregate query */
77160       if( ALWAYS(pSrcList!=0) ){
77161         struct SrcList_item *pItem = pSrcList->a;
77162         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77163           struct AggInfo_col *pCol;
77164           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77165           if( pExpr->iTable==pItem->iCursor ){
77166             /* If we reach this point, it means that pExpr refers to a table
77167             ** that is in the FROM clause of the aggregate query.  
77168             **
77169             ** Make an entry for the column in pAggInfo->aCol[] if there
77170             ** is not an entry there already.
77171             */
77172             int k;
77173             pCol = pAggInfo->aCol;
77174             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77175               if( pCol->iTable==pExpr->iTable &&
77176                   pCol->iColumn==pExpr->iColumn ){
77177                 break;
77178               }
77179             }
77180             if( (k>=pAggInfo->nColumn)
77181              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
77182             ){
77183               pCol = &pAggInfo->aCol[k];
77184               pCol->pTab = pExpr->pTab;
77185               pCol->iTable = pExpr->iTable;
77186               pCol->iColumn = pExpr->iColumn;
77187               pCol->iMem = ++pParse->nMem;
77188               pCol->iSorterColumn = -1;
77189               pCol->pExpr = pExpr;
77190               if( pAggInfo->pGroupBy ){
77191                 int j, n;
77192                 ExprList *pGB = pAggInfo->pGroupBy;
77193                 struct ExprList_item *pTerm = pGB->a;
77194                 n = pGB->nExpr;
77195                 for(j=0; j<n; j++, pTerm++){
77196                   Expr *pE = pTerm->pExpr;
77197                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77198                       pE->iColumn==pExpr->iColumn ){
77199                     pCol->iSorterColumn = j;
77200                     break;
77201                   }
77202                 }
77203               }
77204               if( pCol->iSorterColumn<0 ){
77205                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
77206               }
77207             }
77208             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
77209             ** because it was there before or because we just created it).
77210             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
77211             ** pAggInfo->aCol[] entry.
77212             */
77213             ExprSetIrreducible(pExpr);
77214             pExpr->pAggInfo = pAggInfo;
77215             pExpr->op = TK_AGG_COLUMN;
77216             pExpr->iAgg = (i16)k;
77217             break;
77218           } /* endif pExpr->iTable==pItem->iCursor */
77219         } /* end loop over pSrcList */
77220       }
77221       return WRC_Prune;
77222     }
77223     case TK_AGG_FUNCTION: {
77224       if( (pNC->ncFlags & NC_InAggFunc)==0
77225        && pWalker->walkerDepth==pExpr->op2
77226       ){
77227         /* Check to see if pExpr is a duplicate of another aggregate 
77228         ** function that is already in the pAggInfo structure
77229         */
77230         struct AggInfo_func *pItem = pAggInfo->aFunc;
77231         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
77232           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
77233             break;
77234           }
77235         }
77236         if( i>=pAggInfo->nFunc ){
77237           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
77238           */
77239           u8 enc = ENC(pParse->db);
77240           i = addAggInfoFunc(pParse->db, pAggInfo);
77241           if( i>=0 ){
77242             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77243             pItem = &pAggInfo->aFunc[i];
77244             pItem->pExpr = pExpr;
77245             pItem->iMem = ++pParse->nMem;
77246             assert( !ExprHasProperty(pExpr, EP_IntValue) );
77247             pItem->pFunc = sqlite3FindFunction(pParse->db,
77248                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
77249                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
77250             if( pExpr->flags & EP_Distinct ){
77251               pItem->iDistinct = pParse->nTab++;
77252             }else{
77253               pItem->iDistinct = -1;
77254             }
77255           }
77256         }
77257         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
77258         */
77259         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77260         ExprSetIrreducible(pExpr);
77261         pExpr->iAgg = (i16)i;
77262         pExpr->pAggInfo = pAggInfo;
77263       }
77264       return WRC_Prune;
77265     }
77266   }
77267   return WRC_Continue;
77268 }
77269 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
77270   UNUSED_PARAMETER(pWalker);
77271   UNUSED_PARAMETER(pSelect);
77272   return WRC_Continue;
77273 }
77274
77275 /*
77276 ** Analyze the given expression looking for aggregate functions and
77277 ** for variables that need to be added to the pParse->aAgg[] array.
77278 ** Make additional entries to the pParse->aAgg[] array as necessary.
77279 **
77280 ** This routine should only be called after the expression has been
77281 ** analyzed by sqlite3ResolveExprNames().
77282 */
77283 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
77284   Walker w;
77285   memset(&w, 0, sizeof(w));
77286   w.xExprCallback = analyzeAggregate;
77287   w.xSelectCallback = analyzeAggregatesInSelect;
77288   w.u.pNC = pNC;
77289   assert( pNC->pSrcList!=0 );
77290   sqlite3WalkExpr(&w, pExpr);
77291 }
77292
77293 /*
77294 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
77295 ** expression list.  Return the number of errors.
77296 **
77297 ** If an error is found, the analysis is cut short.
77298 */
77299 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
77300   struct ExprList_item *pItem;
77301   int i;
77302   if( pList ){
77303     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
77304       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
77305     }
77306   }
77307 }
77308
77309 /*
77310 ** Allocate a single new register for use to hold some intermediate result.
77311 */
77312 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
77313   if( pParse->nTempReg==0 ){
77314     return ++pParse->nMem;
77315   }
77316   return pParse->aTempReg[--pParse->nTempReg];
77317 }
77318
77319 /*
77320 ** Deallocate a register, making available for reuse for some other
77321 ** purpose.
77322 **
77323 ** If a register is currently being used by the column cache, then
77324 ** the dallocation is deferred until the column cache line that uses
77325 ** the register becomes stale.
77326 */
77327 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
77328   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77329     int i;
77330     struct yColCache *p;
77331     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77332       if( p->iReg==iReg ){
77333         p->tempReg = 1;
77334         return;
77335       }
77336     }
77337     pParse->aTempReg[pParse->nTempReg++] = iReg;
77338   }
77339 }
77340
77341 /*
77342 ** Allocate or deallocate a block of nReg consecutive registers
77343 */
77344 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
77345   int i, n;
77346   i = pParse->iRangeReg;
77347   n = pParse->nRangeReg;
77348   if( nReg<=n ){
77349     assert( !usedAsColumnCache(pParse, i, i+n-1) );
77350     pParse->iRangeReg += nReg;
77351     pParse->nRangeReg -= nReg;
77352   }else{
77353     i = pParse->nMem+1;
77354     pParse->nMem += nReg;
77355   }
77356   return i;
77357 }
77358 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
77359   sqlite3ExprCacheRemove(pParse, iReg, nReg);
77360   if( nReg>pParse->nRangeReg ){
77361     pParse->nRangeReg = nReg;
77362     pParse->iRangeReg = iReg;
77363   }
77364 }
77365
77366 /*
77367 ** Mark all temporary registers as being unavailable for reuse.
77368 */
77369 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
77370   pParse->nTempReg = 0;
77371   pParse->nRangeReg = 0;
77372 }
77373
77374 /************** End of expr.c ************************************************/
77375 /************** Begin file alter.c *******************************************/
77376 /*
77377 ** 2005 February 15
77378 **
77379 ** The author disclaims copyright to this source code.  In place of
77380 ** a legal notice, here is a blessing:
77381 **
77382 **    May you do good and not evil.
77383 **    May you find forgiveness for yourself and forgive others.
77384 **    May you share freely, never taking more than you give.
77385 **
77386 *************************************************************************
77387 ** This file contains C code routines that used to generate VDBE code
77388 ** that implements the ALTER TABLE command.
77389 */
77390
77391 /*
77392 ** The code in this file only exists if we are not omitting the
77393 ** ALTER TABLE logic from the build.
77394 */
77395 #ifndef SQLITE_OMIT_ALTERTABLE
77396
77397
77398 /*
77399 ** This function is used by SQL generated to implement the 
77400 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
77401 ** CREATE INDEX command. The second is a table name. The table name in 
77402 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
77403 ** argument and the result returned. Examples:
77404 **
77405 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
77406 **     -> 'CREATE TABLE def(a, b, c)'
77407 **
77408 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
77409 **     -> 'CREATE INDEX i ON def(a, b, c)'
77410 */
77411 static void renameTableFunc(
77412   sqlite3_context *context,
77413   int NotUsed,
77414   sqlite3_value **argv
77415 ){
77416   unsigned char const *zSql = sqlite3_value_text(argv[0]);
77417   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
77418
77419   int token;
77420   Token tname;
77421   unsigned char const *zCsr = zSql;
77422   int len = 0;
77423   char *zRet;
77424
77425   sqlite3 *db = sqlite3_context_db_handle(context);
77426
77427   UNUSED_PARAMETER(NotUsed);
77428
77429   /* The principle used to locate the table name in the CREATE TABLE 
77430   ** statement is that the table name is the first non-space token that
77431   ** is immediately followed by a TK_LP or TK_USING token.
77432   */
77433   if( zSql ){
77434     do {
77435       if( !*zCsr ){
77436         /* Ran out of input before finding an opening bracket. Return NULL. */
77437         return;
77438       }
77439
77440       /* Store the token that zCsr points to in tname. */
77441       tname.z = (char*)zCsr;
77442       tname.n = len;
77443
77444       /* Advance zCsr to the next token. Store that token type in 'token',
77445       ** and its length in 'len' (to be used next iteration of this loop).
77446       */
77447       do {
77448         zCsr += len;
77449         len = sqlite3GetToken(zCsr, &token);
77450       } while( token==TK_SPACE );
77451       assert( len>0 );
77452     } while( token!=TK_LP && token!=TK_USING );
77453
77454     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
77455        zTableName, tname.z+tname.n);
77456     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
77457   }
77458 }
77459
77460 /*
77461 ** This C function implements an SQL user function that is used by SQL code
77462 ** generated by the ALTER TABLE ... RENAME command to modify the definition
77463 ** of any foreign key constraints that use the table being renamed as the 
77464 ** parent table. It is passed three arguments:
77465 **
77466 **   1) The complete text of the CREATE TABLE statement being modified,
77467 **   2) The old name of the table being renamed, and
77468 **   3) The new name of the table being renamed.
77469 **
77470 ** It returns the new CREATE TABLE statement. For example:
77471 **
77472 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
77473 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
77474 */
77475 #ifndef SQLITE_OMIT_FOREIGN_KEY
77476 static void renameParentFunc(
77477   sqlite3_context *context,
77478   int NotUsed,
77479   sqlite3_value **argv
77480 ){
77481   sqlite3 *db = sqlite3_context_db_handle(context);
77482   char *zOutput = 0;
77483   char *zResult;
77484   unsigned char const *zInput = sqlite3_value_text(argv[0]);
77485   unsigned char const *zOld = sqlite3_value_text(argv[1]);
77486   unsigned char const *zNew = sqlite3_value_text(argv[2]);
77487
77488   unsigned const char *z;         /* Pointer to token */
77489   int n;                          /* Length of token z */
77490   int token;                      /* Type of token */
77491
77492   UNUSED_PARAMETER(NotUsed);
77493   for(z=zInput; *z; z=z+n){
77494     n = sqlite3GetToken(z, &token);
77495     if( token==TK_REFERENCES ){
77496       char *zParent;
77497       do {
77498         z += n;
77499         n = sqlite3GetToken(z, &token);
77500       }while( token==TK_SPACE );
77501
77502       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
77503       if( zParent==0 ) break;
77504       sqlite3Dequote(zParent);
77505       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
77506         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
77507             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
77508         );
77509         sqlite3DbFree(db, zOutput);
77510         zOutput = zOut;
77511         zInput = &z[n];
77512       }
77513       sqlite3DbFree(db, zParent);
77514     }
77515   }
77516
77517   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
77518   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
77519   sqlite3DbFree(db, zOutput);
77520 }
77521 #endif
77522
77523 #ifndef SQLITE_OMIT_TRIGGER
77524 /* This function is used by SQL generated to implement the
77525 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
77526 ** statement. The second is a table name. The table name in the CREATE 
77527 ** TRIGGER statement is replaced with the third argument and the result 
77528 ** returned. This is analagous to renameTableFunc() above, except for CREATE
77529 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
77530 */
77531 static void renameTriggerFunc(
77532   sqlite3_context *context,
77533   int NotUsed,
77534   sqlite3_value **argv
77535 ){
77536   unsigned char const *zSql = sqlite3_value_text(argv[0]);
77537   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
77538
77539   int token;
77540   Token tname;
77541   int dist = 3;
77542   unsigned char const *zCsr = zSql;
77543   int len = 0;
77544   char *zRet;
77545   sqlite3 *db = sqlite3_context_db_handle(context);
77546
77547   UNUSED_PARAMETER(NotUsed);
77548
77549   /* The principle used to locate the table name in the CREATE TRIGGER 
77550   ** statement is that the table name is the first token that is immediatedly
77551   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
77552   ** of TK_WHEN, TK_BEGIN or TK_FOR.
77553   */
77554   if( zSql ){
77555     do {
77556
77557       if( !*zCsr ){
77558         /* Ran out of input before finding the table name. Return NULL. */
77559         return;
77560       }
77561
77562       /* Store the token that zCsr points to in tname. */
77563       tname.z = (char*)zCsr;
77564       tname.n = len;
77565
77566       /* Advance zCsr to the next token. Store that token type in 'token',
77567       ** and its length in 'len' (to be used next iteration of this loop).
77568       */
77569       do {
77570         zCsr += len;
77571         len = sqlite3GetToken(zCsr, &token);
77572       }while( token==TK_SPACE );
77573       assert( len>0 );
77574
77575       /* Variable 'dist' stores the number of tokens read since the most
77576       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
77577       ** token is read and 'dist' equals 2, the condition stated above
77578       ** to be met.
77579       **
77580       ** Note that ON cannot be a database, table or column name, so
77581       ** there is no need to worry about syntax like 
77582       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
77583       */
77584       dist++;
77585       if( token==TK_DOT || token==TK_ON ){
77586         dist = 0;
77587       }
77588     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
77589
77590     /* Variable tname now contains the token that is the old table-name
77591     ** in the CREATE TRIGGER statement.
77592     */
77593     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
77594        zTableName, tname.z+tname.n);
77595     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
77596   }
77597 }
77598 #endif   /* !SQLITE_OMIT_TRIGGER */
77599
77600 /*
77601 ** Register built-in functions used to help implement ALTER TABLE
77602 */
77603 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
77604   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
77605     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
77606 #ifndef SQLITE_OMIT_TRIGGER
77607     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
77608 #endif
77609 #ifndef SQLITE_OMIT_FOREIGN_KEY
77610     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
77611 #endif
77612   };
77613   int i;
77614   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
77615   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
77616
77617   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
77618     sqlite3FuncDefInsert(pHash, &aFunc[i]);
77619   }
77620 }
77621
77622 /*
77623 ** This function is used to create the text of expressions of the form:
77624 **
77625 **   name=<constant1> OR name=<constant2> OR ...
77626 **
77627 ** If argument zWhere is NULL, then a pointer string containing the text 
77628 ** "name=<constant>" is returned, where <constant> is the quoted version
77629 ** of the string passed as argument zConstant. The returned buffer is
77630 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
77631 ** caller to ensure that it is eventually freed.
77632 **
77633 ** If argument zWhere is not NULL, then the string returned is 
77634 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
77635 ** In this case zWhere is passed to sqlite3DbFree() before returning.
77636 ** 
77637 */
77638 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
77639   char *zNew;
77640   if( !zWhere ){
77641     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
77642   }else{
77643     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
77644     sqlite3DbFree(db, zWhere);
77645   }
77646   return zNew;
77647 }
77648
77649 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77650 /*
77651 ** Generate the text of a WHERE expression which can be used to select all
77652 ** tables that have foreign key constraints that refer to table pTab (i.e.
77653 ** constraints for which pTab is the parent table) from the sqlite_master
77654 ** table.
77655 */
77656 static char *whereForeignKeys(Parse *pParse, Table *pTab){
77657   FKey *p;
77658   char *zWhere = 0;
77659   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
77660     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
77661   }
77662   return zWhere;
77663 }
77664 #endif
77665
77666 /*
77667 ** Generate the text of a WHERE expression which can be used to select all
77668 ** temporary triggers on table pTab from the sqlite_temp_master table. If
77669 ** table pTab has no temporary triggers, or is itself stored in the 
77670 ** temporary database, NULL is returned.
77671 */
77672 static char *whereTempTriggers(Parse *pParse, Table *pTab){
77673   Trigger *pTrig;
77674   char *zWhere = 0;
77675   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
77676
77677   /* If the table is not located in the temp-db (in which case NULL is 
77678   ** returned, loop through the tables list of triggers. For each trigger
77679   ** that is not part of the temp-db schema, add a clause to the WHERE 
77680   ** expression being built up in zWhere.
77681   */
77682   if( pTab->pSchema!=pTempSchema ){
77683     sqlite3 *db = pParse->db;
77684     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
77685       if( pTrig->pSchema==pTempSchema ){
77686         zWhere = whereOrName(db, zWhere, pTrig->zName);
77687       }
77688     }
77689   }
77690   if( zWhere ){
77691     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
77692     sqlite3DbFree(pParse->db, zWhere);
77693     zWhere = zNew;
77694   }
77695   return zWhere;
77696 }
77697
77698 /*
77699 ** Generate code to drop and reload the internal representation of table
77700 ** pTab from the database, including triggers and temporary triggers.
77701 ** Argument zName is the name of the table in the database schema at
77702 ** the time the generated code is executed. This can be different from
77703 ** pTab->zName if this function is being called to code part of an 
77704 ** "ALTER TABLE RENAME TO" statement.
77705 */
77706 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
77707   Vdbe *v;
77708   char *zWhere;
77709   int iDb;                   /* Index of database containing pTab */
77710 #ifndef SQLITE_OMIT_TRIGGER
77711   Trigger *pTrig;
77712 #endif
77713
77714   v = sqlite3GetVdbe(pParse);
77715   if( NEVER(v==0) ) return;
77716   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77717   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77718   assert( iDb>=0 );
77719
77720 #ifndef SQLITE_OMIT_TRIGGER
77721   /* Drop any table triggers from the internal schema. */
77722   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
77723     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
77724     assert( iTrigDb==iDb || iTrigDb==1 );
77725     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
77726   }
77727 #endif
77728
77729   /* Drop the table and index from the internal schema.  */
77730   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
77731
77732   /* Reload the table, index and permanent trigger schemas. */
77733   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
77734   if( !zWhere ) return;
77735   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
77736
77737 #ifndef SQLITE_OMIT_TRIGGER
77738   /* Now, if the table is not stored in the temp database, reload any temp 
77739   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
77740   */
77741   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77742     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
77743   }
77744 #endif
77745 }
77746
77747 /*
77748 ** Parameter zName is the name of a table that is about to be altered
77749 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
77750 ** If the table is a system table, this function leaves an error message
77751 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
77752 **
77753 ** Or, if zName is not a system table, zero is returned.
77754 */
77755 static int isSystemTable(Parse *pParse, const char *zName){
77756   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77757     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
77758     return 1;
77759   }
77760   return 0;
77761 }
77762
77763 /*
77764 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
77765 ** command. 
77766 */
77767 SQLITE_PRIVATE void sqlite3AlterRenameTable(
77768   Parse *pParse,            /* Parser context. */
77769   SrcList *pSrc,            /* The table to rename. */
77770   Token *pName              /* The new table name. */
77771 ){
77772   int iDb;                  /* Database that contains the table */
77773   char *zDb;                /* Name of database iDb */
77774   Table *pTab;              /* Table being renamed */
77775   char *zName = 0;          /* NULL-terminated version of pName */ 
77776   sqlite3 *db = pParse->db; /* Database connection */
77777   int nTabName;             /* Number of UTF-8 characters in zTabName */
77778   const char *zTabName;     /* Original name of the table */
77779   Vdbe *v;
77780 #ifndef SQLITE_OMIT_TRIGGER
77781   char *zWhere = 0;         /* Where clause to locate temp triggers */
77782 #endif
77783   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
77784   int savedDbFlags;         /* Saved value of db->flags */
77785
77786   savedDbFlags = db->flags;  
77787   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
77788   assert( pSrc->nSrc==1 );
77789   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77790
77791   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
77792   if( !pTab ) goto exit_rename_table;
77793   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77794   zDb = db->aDb[iDb].zName;
77795   db->flags |= SQLITE_PreferBuiltin;
77796
77797   /* Get a NULL terminated version of the new table name. */
77798   zName = sqlite3NameFromToken(db, pName);
77799   if( !zName ) goto exit_rename_table;
77800
77801   /* Check that a table or index named 'zName' does not already exist
77802   ** in database iDb. If so, this is an error.
77803   */
77804   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
77805     sqlite3ErrorMsg(pParse, 
77806         "there is already another table or index with this name: %s", zName);
77807     goto exit_rename_table;
77808   }
77809
77810   /* Make sure it is not a system table being altered, or a reserved name
77811   ** that the table is being renamed to.
77812   */
77813   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
77814     goto exit_rename_table;
77815   }
77816   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
77817     exit_rename_table;
77818   }
77819
77820 #ifndef SQLITE_OMIT_VIEW
77821   if( pTab->pSelect ){
77822     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
77823     goto exit_rename_table;
77824   }
77825 #endif
77826
77827 #ifndef SQLITE_OMIT_AUTHORIZATION
77828   /* Invoke the authorization callback. */
77829   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
77830     goto exit_rename_table;
77831   }
77832 #endif
77833
77834 #ifndef SQLITE_OMIT_VIRTUALTABLE
77835   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
77836     goto exit_rename_table;
77837   }
77838   if( IsVirtual(pTab) ){
77839     pVTab = sqlite3GetVTable(db, pTab);
77840     if( pVTab->pVtab->pModule->xRename==0 ){
77841       pVTab = 0;
77842     }
77843   }
77844 #endif
77845
77846   /* Begin a transaction and code the VerifyCookie for database iDb. 
77847   ** Then modify the schema cookie (since the ALTER TABLE modifies the
77848   ** schema). Open a statement transaction if the table is a virtual
77849   ** table.
77850   */
77851   v = sqlite3GetVdbe(pParse);
77852   if( v==0 ){
77853     goto exit_rename_table;
77854   }
77855   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
77856   sqlite3ChangeCookie(pParse, iDb);
77857
77858   /* If this is a virtual table, invoke the xRename() function if
77859   ** one is defined. The xRename() callback will modify the names
77860   ** of any resources used by the v-table implementation (including other
77861   ** SQLite tables) that are identified by the name of the virtual table.
77862   */
77863 #ifndef SQLITE_OMIT_VIRTUALTABLE
77864   if( pVTab ){
77865     int i = ++pParse->nMem;
77866     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
77867     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
77868     sqlite3MayAbort(pParse);
77869   }
77870 #endif
77871
77872   /* figure out how many UTF-8 characters are in zName */
77873   zTabName = pTab->zName;
77874   nTabName = sqlite3Utf8CharLen(zTabName, -1);
77875
77876 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77877   if( db->flags&SQLITE_ForeignKeys ){
77878     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
77879     ** statements corresponding to all child tables of foreign key constraints
77880     ** for which the renamed table is the parent table.  */
77881     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
77882       sqlite3NestedParse(pParse, 
77883           "UPDATE \"%w\".%s SET "
77884               "sql = sqlite_rename_parent(sql, %Q, %Q) "
77885               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
77886       sqlite3DbFree(db, zWhere);
77887     }
77888   }
77889 #endif
77890
77891   /* Modify the sqlite_master table to use the new table name. */
77892   sqlite3NestedParse(pParse,
77893       "UPDATE %Q.%s SET "
77894 #ifdef SQLITE_OMIT_TRIGGER
77895           "sql = sqlite_rename_table(sql, %Q), "
77896 #else
77897           "sql = CASE "
77898             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
77899             "ELSE sqlite_rename_table(sql, %Q) END, "
77900 #endif
77901           "tbl_name = %Q, "
77902           "name = CASE "
77903             "WHEN type='table' THEN %Q "
77904             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
77905              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
77906             "ELSE name END "
77907       "WHERE tbl_name=%Q COLLATE nocase AND "
77908           "(type='table' OR type='index' OR type='trigger');", 
77909       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
77910 #ifndef SQLITE_OMIT_TRIGGER
77911       zName,
77912 #endif
77913       zName, nTabName, zTabName
77914   );
77915
77916 #ifndef SQLITE_OMIT_AUTOINCREMENT
77917   /* If the sqlite_sequence table exists in this database, then update 
77918   ** it with the new table name.
77919   */
77920   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
77921     sqlite3NestedParse(pParse,
77922         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
77923         zDb, zName, pTab->zName);
77924   }
77925 #endif
77926
77927 #ifndef SQLITE_OMIT_TRIGGER
77928   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
77929   ** table. Don't do this if the table being ALTERed is itself located in
77930   ** the temp database.
77931   */
77932   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77933     sqlite3NestedParse(pParse, 
77934         "UPDATE sqlite_temp_master SET "
77935             "sql = sqlite_rename_trigger(sql, %Q), "
77936             "tbl_name = %Q "
77937             "WHERE %s;", zName, zName, zWhere);
77938     sqlite3DbFree(db, zWhere);
77939   }
77940 #endif
77941
77942 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77943   if( db->flags&SQLITE_ForeignKeys ){
77944     FKey *p;
77945     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
77946       Table *pFrom = p->pFrom;
77947       if( pFrom!=pTab ){
77948         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
77949       }
77950     }
77951   }
77952 #endif
77953
77954   /* Drop and reload the internal table schema. */
77955   reloadTableSchema(pParse, pTab, zName);
77956
77957 exit_rename_table:
77958   sqlite3SrcListDelete(db, pSrc);
77959   sqlite3DbFree(db, zName);
77960   db->flags = savedDbFlags;
77961 }
77962
77963
77964 /*
77965 ** Generate code to make sure the file format number is at least minFormat.
77966 ** The generated code will increase the file format number if necessary.
77967 */
77968 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
77969   Vdbe *v;
77970   v = sqlite3GetVdbe(pParse);
77971   /* The VDBE should have been allocated before this routine is called.
77972   ** If that allocation failed, we would have quit before reaching this
77973   ** point */
77974   if( ALWAYS(v) ){
77975     int r1 = sqlite3GetTempReg(pParse);
77976     int r2 = sqlite3GetTempReg(pParse);
77977     int j1;
77978     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
77979     sqlite3VdbeUsesBtree(v, iDb);
77980     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
77981     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
77982     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
77983     sqlite3VdbeJumpHere(v, j1);
77984     sqlite3ReleaseTempReg(pParse, r1);
77985     sqlite3ReleaseTempReg(pParse, r2);
77986   }
77987 }
77988
77989 /*
77990 ** This function is called after an "ALTER TABLE ... ADD" statement
77991 ** has been parsed. Argument pColDef contains the text of the new
77992 ** column definition.
77993 **
77994 ** The Table structure pParse->pNewTable was extended to include
77995 ** the new column during parsing.
77996 */
77997 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
77998   Table *pNew;              /* Copy of pParse->pNewTable */
77999   Table *pTab;              /* Table being altered */
78000   int iDb;                  /* Database number */
78001   const char *zDb;          /* Database name */
78002   const char *zTab;         /* Table name */
78003   char *zCol;               /* Null-terminated column definition */
78004   Column *pCol;             /* The new column */
78005   Expr *pDflt;              /* Default value for the new column */
78006   sqlite3 *db;              /* The database connection; */
78007
78008   db = pParse->db;
78009   if( pParse->nErr || db->mallocFailed ) return;
78010   pNew = pParse->pNewTable;
78011   assert( pNew );
78012
78013   assert( sqlite3BtreeHoldsAllMutexes(db) );
78014   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
78015   zDb = db->aDb[iDb].zName;
78016   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
78017   pCol = &pNew->aCol[pNew->nCol-1];
78018   pDflt = pCol->pDflt;
78019   pTab = sqlite3FindTable(db, zTab, zDb);
78020   assert( pTab );
78021
78022 #ifndef SQLITE_OMIT_AUTHORIZATION
78023   /* Invoke the authorization callback. */
78024   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78025     return;
78026   }
78027 #endif
78028
78029   /* If the default value for the new column was specified with a 
78030   ** literal NULL, then set pDflt to 0. This simplifies checking
78031   ** for an SQL NULL default below.
78032   */
78033   if( pDflt && pDflt->op==TK_NULL ){
78034     pDflt = 0;
78035   }
78036
78037   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78038   ** If there is a NOT NULL constraint, then the default value for the
78039   ** column must not be NULL.
78040   */
78041   if( pCol->isPrimKey ){
78042     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78043     return;
78044   }
78045   if( pNew->pIndex ){
78046     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78047     return;
78048   }
78049   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
78050     sqlite3ErrorMsg(pParse, 
78051         "Cannot add a REFERENCES column with non-NULL default value");
78052     return;
78053   }
78054   if( pCol->notNull && !pDflt ){
78055     sqlite3ErrorMsg(pParse, 
78056         "Cannot add a NOT NULL column with default value NULL");
78057     return;
78058   }
78059
78060   /* Ensure the default expression is something that sqlite3ValueFromExpr()
78061   ** can handle (i.e. not CURRENT_TIME etc.)
78062   */
78063   if( pDflt ){
78064     sqlite3_value *pVal;
78065     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
78066       db->mallocFailed = 1;
78067       return;
78068     }
78069     if( !pVal ){
78070       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78071       return;
78072     }
78073     sqlite3ValueFree(pVal);
78074   }
78075
78076   /* Modify the CREATE TABLE statement. */
78077   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78078   if( zCol ){
78079     char *zEnd = &zCol[pColDef->n-1];
78080     int savedDbFlags = db->flags;
78081     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
78082       *zEnd-- = '\0';
78083     }
78084     db->flags |= SQLITE_PreferBuiltin;
78085     sqlite3NestedParse(pParse, 
78086         "UPDATE \"%w\".%s SET "
78087           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78088         "WHERE type = 'table' AND name = %Q", 
78089       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78090       zTab
78091     );
78092     sqlite3DbFree(db, zCol);
78093     db->flags = savedDbFlags;
78094   }
78095
78096   /* If the default value of the new column is NULL, then set the file
78097   ** format to 2. If the default value of the new column is not NULL,
78098   ** the file format becomes 3.
78099   */
78100   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78101
78102   /* Reload the schema of the modified table. */
78103   reloadTableSchema(pParse, pTab, pTab->zName);
78104 }
78105
78106 /*
78107 ** This function is called by the parser after the table-name in
78108 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
78109 ** pSrc is the full-name of the table being altered.
78110 **
78111 ** This routine makes a (partial) copy of the Table structure
78112 ** for the table being altered and sets Parse.pNewTable to point
78113 ** to it. Routines called by the parser as the column definition
78114 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
78115 ** the copy. The copy of the Table structure is deleted by tokenize.c 
78116 ** after parsing is finished.
78117 **
78118 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
78119 ** coding the "ALTER TABLE ... ADD" statement.
78120 */
78121 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78122   Table *pNew;
78123   Table *pTab;
78124   Vdbe *v;
78125   int iDb;
78126   int i;
78127   int nAlloc;
78128   sqlite3 *db = pParse->db;
78129
78130   /* Look up the table being altered. */
78131   assert( pParse->pNewTable==0 );
78132   assert( sqlite3BtreeHoldsAllMutexes(db) );
78133   if( db->mallocFailed ) goto exit_begin_add_column;
78134   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78135   if( !pTab ) goto exit_begin_add_column;
78136
78137 #ifndef SQLITE_OMIT_VIRTUALTABLE
78138   if( IsVirtual(pTab) ){
78139     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
78140     goto exit_begin_add_column;
78141   }
78142 #endif
78143
78144   /* Make sure this is not an attempt to ALTER a view. */
78145   if( pTab->pSelect ){
78146     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
78147     goto exit_begin_add_column;
78148   }
78149   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78150     goto exit_begin_add_column;
78151   }
78152
78153   assert( pTab->addColOffset>0 );
78154   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78155
78156   /* Put a copy of the Table struct in Parse.pNewTable for the
78157   ** sqlite3AddColumn() function and friends to modify.  But modify
78158   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
78159   ** prefix, we insure that the name will not collide with an existing
78160   ** table because user table are not allowed to have the "sqlite_"
78161   ** prefix on their name.
78162   */
78163   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
78164   if( !pNew ) goto exit_begin_add_column;
78165   pParse->pNewTable = pNew;
78166   pNew->nRef = 1;
78167   pNew->nCol = pTab->nCol;
78168   assert( pNew->nCol>0 );
78169   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78170   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78171   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
78172   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
78173   if( !pNew->aCol || !pNew->zName ){
78174     db->mallocFailed = 1;
78175     goto exit_begin_add_column;
78176   }
78177   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78178   for(i=0; i<pNew->nCol; i++){
78179     Column *pCol = &pNew->aCol[i];
78180     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
78181     pCol->zColl = 0;
78182     pCol->zType = 0;
78183     pCol->pDflt = 0;
78184     pCol->zDflt = 0;
78185   }
78186   pNew->pSchema = db->aDb[iDb].pSchema;
78187   pNew->addColOffset = pTab->addColOffset;
78188   pNew->nRef = 1;
78189
78190   /* Begin a transaction and increment the schema cookie.  */
78191   sqlite3BeginWriteOperation(pParse, 0, iDb);
78192   v = sqlite3GetVdbe(pParse);
78193   if( !v ) goto exit_begin_add_column;
78194   sqlite3ChangeCookie(pParse, iDb);
78195
78196 exit_begin_add_column:
78197   sqlite3SrcListDelete(db, pSrc);
78198   return;
78199 }
78200 #endif  /* SQLITE_ALTER_TABLE */
78201
78202 /************** End of alter.c ***********************************************/
78203 /************** Begin file analyze.c *****************************************/
78204 /*
78205 ** 2005 July 8
78206 **
78207 ** The author disclaims copyright to this source code.  In place of
78208 ** a legal notice, here is a blessing:
78209 **
78210 **    May you do good and not evil.
78211 **    May you find forgiveness for yourself and forgive others.
78212 **    May you share freely, never taking more than you give.
78213 **
78214 *************************************************************************
78215 ** This file contains code associated with the ANALYZE command.
78216 **
78217 ** The ANALYZE command gather statistics about the content of tables
78218 ** and indices.  These statistics are made available to the query planner
78219 ** to help it make better decisions about how to perform queries.
78220 **
78221 ** The following system tables are or have been supported:
78222 **
78223 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
78224 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
78225 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
78226 **
78227 ** Additional tables might be added in future releases of SQLite.
78228 ** The sqlite_stat2 table is not created or used unless the SQLite version
78229 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
78230 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
78231 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
78232 ** created and used by SQLite versions 3.7.9 and later and with
78233 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
78234 ** is a superset of sqlite_stat2.  
78235 **
78236 ** Format of sqlite_stat1:
78237 **
78238 ** There is normally one row per index, with the index identified by the
78239 ** name in the idx column.  The tbl column is the name of the table to
78240 ** which the index belongs.  In each such row, the stat column will be
78241 ** a string consisting of a list of integers.  The first integer in this
78242 ** list is the number of rows in the index and in the table.  The second
78243 ** integer is the average number of rows in the index that have the same
78244 ** value in the first column of the index.  The third integer is the average
78245 ** number of rows in the index that have the same value for the first two
78246 ** columns.  The N-th integer (for N>1) is the average number of rows in 
78247 ** the index which have the same value for the first N-1 columns.  For
78248 ** a K-column index, there will be K+1 integers in the stat column.  If
78249 ** the index is unique, then the last integer will be 1.
78250 **
78251 ** The list of integers in the stat column can optionally be followed
78252 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
78253 ** must be separated from the last integer by a single space.  If the
78254 ** "unordered" keyword is present, then the query planner assumes that
78255 ** the index is unordered and will not use the index for a range query.
78256 ** 
78257 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
78258 ** column contains a single integer which is the (estimated) number of
78259 ** rows in the table identified by sqlite_stat1.tbl.
78260 **
78261 ** Format of sqlite_stat2:
78262 **
78263 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
78264 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
78265 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
78266 ** about the distribution of keys within an index.  The index is identified by
78267 ** the "idx" column and the "tbl" column is the name of the table to which
78268 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
78269 ** table for each index.
78270 **
78271 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
78272 ** inclusive are samples of the left-most key value in the index taken at
78273 ** evenly spaced points along the index.  Let the number of samples be S
78274 ** (10 in the standard build) and let C be the number of rows in the index.
78275 ** Then the sampled rows are given by:
78276 **
78277 **     rownumber = (i*C*2 + C)/(S*2)
78278 **
78279 ** For i between 0 and S-1.  Conceptually, the index space is divided into
78280 ** S uniform buckets and the samples are the middle row from each bucket.
78281 **
78282 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
78283 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
78284 ** writes the sqlite_stat2 table.  This version of SQLite only supports
78285 ** sqlite_stat3.
78286 **
78287 ** Format for sqlite_stat3:
78288 **
78289 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
78290 ** used to avoid compatibility problems.  
78291 **
78292 ** The format of the sqlite_stat3 table is similar to the format of
78293 ** the sqlite_stat2 table.  There are multiple entries for each index.
78294 ** The idx column names the index and the tbl column is the table of the
78295 ** index.  If the idx and tbl columns are the same, then the sample is
78296 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
78297 ** the left-most column of the index.  The nEq column is the approximate
78298 ** number of entires in the index whose left-most column exactly matches
78299 ** the sample.  nLt is the approximate number of entires whose left-most
78300 ** column is less than the sample.  The nDLt column is the approximate
78301 ** number of distinct left-most entries in the index that are less than
78302 ** the sample.
78303 **
78304 ** Future versions of SQLite might change to store a string containing
78305 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
78306 ** integer will be the number of prior index entires that are distinct in
78307 ** the left-most column.  The second integer will be the number of prior index
78308 ** entries that are distinct in the first two columns.  The third integer
78309 ** will be the number of prior index entries that are distinct in the first
78310 ** three columns.  And so forth.  With that extension, the nDLt field is
78311 ** similar in function to the sqlite_stat1.stat field.
78312 **
78313 ** There can be an arbitrary number of sqlite_stat3 entries per index.
78314 ** The ANALYZE command will typically generate sqlite_stat3 tables
78315 ** that contain between 10 and 40 samples which are distributed across
78316 ** the key space, though not uniformly, and which include samples with
78317 ** largest possible nEq values.
78318 */
78319 #ifndef SQLITE_OMIT_ANALYZE
78320
78321 /*
78322 ** This routine generates code that opens the sqlite_stat1 table for
78323 ** writing with cursor iStatCur. If the library was built with the
78324 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
78325 ** opened for writing using cursor (iStatCur+1)
78326 **
78327 ** If the sqlite_stat1 tables does not previously exist, it is created.
78328 ** Similarly, if the sqlite_stat3 table does not exist and the library
78329 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. 
78330 **
78331 ** Argument zWhere may be a pointer to a buffer containing a table name,
78332 ** or it may be a NULL pointer. If it is not NULL, then all entries in
78333 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
78334 ** with the named table are deleted. If zWhere==0, then code is generated
78335 ** to delete all stat table entries.
78336 */
78337 static void openStatTable(
78338   Parse *pParse,          /* Parsing context */
78339   int iDb,                /* The database we are looking in */
78340   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
78341   const char *zWhere,     /* Delete entries for this table or index */
78342   const char *zWhereType  /* Either "tbl" or "idx" */
78343 ){
78344   static const struct {
78345     const char *zName;
78346     const char *zCols;
78347   } aTable[] = {
78348     { "sqlite_stat1", "tbl,idx,stat" },
78349 #ifdef SQLITE_ENABLE_STAT3
78350     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
78351 #endif
78352   };
78353
78354   int aRoot[] = {0, 0};
78355   u8 aCreateTbl[] = {0, 0};
78356
78357   int i;
78358   sqlite3 *db = pParse->db;
78359   Db *pDb;
78360   Vdbe *v = sqlite3GetVdbe(pParse);
78361   if( v==0 ) return;
78362   assert( sqlite3BtreeHoldsAllMutexes(db) );
78363   assert( sqlite3VdbeDb(v)==db );
78364   pDb = &db->aDb[iDb];
78365
78366   /* Create new statistic tables if they do not exist, or clear them
78367   ** if they do already exist.
78368   */
78369   for(i=0; i<ArraySize(aTable); i++){
78370     const char *zTab = aTable[i].zName;
78371     Table *pStat;
78372     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
78373       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
78374       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
78375       ** of the new table in register pParse->regRoot. This is important 
78376       ** because the OpenWrite opcode below will be needing it. */
78377       sqlite3NestedParse(pParse,
78378           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
78379       );
78380       aRoot[i] = pParse->regRoot;
78381       aCreateTbl[i] = OPFLAG_P2ISREG;
78382     }else{
78383       /* The table already exists. If zWhere is not NULL, delete all entries 
78384       ** associated with the table zWhere. If zWhere is NULL, delete the
78385       ** entire contents of the table. */
78386       aRoot[i] = pStat->tnum;
78387       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
78388       if( zWhere ){
78389         sqlite3NestedParse(pParse,
78390            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
78391         );
78392       }else{
78393         /* The sqlite_stat[12] table already exists.  Delete all rows. */
78394         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
78395       }
78396     }
78397   }
78398
78399   /* Open the sqlite_stat[13] tables for writing. */
78400   for(i=0; i<ArraySize(aTable); i++){
78401     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
78402     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
78403     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
78404   }
78405 }
78406
78407 /*
78408 ** Recommended number of samples for sqlite_stat3
78409 */
78410 #ifndef SQLITE_STAT3_SAMPLES
78411 # define SQLITE_STAT3_SAMPLES 24
78412 #endif
78413
78414 /*
78415 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
78416 ** share an instance of the following structure to hold their state
78417 ** information.
78418 */
78419 typedef struct Stat3Accum Stat3Accum;
78420 struct Stat3Accum {
78421   tRowcnt nRow;             /* Number of rows in the entire table */
78422   tRowcnt nPSample;         /* How often to do a periodic sample */
78423   int iMin;                 /* Index of entry with minimum nEq and hash */
78424   int mxSample;             /* Maximum number of samples to accumulate */
78425   int nSample;              /* Current number of samples */
78426   u32 iPrn;                 /* Pseudo-random number used for sampling */
78427   struct Stat3Sample {
78428     i64 iRowid;                /* Rowid in main table of the key */
78429     tRowcnt nEq;               /* sqlite_stat3.nEq */
78430     tRowcnt nLt;               /* sqlite_stat3.nLt */
78431     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
78432     u8 isPSample;              /* True if a periodic sample */
78433     u32 iHash;                 /* Tiebreaker hash */
78434   } *a;                     /* An array of samples */
78435 };
78436
78437 #ifdef SQLITE_ENABLE_STAT3
78438 /*
78439 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
78440 ** are the number of rows in the table or index (C) and the number of samples
78441 ** to accumulate (S).
78442 **
78443 ** This routine allocates the Stat3Accum object.
78444 **
78445 ** The return value is the Stat3Accum object (P).
78446 */
78447 static void stat3Init(
78448   sqlite3_context *context,
78449   int argc,
78450   sqlite3_value **argv
78451 ){
78452   Stat3Accum *p;
78453   tRowcnt nRow;
78454   int mxSample;
78455   int n;
78456
78457   UNUSED_PARAMETER(argc);
78458   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
78459   mxSample = sqlite3_value_int(argv[1]);
78460   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
78461   p = sqlite3MallocZero( n );
78462   if( p==0 ){
78463     sqlite3_result_error_nomem(context);
78464     return;
78465   }
78466   p->a = (struct Stat3Sample*)&p[1];
78467   p->nRow = nRow;
78468   p->mxSample = mxSample;
78469   p->nPSample = p->nRow/(mxSample/3+1) + 1;
78470   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
78471   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
78472 }
78473 static const FuncDef stat3InitFuncdef = {
78474   2,                /* nArg */
78475   SQLITE_UTF8,      /* iPrefEnc */
78476   0,                /* flags */
78477   0,                /* pUserData */
78478   0,                /* pNext */
78479   stat3Init,        /* xFunc */
78480   0,                /* xStep */
78481   0,                /* xFinalize */
78482   "stat3_init",     /* zName */
78483   0,                /* pHash */
78484   0                 /* pDestructor */
78485 };
78486
78487
78488 /*
78489 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
78490 ** arguments describe a single key instance.  This routine makes the 
78491 ** decision about whether or not to retain this key for the sqlite_stat3
78492 ** table.
78493 **
78494 ** The return value is NULL.
78495 */
78496 static void stat3Push(
78497   sqlite3_context *context,
78498   int argc,
78499   sqlite3_value **argv
78500 ){
78501   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
78502   tRowcnt nEq = sqlite3_value_int64(argv[0]);
78503   tRowcnt nLt = sqlite3_value_int64(argv[1]);
78504   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
78505   i64 rowid = sqlite3_value_int64(argv[3]);
78506   u8 isPSample = 0;
78507   u8 doInsert = 0;
78508   int iMin = p->iMin;
78509   struct Stat3Sample *pSample;
78510   int i;
78511   u32 h;
78512
78513   UNUSED_PARAMETER(context);
78514   UNUSED_PARAMETER(argc);
78515   if( nEq==0 ) return;
78516   h = p->iPrn = p->iPrn*1103515245 + 12345;
78517   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
78518     doInsert = isPSample = 1;
78519   }else if( p->nSample<p->mxSample ){
78520     doInsert = 1;
78521   }else{
78522     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
78523       doInsert = 1;
78524     }
78525   }
78526   if( !doInsert ) return;
78527   if( p->nSample==p->mxSample ){
78528     assert( p->nSample - iMin - 1 >= 0 );
78529     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
78530     pSample = &p->a[p->nSample-1];
78531   }else{
78532     pSample = &p->a[p->nSample++];
78533   }
78534   pSample->iRowid = rowid;
78535   pSample->nEq = nEq;
78536   pSample->nLt = nLt;
78537   pSample->nDLt = nDLt;
78538   pSample->iHash = h;
78539   pSample->isPSample = isPSample;
78540
78541   /* Find the new minimum */
78542   if( p->nSample==p->mxSample ){
78543     pSample = p->a;
78544     i = 0;
78545     while( pSample->isPSample ){
78546       i++;
78547       pSample++;
78548       assert( i<p->nSample );
78549     }
78550     nEq = pSample->nEq;
78551     h = pSample->iHash;
78552     iMin = i;
78553     for(i++, pSample++; i<p->nSample; i++, pSample++){
78554       if( pSample->isPSample ) continue;
78555       if( pSample->nEq<nEq
78556        || (pSample->nEq==nEq && pSample->iHash<h)
78557       ){
78558         iMin = i;
78559         nEq = pSample->nEq;
78560         h = pSample->iHash;
78561       }
78562     }
78563     p->iMin = iMin;
78564   }
78565 }
78566 static const FuncDef stat3PushFuncdef = {
78567   5,                /* nArg */
78568   SQLITE_UTF8,      /* iPrefEnc */
78569   0,                /* flags */
78570   0,                /* pUserData */
78571   0,                /* pNext */
78572   stat3Push,        /* xFunc */
78573   0,                /* xStep */
78574   0,                /* xFinalize */
78575   "stat3_push",     /* zName */
78576   0,                /* pHash */
78577   0                 /* pDestructor */
78578 };
78579
78580 /*
78581 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
78582 ** used to query the results.  Content is returned for the Nth sqlite_stat3
78583 ** row where N is between 0 and S-1 and S is the number of samples.  The
78584 ** value returned depends on the number of arguments.
78585 **
78586 **   argc==2    result:  rowid
78587 **   argc==3    result:  nEq
78588 **   argc==4    result:  nLt
78589 **   argc==5    result:  nDLt
78590 */
78591 static void stat3Get(
78592   sqlite3_context *context,
78593   int argc,
78594   sqlite3_value **argv
78595 ){
78596   int n = sqlite3_value_int(argv[1]);
78597   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
78598
78599   assert( p!=0 );
78600   if( p->nSample<=n ) return;
78601   switch( argc ){
78602     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
78603     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
78604     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
78605     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
78606   }
78607 }
78608 static const FuncDef stat3GetFuncdef = {
78609   -1,               /* nArg */
78610   SQLITE_UTF8,      /* iPrefEnc */
78611   0,                /* flags */
78612   0,                /* pUserData */
78613   0,                /* pNext */
78614   stat3Get,         /* xFunc */
78615   0,                /* xStep */
78616   0,                /* xFinalize */
78617   "stat3_get",     /* zName */
78618   0,                /* pHash */
78619   0                 /* pDestructor */
78620 };
78621 #endif /* SQLITE_ENABLE_STAT3 */
78622
78623
78624
78625
78626 /*
78627 ** Generate code to do an analysis of all indices associated with
78628 ** a single table.
78629 */
78630 static void analyzeOneTable(
78631   Parse *pParse,   /* Parser context */
78632   Table *pTab,     /* Table whose indices are to be analyzed */
78633   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
78634   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
78635   int iMem         /* Available memory locations begin here */
78636 ){
78637   sqlite3 *db = pParse->db;    /* Database handle */
78638   Index *pIdx;                 /* An index to being analyzed */
78639   int iIdxCur;                 /* Cursor open on index being analyzed */
78640   Vdbe *v;                     /* The virtual machine being built up */
78641   int i;                       /* Loop counter */
78642   int topOfLoop;               /* The top of the loop */
78643   int endOfLoop;               /* The end of the loop */
78644   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
78645   int iDb;                     /* Index of database containing pTab */
78646   int regTabname = iMem++;     /* Register containing table name */
78647   int regIdxname = iMem++;     /* Register containing index name */
78648   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
78649 #ifdef SQLITE_ENABLE_STAT3
78650   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
78651   int regNumLt = iMem++;       /* Number of keys less than regSample */
78652   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
78653   int regSample = iMem++;      /* The next sample value */
78654   int regRowid = regSample;    /* Rowid of a sample */
78655   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
78656   int regLoop = iMem++;        /* Loop counter */
78657   int regCount = iMem++;       /* Number of rows in the table or index */
78658   int regTemp1 = iMem++;       /* Intermediate register */
78659   int regTemp2 = iMem++;       /* Intermediate register */
78660   int once = 1;                /* One-time initialization */
78661   int shortJump = 0;           /* Instruction address */
78662   int iTabCur = pParse->nTab++; /* Table cursor */
78663 #endif
78664   int regCol = iMem++;         /* Content of a column in analyzed table */
78665   int regRec = iMem++;         /* Register holding completed record */
78666   int regTemp = iMem++;        /* Temporary use register */
78667   int regNewRowid = iMem++;    /* Rowid for the inserted record */
78668
78669
78670   v = sqlite3GetVdbe(pParse);
78671   if( v==0 || NEVER(pTab==0) ){
78672     return;
78673   }
78674   if( pTab->tnum==0 ){
78675     /* Do not gather statistics on views or virtual tables */
78676     return;
78677   }
78678   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
78679     /* Do not gather statistics on system tables */
78680     return;
78681   }
78682   assert( sqlite3BtreeHoldsAllMutexes(db) );
78683   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78684   assert( iDb>=0 );
78685   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78686 #ifndef SQLITE_OMIT_AUTHORIZATION
78687   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
78688       db->aDb[iDb].zName ) ){
78689     return;
78690   }
78691 #endif
78692
78693   /* Establish a read-lock on the table at the shared-cache level. */
78694   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
78695
78696   iIdxCur = pParse->nTab++;
78697   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
78698   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78699     int nCol;
78700     KeyInfo *pKey;
78701     int addrIfNot = 0;           /* address of OP_IfNot */
78702     int *aChngAddr;              /* Array of jump instruction addresses */
78703
78704     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
78705     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
78706     nCol = pIdx->nColumn;
78707     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
78708     if( aChngAddr==0 ) continue;
78709     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
78710     if( iMem+1+(nCol*2)>pParse->nMem ){
78711       pParse->nMem = iMem+1+(nCol*2);
78712     }
78713
78714     /* Open a cursor to the index to be analyzed. */
78715     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
78716     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
78717         (char *)pKey, P4_KEYINFO_HANDOFF);
78718     VdbeComment((v, "%s", pIdx->zName));
78719
78720     /* Populate the register containing the index name. */
78721     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
78722
78723 #ifdef SQLITE_ENABLE_STAT3
78724     if( once ){
78725       once = 0;
78726       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
78727     }
78728     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
78729     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
78730     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
78731     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
78732     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
78733     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
78734     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
78735                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
78736     sqlite3VdbeChangeP5(v, 2);
78737 #endif /* SQLITE_ENABLE_STAT3 */
78738
78739     /* The block of memory cells initialized here is used as follows.
78740     **
78741     **    iMem:                
78742     **        The total number of rows in the table.
78743     **
78744     **    iMem+1 .. iMem+nCol: 
78745     **        Number of distinct entries in index considering the 
78746     **        left-most N columns only, where N is between 1 and nCol, 
78747     **        inclusive.
78748     **
78749     **    iMem+nCol+1 .. Mem+2*nCol:  
78750     **        Previous value of indexed columns, from left to right.
78751     **
78752     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
78753     ** initialized to contain an SQL NULL.
78754     */
78755     for(i=0; i<=nCol; i++){
78756       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
78757     }
78758     for(i=0; i<nCol; i++){
78759       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
78760     }
78761
78762     /* Start the analysis loop. This loop runs through all the entries in
78763     ** the index b-tree.  */
78764     endOfLoop = sqlite3VdbeMakeLabel(v);
78765     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
78766     topOfLoop = sqlite3VdbeCurrentAddr(v);
78767     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
78768
78769     for(i=0; i<nCol; i++){
78770       CollSeq *pColl;
78771       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
78772       if( i==0 ){
78773         /* Always record the very first row */
78774         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
78775       }
78776       assert( pIdx->azColl!=0 );
78777       assert( pIdx->azColl[i]!=0 );
78778       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
78779       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
78780                                       (char*)pColl, P4_COLLSEQ);
78781       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
78782       VdbeComment((v, "jump if column %d changed", i));
78783 #ifdef SQLITE_ENABLE_STAT3
78784       if( i==0 ){
78785         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
78786         VdbeComment((v, "incr repeat count"));
78787       }
78788 #endif
78789     }
78790     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
78791     for(i=0; i<nCol; i++){
78792       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
78793       if( i==0 ){
78794         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
78795 #ifdef SQLITE_ENABLE_STAT3
78796         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
78797                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
78798         sqlite3VdbeChangeP5(v, 5);
78799         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
78800         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
78801         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
78802         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
78803 #endif        
78804       }
78805       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
78806       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
78807     }
78808     sqlite3DbFree(db, aChngAddr);
78809
78810     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
78811     sqlite3VdbeResolveLabel(v, endOfLoop);
78812
78813     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
78814     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
78815 #ifdef SQLITE_ENABLE_STAT3
78816     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
78817                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
78818     sqlite3VdbeChangeP5(v, 5);
78819     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
78820     shortJump = 
78821     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
78822     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
78823                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
78824     sqlite3VdbeChangeP5(v, 2);
78825     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
78826     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
78827     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
78828     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
78829     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
78830                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
78831     sqlite3VdbeChangeP5(v, 3);
78832     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
78833                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
78834     sqlite3VdbeChangeP5(v, 4);
78835     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
78836                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
78837     sqlite3VdbeChangeP5(v, 5);
78838     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
78839     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
78840     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
78841     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
78842     sqlite3VdbeJumpHere(v, shortJump+2);
78843 #endif        
78844
78845     /* Store the results in sqlite_stat1.
78846     **
78847     ** The result is a single row of the sqlite_stat1 table.  The first
78848     ** two columns are the names of the table and index.  The third column
78849     ** is a string composed of a list of integer statistics about the
78850     ** index.  The first integer in the list is the total number of entries
78851     ** in the index.  There is one additional integer in the list for each
78852     ** column of the table.  This additional integer is a guess of how many
78853     ** rows of the table the index will select.  If D is the count of distinct
78854     ** values and K is the total number of rows, then the integer is computed
78855     ** as:
78856     **
78857     **        I = (K+D-1)/D
78858     **
78859     ** If K==0 then no entry is made into the sqlite_stat1 table.  
78860     ** If K>0 then it is always the case the D>0 so division by zero
78861     ** is never possible.
78862     */
78863     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
78864     if( jZeroRows<0 ){
78865       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
78866     }
78867     for(i=0; i<nCol; i++){
78868       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
78869       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
78870       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
78871       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
78872       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
78873       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
78874       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
78875     }
78876     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
78877     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
78878     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
78879     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
78880   }
78881
78882   /* If the table has no indices, create a single sqlite_stat1 entry
78883   ** containing NULL as the index name and the row count as the content.
78884   */
78885   if( pTab->pIndex==0 ){
78886     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
78887     VdbeComment((v, "%s", pTab->zName));
78888     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
78889     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
78890     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
78891   }else{
78892     sqlite3VdbeJumpHere(v, jZeroRows);
78893     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
78894   }
78895   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
78896   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
78897   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
78898   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
78899   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
78900   if( pParse->nMem<regRec ) pParse->nMem = regRec;
78901   sqlite3VdbeJumpHere(v, jZeroRows);
78902 }
78903
78904
78905 /*
78906 ** Generate code that will cause the most recent index analysis to
78907 ** be loaded into internal hash tables where is can be used.
78908 */
78909 static void loadAnalysis(Parse *pParse, int iDb){
78910   Vdbe *v = sqlite3GetVdbe(pParse);
78911   if( v ){
78912     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
78913   }
78914 }
78915
78916 /*
78917 ** Generate code that will do an analysis of an entire database
78918 */
78919 static void analyzeDatabase(Parse *pParse, int iDb){
78920   sqlite3 *db = pParse->db;
78921   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
78922   HashElem *k;
78923   int iStatCur;
78924   int iMem;
78925
78926   sqlite3BeginWriteOperation(pParse, 0, iDb);
78927   iStatCur = pParse->nTab;
78928   pParse->nTab += 3;
78929   openStatTable(pParse, iDb, iStatCur, 0, 0);
78930   iMem = pParse->nMem+1;
78931   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78932   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
78933     Table *pTab = (Table*)sqliteHashData(k);
78934     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
78935   }
78936   loadAnalysis(pParse, iDb);
78937 }
78938
78939 /*
78940 ** Generate code that will do an analysis of a single table in
78941 ** a database.  If pOnlyIdx is not NULL then it is a single index
78942 ** in pTab that should be analyzed.
78943 */
78944 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
78945   int iDb;
78946   int iStatCur;
78947
78948   assert( pTab!=0 );
78949   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78950   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78951   sqlite3BeginWriteOperation(pParse, 0, iDb);
78952   iStatCur = pParse->nTab;
78953   pParse->nTab += 3;
78954   if( pOnlyIdx ){
78955     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
78956   }else{
78957     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
78958   }
78959   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
78960   loadAnalysis(pParse, iDb);
78961 }
78962
78963 /*
78964 ** Generate code for the ANALYZE command.  The parser calls this routine
78965 ** when it recognizes an ANALYZE command.
78966 **
78967 **        ANALYZE                            -- 1
78968 **        ANALYZE  <database>                -- 2
78969 **        ANALYZE  ?<database>.?<tablename>  -- 3
78970 **
78971 ** Form 1 causes all indices in all attached databases to be analyzed.
78972 ** Form 2 analyzes all indices the single database named.
78973 ** Form 3 analyzes all indices associated with the named table.
78974 */
78975 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
78976   sqlite3 *db = pParse->db;
78977   int iDb;
78978   int i;
78979   char *z, *zDb;
78980   Table *pTab;
78981   Index *pIdx;
78982   Token *pTableName;
78983
78984   /* Read the database schema. If an error occurs, leave an error message
78985   ** and code in pParse and return NULL. */
78986   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78987   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78988     return;
78989   }
78990
78991   assert( pName2!=0 || pName1==0 );
78992   if( pName1==0 ){
78993     /* Form 1:  Analyze everything */
78994     for(i=0; i<db->nDb; i++){
78995       if( i==1 ) continue;  /* Do not analyze the TEMP database */
78996       analyzeDatabase(pParse, i);
78997     }
78998   }else if( pName2->n==0 ){
78999     /* Form 2:  Analyze the database or table named */
79000     iDb = sqlite3FindDb(db, pName1);
79001     if( iDb>=0 ){
79002       analyzeDatabase(pParse, iDb);
79003     }else{
79004       z = sqlite3NameFromToken(db, pName1);
79005       if( z ){
79006         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
79007           analyzeTable(pParse, pIdx->pTable, pIdx);
79008         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
79009           analyzeTable(pParse, pTab, 0);
79010         }
79011         sqlite3DbFree(db, z);
79012       }
79013     }
79014   }else{
79015     /* Form 3: Analyze the fully qualified table name */
79016     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
79017     if( iDb>=0 ){
79018       zDb = db->aDb[iDb].zName;
79019       z = sqlite3NameFromToken(db, pTableName);
79020       if( z ){
79021         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
79022           analyzeTable(pParse, pIdx->pTable, pIdx);
79023         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
79024           analyzeTable(pParse, pTab, 0);
79025         }
79026         sqlite3DbFree(db, z);
79027       }
79028     }   
79029   }
79030 }
79031
79032 /*
79033 ** Used to pass information from the analyzer reader through to the
79034 ** callback routine.
79035 */
79036 typedef struct analysisInfo analysisInfo;
79037 struct analysisInfo {
79038   sqlite3 *db;
79039   const char *zDatabase;
79040 };
79041
79042 /*
79043 ** This callback is invoked once for each index when reading the
79044 ** sqlite_stat1 table.  
79045 **
79046 **     argv[0] = name of the table
79047 **     argv[1] = name of the index (might be NULL)
79048 **     argv[2] = results of analysis - on integer for each column
79049 **
79050 ** Entries for which argv[1]==NULL simply record the number of rows in
79051 ** the table.
79052 */
79053 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79054   analysisInfo *pInfo = (analysisInfo*)pData;
79055   Index *pIndex;
79056   Table *pTable;
79057   int i, c, n;
79058   tRowcnt v;
79059   const char *z;
79060
79061   assert( argc==3 );
79062   UNUSED_PARAMETER2(NotUsed, argc);
79063
79064   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79065     return 0;
79066   }
79067   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79068   if( pTable==0 ){
79069     return 0;
79070   }
79071   if( argv[1] ){
79072     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79073   }else{
79074     pIndex = 0;
79075   }
79076   n = pIndex ? pIndex->nColumn : 0;
79077   z = argv[2];
79078   for(i=0; *z && i<=n; i++){
79079     v = 0;
79080     while( (c=z[0])>='0' && c<='9' ){
79081       v = v*10 + c - '0';
79082       z++;
79083     }
79084     if( i==0 ) pTable->nRowEst = v;
79085     if( pIndex==0 ) break;
79086     pIndex->aiRowEst[i] = v;
79087     if( *z==' ' ) z++;
79088     if( memcmp(z, "unordered", 10)==0 ){
79089       pIndex->bUnordered = 1;
79090       break;
79091     }
79092   }
79093   return 0;
79094 }
79095
79096 /*
79097 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79098 ** and its contents.
79099 */
79100 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
79101 #ifdef SQLITE_ENABLE_STAT3
79102   if( pIdx->aSample ){
79103     int j;
79104     for(j=0; j<pIdx->nSample; j++){
79105       IndexSample *p = &pIdx->aSample[j];
79106       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
79107         sqlite3DbFree(db, p->u.z);
79108       }
79109     }
79110     sqlite3DbFree(db, pIdx->aSample);
79111   }
79112   if( db && db->pnBytesFreed==0 ){
79113     pIdx->nSample = 0;
79114     pIdx->aSample = 0;
79115   }
79116 #else
79117   UNUSED_PARAMETER(db);
79118   UNUSED_PARAMETER(pIdx);
79119 #endif
79120 }
79121
79122 #ifdef SQLITE_ENABLE_STAT3
79123 /*
79124 ** Load content from the sqlite_stat3 table into the Index.aSample[]
79125 ** arrays of all indices.
79126 */
79127 static int loadStat3(sqlite3 *db, const char *zDb){
79128   int rc;                       /* Result codes from subroutines */
79129   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
79130   char *zSql;                   /* Text of the SQL statement */
79131   Index *pPrevIdx = 0;          /* Previous index in the loop */
79132   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79133   int eType;                    /* Datatype of a sample */
79134   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79135
79136   assert( db->lookaside.bEnabled==0 );
79137   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
79138     return SQLITE_OK;
79139   }
79140
79141   zSql = sqlite3MPrintf(db, 
79142       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
79143       " GROUP BY idx", zDb);
79144   if( !zSql ){
79145     return SQLITE_NOMEM;
79146   }
79147   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79148   sqlite3DbFree(db, zSql);
79149   if( rc ) return rc;
79150
79151   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79152     char *zIndex;   /* Index name */
79153     Index *pIdx;    /* Pointer to the index object */
79154     int nSample;    /* Number of samples */
79155
79156     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79157     if( zIndex==0 ) continue;
79158     nSample = sqlite3_column_int(pStmt, 1);
79159     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79160     if( pIdx==0 ) continue;
79161     assert( pIdx->nSample==0 );
79162     pIdx->nSample = nSample;
79163     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
79164     pIdx->avgEq = pIdx->aiRowEst[1];
79165     if( pIdx->aSample==0 ){
79166       db->mallocFailed = 1;
79167       sqlite3_finalize(pStmt);
79168       return SQLITE_NOMEM;
79169     }
79170   }
79171   rc = sqlite3_finalize(pStmt);
79172   if( rc ) return rc;
79173
79174   zSql = sqlite3MPrintf(db, 
79175       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
79176   if( !zSql ){
79177     return SQLITE_NOMEM;
79178   }
79179   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79180   sqlite3DbFree(db, zSql);
79181   if( rc ) return rc;
79182
79183   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79184     char *zIndex;   /* Index name */
79185     Index *pIdx;    /* Pointer to the index object */
79186     int i;          /* Loop counter */
79187     tRowcnt sumEq;  /* Sum of the nEq values */
79188
79189     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79190     if( zIndex==0 ) continue;
79191     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79192     if( pIdx==0 ) continue;
79193     if( pIdx==pPrevIdx ){
79194       idx++;
79195     }else{
79196       pPrevIdx = pIdx;
79197       idx = 0;
79198     }
79199     assert( idx<pIdx->nSample );
79200     pSample = &pIdx->aSample[idx];
79201     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
79202     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
79203     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
79204     if( idx==pIdx->nSample-1 ){
79205       if( pSample->nDLt>0 ){
79206         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
79207         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
79208       }
79209       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
79210     }
79211     eType = sqlite3_column_type(pStmt, 4);
79212     pSample->eType = (u8)eType;
79213     switch( eType ){
79214       case SQLITE_INTEGER: {
79215         pSample->u.i = sqlite3_column_int64(pStmt, 4);
79216         break;
79217       }
79218       case SQLITE_FLOAT: {
79219         pSample->u.r = sqlite3_column_double(pStmt, 4);
79220         break;
79221       }
79222       case SQLITE_NULL: {
79223         break;
79224       }
79225       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
79226         const char *z = (const char *)(
79227               (eType==SQLITE_BLOB) ?
79228               sqlite3_column_blob(pStmt, 4):
79229               sqlite3_column_text(pStmt, 4)
79230            );
79231         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
79232         pSample->nByte = n;
79233         if( n < 1){
79234           pSample->u.z = 0;
79235         }else{
79236           pSample->u.z = sqlite3DbMallocRaw(db, n);
79237           if( pSample->u.z==0 ){
79238             db->mallocFailed = 1;
79239             sqlite3_finalize(pStmt);
79240             return SQLITE_NOMEM;
79241           }
79242           memcpy(pSample->u.z, z, n);
79243         }
79244       }
79245     }
79246   }
79247   return sqlite3_finalize(pStmt);
79248 }
79249 #endif /* SQLITE_ENABLE_STAT3 */
79250
79251 /*
79252 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
79253 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
79254 ** arrays. The contents of sqlite_stat3 are used to populate the
79255 ** Index.aSample[] arrays.
79256 **
79257 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
79258 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined 
79259 ** during compilation and the sqlite_stat3 table is present, no data is 
79260 ** read from it.
79261 **
79262 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the 
79263 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
79264 ** returned. However, in this case, data is read from the sqlite_stat1
79265 ** table (if it is present) before returning.
79266 **
79267 ** If an OOM error occurs, this function always sets db->mallocFailed.
79268 ** This means if the caller does not care about other errors, the return
79269 ** code may be ignored.
79270 */
79271 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
79272   analysisInfo sInfo;
79273   HashElem *i;
79274   char *zSql;
79275   int rc;
79276
79277   assert( iDb>=0 && iDb<db->nDb );
79278   assert( db->aDb[iDb].pBt!=0 );
79279
79280   /* Clear any prior statistics */
79281   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79282   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
79283     Index *pIdx = sqliteHashData(i);
79284     sqlite3DefaultRowEst(pIdx);
79285 #ifdef SQLITE_ENABLE_STAT3
79286     sqlite3DeleteIndexSamples(db, pIdx);
79287     pIdx->aSample = 0;
79288 #endif
79289   }
79290
79291   /* Check to make sure the sqlite_stat1 table exists */
79292   sInfo.db = db;
79293   sInfo.zDatabase = db->aDb[iDb].zName;
79294   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
79295     return SQLITE_ERROR;
79296   }
79297
79298   /* Load new statistics out of the sqlite_stat1 table */
79299   zSql = sqlite3MPrintf(db, 
79300       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
79301   if( zSql==0 ){
79302     rc = SQLITE_NOMEM;
79303   }else{
79304     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
79305     sqlite3DbFree(db, zSql);
79306   }
79307
79308
79309   /* Load the statistics from the sqlite_stat3 table. */
79310 #ifdef SQLITE_ENABLE_STAT3
79311   if( rc==SQLITE_OK ){
79312     int lookasideEnabled = db->lookaside.bEnabled;
79313     db->lookaside.bEnabled = 0;
79314     rc = loadStat3(db, sInfo.zDatabase);
79315     db->lookaside.bEnabled = lookasideEnabled;
79316   }
79317 #endif
79318
79319   if( rc==SQLITE_NOMEM ){
79320     db->mallocFailed = 1;
79321   }
79322   return rc;
79323 }
79324
79325
79326 #endif /* SQLITE_OMIT_ANALYZE */
79327
79328 /************** End of analyze.c *********************************************/
79329 /************** Begin file attach.c ******************************************/
79330 /*
79331 ** 2003 April 6
79332 **
79333 ** The author disclaims copyright to this source code.  In place of
79334 ** a legal notice, here is a blessing:
79335 **
79336 **    May you do good and not evil.
79337 **    May you find forgiveness for yourself and forgive others.
79338 **    May you share freely, never taking more than you give.
79339 **
79340 *************************************************************************
79341 ** This file contains code used to implement the ATTACH and DETACH commands.
79342 */
79343
79344 #ifndef SQLITE_OMIT_ATTACH
79345 /*
79346 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
79347 ** is slightly different from resolving a normal SQL expression, because simple
79348 ** identifiers are treated as strings, not possible column names or aliases.
79349 **
79350 ** i.e. if the parser sees:
79351 **
79352 **     ATTACH DATABASE abc AS def
79353 **
79354 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
79355 ** looking for columns of the same name.
79356 **
79357 ** This only applies to the root node of pExpr, so the statement:
79358 **
79359 **     ATTACH DATABASE abc||def AS 'db2'
79360 **
79361 ** will fail because neither abc or def can be resolved.
79362 */
79363 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
79364 {
79365   int rc = SQLITE_OK;
79366   if( pExpr ){
79367     if( pExpr->op!=TK_ID ){
79368       rc = sqlite3ResolveExprNames(pName, pExpr);
79369       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
79370         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
79371         return SQLITE_ERROR;
79372       }
79373     }else{
79374       pExpr->op = TK_STRING;
79375     }
79376   }
79377   return rc;
79378 }
79379
79380 /*
79381 ** An SQL user-function registered to do the work of an ATTACH statement. The
79382 ** three arguments to the function come directly from an attach statement:
79383 **
79384 **     ATTACH DATABASE x AS y KEY z
79385 **
79386 **     SELECT sqlite_attach(x, y, z)
79387 **
79388 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
79389 ** third argument.
79390 */
79391 static void attachFunc(
79392   sqlite3_context *context,
79393   int NotUsed,
79394   sqlite3_value **argv
79395 ){
79396   int i;
79397   int rc = 0;
79398   sqlite3 *db = sqlite3_context_db_handle(context);
79399   const char *zName;
79400   const char *zFile;
79401   char *zPath = 0;
79402   char *zErr = 0;
79403   unsigned int flags;
79404   Db *aNew;
79405   char *zErrDyn = 0;
79406   sqlite3_vfs *pVfs;
79407
79408   UNUSED_PARAMETER(NotUsed);
79409
79410   zFile = (const char *)sqlite3_value_text(argv[0]);
79411   zName = (const char *)sqlite3_value_text(argv[1]);
79412   if( zFile==0 ) zFile = "";
79413   if( zName==0 ) zName = "";
79414
79415   /* Check for the following errors:
79416   **
79417   **     * Too many attached databases,
79418   **     * Transaction currently open
79419   **     * Specified database name already being used.
79420   */
79421   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
79422     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
79423       db->aLimit[SQLITE_LIMIT_ATTACHED]
79424     );
79425     goto attach_error;
79426   }
79427   if( !db->autoCommit ){
79428     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
79429     goto attach_error;
79430   }
79431   for(i=0; i<db->nDb; i++){
79432     char *z = db->aDb[i].zName;
79433     assert( z && zName );
79434     if( sqlite3StrICmp(z, zName)==0 ){
79435       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
79436       goto attach_error;
79437     }
79438   }
79439
79440   /* Allocate the new entry in the db->aDb[] array and initialise the schema
79441   ** hash tables.
79442   */
79443   if( db->aDb==db->aDbStatic ){
79444     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
79445     if( aNew==0 ) return;
79446     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
79447   }else{
79448     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
79449     if( aNew==0 ) return;
79450   }
79451   db->aDb = aNew;
79452   aNew = &db->aDb[db->nDb];
79453   memset(aNew, 0, sizeof(*aNew));
79454
79455   /* Open the database file. If the btree is successfully opened, use
79456   ** it to obtain the database schema. At this point the schema may
79457   ** or may not be initialised.
79458   */
79459   flags = db->openFlags;
79460   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
79461   if( rc!=SQLITE_OK ){
79462     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
79463     sqlite3_result_error(context, zErr, -1);
79464     sqlite3_free(zErr);
79465     return;
79466   }
79467   assert( pVfs );
79468   flags |= SQLITE_OPEN_MAIN_DB;
79469   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
79470   sqlite3_free( zPath );
79471   db->nDb++;
79472   if( rc==SQLITE_CONSTRAINT ){
79473     rc = SQLITE_ERROR;
79474     zErrDyn = sqlite3MPrintf(db, "database is already attached");
79475   }else if( rc==SQLITE_OK ){
79476     Pager *pPager;
79477     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
79478     if( !aNew->pSchema ){
79479       rc = SQLITE_NOMEM;
79480     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
79481       zErrDyn = sqlite3MPrintf(db, 
79482         "attached databases must use the same text encoding as main database");
79483       rc = SQLITE_ERROR;
79484     }
79485     pPager = sqlite3BtreePager(aNew->pBt);
79486     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
79487     sqlite3BtreeSecureDelete(aNew->pBt,
79488                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
79489   }
79490   aNew->safety_level = 3;
79491   aNew->zName = sqlite3DbStrDup(db, zName);
79492   if( rc==SQLITE_OK && aNew->zName==0 ){
79493     rc = SQLITE_NOMEM;
79494   }
79495
79496
79497 #ifdef SQLITE_HAS_CODEC
79498   if( rc==SQLITE_OK ){
79499     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
79500     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
79501     int nKey;
79502     char *zKey;
79503     int t = sqlite3_value_type(argv[2]);
79504     switch( t ){
79505       case SQLITE_INTEGER:
79506       case SQLITE_FLOAT:
79507         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
79508         rc = SQLITE_ERROR;
79509         break;
79510         
79511       case SQLITE_TEXT:
79512       case SQLITE_BLOB:
79513         nKey = sqlite3_value_bytes(argv[2]);
79514         zKey = (char *)sqlite3_value_blob(argv[2]);
79515         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
79516         break;
79517
79518       case SQLITE_NULL:
79519         /* No key specified.  Use the key from the main database */
79520         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
79521         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
79522           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
79523         }
79524         break;
79525     }
79526   }
79527 #endif
79528
79529   /* If the file was opened successfully, read the schema for the new database.
79530   ** If this fails, or if opening the file failed, then close the file and 
79531   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
79532   ** we found it.
79533   */
79534   if( rc==SQLITE_OK ){
79535     sqlite3BtreeEnterAll(db);
79536     rc = sqlite3Init(db, &zErrDyn);
79537     sqlite3BtreeLeaveAll(db);
79538   }
79539   if( rc ){
79540     int iDb = db->nDb - 1;
79541     assert( iDb>=2 );
79542     if( db->aDb[iDb].pBt ){
79543       sqlite3BtreeClose(db->aDb[iDb].pBt);
79544       db->aDb[iDb].pBt = 0;
79545       db->aDb[iDb].pSchema = 0;
79546     }
79547     sqlite3ResetAllSchemasOfConnection(db);
79548     db->nDb = iDb;
79549     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
79550       db->mallocFailed = 1;
79551       sqlite3DbFree(db, zErrDyn);
79552       zErrDyn = sqlite3MPrintf(db, "out of memory");
79553     }else if( zErrDyn==0 ){
79554       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
79555     }
79556     goto attach_error;
79557   }
79558   
79559   return;
79560
79561 attach_error:
79562   /* Return an error if we get here */
79563   if( zErrDyn ){
79564     sqlite3_result_error(context, zErrDyn, -1);
79565     sqlite3DbFree(db, zErrDyn);
79566   }
79567   if( rc ) sqlite3_result_error_code(context, rc);
79568 }
79569
79570 /*
79571 ** An SQL user-function registered to do the work of an DETACH statement. The
79572 ** three arguments to the function come directly from a detach statement:
79573 **
79574 **     DETACH DATABASE x
79575 **
79576 **     SELECT sqlite_detach(x)
79577 */
79578 static void detachFunc(
79579   sqlite3_context *context,
79580   int NotUsed,
79581   sqlite3_value **argv
79582 ){
79583   const char *zName = (const char *)sqlite3_value_text(argv[0]);
79584   sqlite3 *db = sqlite3_context_db_handle(context);
79585   int i;
79586   Db *pDb = 0;
79587   char zErr[128];
79588
79589   UNUSED_PARAMETER(NotUsed);
79590
79591   if( zName==0 ) zName = "";
79592   for(i=0; i<db->nDb; i++){
79593     pDb = &db->aDb[i];
79594     if( pDb->pBt==0 ) continue;
79595     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
79596   }
79597
79598   if( i>=db->nDb ){
79599     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
79600     goto detach_error;
79601   }
79602   if( i<2 ){
79603     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
79604     goto detach_error;
79605   }
79606   if( !db->autoCommit ){
79607     sqlite3_snprintf(sizeof(zErr), zErr,
79608                      "cannot DETACH database within transaction");
79609     goto detach_error;
79610   }
79611   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
79612     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
79613     goto detach_error;
79614   }
79615
79616   sqlite3BtreeClose(pDb->pBt);
79617   pDb->pBt = 0;
79618   pDb->pSchema = 0;
79619   sqlite3ResetAllSchemasOfConnection(db);
79620   return;
79621
79622 detach_error:
79623   sqlite3_result_error(context, zErr, -1);
79624 }
79625
79626 /*
79627 ** This procedure generates VDBE code for a single invocation of either the
79628 ** sqlite_detach() or sqlite_attach() SQL user functions.
79629 */
79630 static void codeAttach(
79631   Parse *pParse,       /* The parser context */
79632   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
79633   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
79634   Expr *pAuthArg,      /* Expression to pass to authorization callback */
79635   Expr *pFilename,     /* Name of database file */
79636   Expr *pDbname,       /* Name of the database to use internally */
79637   Expr *pKey           /* Database key for encryption extension */
79638 ){
79639   int rc;
79640   NameContext sName;
79641   Vdbe *v;
79642   sqlite3* db = pParse->db;
79643   int regArgs;
79644
79645   memset(&sName, 0, sizeof(NameContext));
79646   sName.pParse = pParse;
79647
79648   if( 
79649       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
79650       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
79651       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
79652   ){
79653     pParse->nErr++;
79654     goto attach_end;
79655   }
79656
79657 #ifndef SQLITE_OMIT_AUTHORIZATION
79658   if( pAuthArg ){
79659     char *zAuthArg;
79660     if( pAuthArg->op==TK_STRING ){
79661       zAuthArg = pAuthArg->u.zToken;
79662     }else{
79663       zAuthArg = 0;
79664     }
79665     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
79666     if(rc!=SQLITE_OK ){
79667       goto attach_end;
79668     }
79669   }
79670 #endif /* SQLITE_OMIT_AUTHORIZATION */
79671
79672
79673   v = sqlite3GetVdbe(pParse);
79674   regArgs = sqlite3GetTempRange(pParse, 4);
79675   sqlite3ExprCode(pParse, pFilename, regArgs);
79676   sqlite3ExprCode(pParse, pDbname, regArgs+1);
79677   sqlite3ExprCode(pParse, pKey, regArgs+2);
79678
79679   assert( v || db->mallocFailed );
79680   if( v ){
79681     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
79682     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
79683     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
79684     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
79685
79686     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
79687     ** statement only). For DETACH, set it to false (expire all existing
79688     ** statements).
79689     */
79690     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
79691   }
79692   
79693 attach_end:
79694   sqlite3ExprDelete(db, pFilename);
79695   sqlite3ExprDelete(db, pDbname);
79696   sqlite3ExprDelete(db, pKey);
79697 }
79698
79699 /*
79700 ** Called by the parser to compile a DETACH statement.
79701 **
79702 **     DETACH pDbname
79703 */
79704 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
79705   static const FuncDef detach_func = {
79706     1,                /* nArg */
79707     SQLITE_UTF8,      /* iPrefEnc */
79708     0,                /* flags */
79709     0,                /* pUserData */
79710     0,                /* pNext */
79711     detachFunc,       /* xFunc */
79712     0,                /* xStep */
79713     0,                /* xFinalize */
79714     "sqlite_detach",  /* zName */
79715     0,                /* pHash */
79716     0                 /* pDestructor */
79717   };
79718   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
79719 }
79720
79721 /*
79722 ** Called by the parser to compile an ATTACH statement.
79723 **
79724 **     ATTACH p AS pDbname KEY pKey
79725 */
79726 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
79727   static const FuncDef attach_func = {
79728     3,                /* nArg */
79729     SQLITE_UTF8,      /* iPrefEnc */
79730     0,                /* flags */
79731     0,                /* pUserData */
79732     0,                /* pNext */
79733     attachFunc,       /* xFunc */
79734     0,                /* xStep */
79735     0,                /* xFinalize */
79736     "sqlite_attach",  /* zName */
79737     0,                /* pHash */
79738     0                 /* pDestructor */
79739   };
79740   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
79741 }
79742 #endif /* SQLITE_OMIT_ATTACH */
79743
79744 /*
79745 ** Initialize a DbFixer structure.  This routine must be called prior
79746 ** to passing the structure to one of the sqliteFixAAAA() routines below.
79747 **
79748 ** The return value indicates whether or not fixation is required.  TRUE
79749 ** means we do need to fix the database references, FALSE means we do not.
79750 */
79751 SQLITE_PRIVATE int sqlite3FixInit(
79752   DbFixer *pFix,      /* The fixer to be initialized */
79753   Parse *pParse,      /* Error messages will be written here */
79754   int iDb,            /* This is the database that must be used */
79755   const char *zType,  /* "view", "trigger", or "index" */
79756   const Token *pName  /* Name of the view, trigger, or index */
79757 ){
79758   sqlite3 *db;
79759
79760   if( NEVER(iDb<0) || iDb==1 ) return 0;
79761   db = pParse->db;
79762   assert( db->nDb>iDb );
79763   pFix->pParse = pParse;
79764   pFix->zDb = db->aDb[iDb].zName;
79765   pFix->zType = zType;
79766   pFix->pName = pName;
79767   return 1;
79768 }
79769
79770 /*
79771 ** The following set of routines walk through the parse tree and assign
79772 ** a specific database to all table references where the database name
79773 ** was left unspecified in the original SQL statement.  The pFix structure
79774 ** must have been initialized by a prior call to sqlite3FixInit().
79775 **
79776 ** These routines are used to make sure that an index, trigger, or
79777 ** view in one database does not refer to objects in a different database.
79778 ** (Exception: indices, triggers, and views in the TEMP database are
79779 ** allowed to refer to anything.)  If a reference is explicitly made
79780 ** to an object in a different database, an error message is added to
79781 ** pParse->zErrMsg and these routines return non-zero.  If everything
79782 ** checks out, these routines return 0.
79783 */
79784 SQLITE_PRIVATE int sqlite3FixSrcList(
79785   DbFixer *pFix,       /* Context of the fixation */
79786   SrcList *pList       /* The Source list to check and modify */
79787 ){
79788   int i;
79789   const char *zDb;
79790   struct SrcList_item *pItem;
79791
79792   if( NEVER(pList==0) ) return 0;
79793   zDb = pFix->zDb;
79794   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
79795     if( pItem->zDatabase==0 ){
79796       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
79797     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
79798       sqlite3ErrorMsg(pFix->pParse,
79799          "%s %T cannot reference objects in database %s",
79800          pFix->zType, pFix->pName, pItem->zDatabase);
79801       return 1;
79802     }
79803 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
79804     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
79805     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
79806 #endif
79807   }
79808   return 0;
79809 }
79810 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
79811 SQLITE_PRIVATE int sqlite3FixSelect(
79812   DbFixer *pFix,       /* Context of the fixation */
79813   Select *pSelect      /* The SELECT statement to be fixed to one database */
79814 ){
79815   while( pSelect ){
79816     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
79817       return 1;
79818     }
79819     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
79820       return 1;
79821     }
79822     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
79823       return 1;
79824     }
79825     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
79826       return 1;
79827     }
79828     pSelect = pSelect->pPrior;
79829   }
79830   return 0;
79831 }
79832 SQLITE_PRIVATE int sqlite3FixExpr(
79833   DbFixer *pFix,     /* Context of the fixation */
79834   Expr *pExpr        /* The expression to be fixed to one database */
79835 ){
79836   while( pExpr ){
79837     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
79838     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79839       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
79840     }else{
79841       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
79842     }
79843     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
79844       return 1;
79845     }
79846     pExpr = pExpr->pLeft;
79847   }
79848   return 0;
79849 }
79850 SQLITE_PRIVATE int sqlite3FixExprList(
79851   DbFixer *pFix,     /* Context of the fixation */
79852   ExprList *pList    /* The expression to be fixed to one database */
79853 ){
79854   int i;
79855   struct ExprList_item *pItem;
79856   if( pList==0 ) return 0;
79857   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
79858     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
79859       return 1;
79860     }
79861   }
79862   return 0;
79863 }
79864 #endif
79865
79866 #ifndef SQLITE_OMIT_TRIGGER
79867 SQLITE_PRIVATE int sqlite3FixTriggerStep(
79868   DbFixer *pFix,     /* Context of the fixation */
79869   TriggerStep *pStep /* The trigger step be fixed to one database */
79870 ){
79871   while( pStep ){
79872     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
79873       return 1;
79874     }
79875     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
79876       return 1;
79877     }
79878     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
79879       return 1;
79880     }
79881     pStep = pStep->pNext;
79882   }
79883   return 0;
79884 }
79885 #endif
79886
79887 /************** End of attach.c **********************************************/
79888 /************** Begin file auth.c ********************************************/
79889 /*
79890 ** 2003 January 11
79891 **
79892 ** The author disclaims copyright to this source code.  In place of
79893 ** a legal notice, here is a blessing:
79894 **
79895 **    May you do good and not evil.
79896 **    May you find forgiveness for yourself and forgive others.
79897 **    May you share freely, never taking more than you give.
79898 **
79899 *************************************************************************
79900 ** This file contains code used to implement the sqlite3_set_authorizer()
79901 ** API.  This facility is an optional feature of the library.  Embedded
79902 ** systems that do not need this facility may omit it by recompiling
79903 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
79904 */
79905
79906 /*
79907 ** All of the code in this file may be omitted by defining a single
79908 ** macro.
79909 */
79910 #ifndef SQLITE_OMIT_AUTHORIZATION
79911
79912 /*
79913 ** Set or clear the access authorization function.
79914 **
79915 ** The access authorization function is be called during the compilation
79916 ** phase to verify that the user has read and/or write access permission on
79917 ** various fields of the database.  The first argument to the auth function
79918 ** is a copy of the 3rd argument to this routine.  The second argument
79919 ** to the auth function is one of these constants:
79920 **
79921 **       SQLITE_CREATE_INDEX
79922 **       SQLITE_CREATE_TABLE
79923 **       SQLITE_CREATE_TEMP_INDEX
79924 **       SQLITE_CREATE_TEMP_TABLE
79925 **       SQLITE_CREATE_TEMP_TRIGGER
79926 **       SQLITE_CREATE_TEMP_VIEW
79927 **       SQLITE_CREATE_TRIGGER
79928 **       SQLITE_CREATE_VIEW
79929 **       SQLITE_DELETE
79930 **       SQLITE_DROP_INDEX
79931 **       SQLITE_DROP_TABLE
79932 **       SQLITE_DROP_TEMP_INDEX
79933 **       SQLITE_DROP_TEMP_TABLE
79934 **       SQLITE_DROP_TEMP_TRIGGER
79935 **       SQLITE_DROP_TEMP_VIEW
79936 **       SQLITE_DROP_TRIGGER
79937 **       SQLITE_DROP_VIEW
79938 **       SQLITE_INSERT
79939 **       SQLITE_PRAGMA
79940 **       SQLITE_READ
79941 **       SQLITE_SELECT
79942 **       SQLITE_TRANSACTION
79943 **       SQLITE_UPDATE
79944 **
79945 ** The third and fourth arguments to the auth function are the name of
79946 ** the table and the column that are being accessed.  The auth function
79947 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
79948 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
79949 ** means that the SQL statement will never-run - the sqlite3_exec() call
79950 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
79951 ** should run but attempts to read the specified column will return NULL
79952 ** and attempts to write the column will be ignored.
79953 **
79954 ** Setting the auth function to NULL disables this hook.  The default
79955 ** setting of the auth function is NULL.
79956 */
79957 SQLITE_API int sqlite3_set_authorizer(
79958   sqlite3 *db,
79959   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
79960   void *pArg
79961 ){
79962   sqlite3_mutex_enter(db->mutex);
79963   db->xAuth = xAuth;
79964   db->pAuthArg = pArg;
79965   sqlite3ExpirePreparedStatements(db);
79966   sqlite3_mutex_leave(db->mutex);
79967   return SQLITE_OK;
79968 }
79969
79970 /*
79971 ** Write an error message into pParse->zErrMsg that explains that the
79972 ** user-supplied authorization function returned an illegal value.
79973 */
79974 static void sqliteAuthBadReturnCode(Parse *pParse){
79975   sqlite3ErrorMsg(pParse, "authorizer malfunction");
79976   pParse->rc = SQLITE_ERROR;
79977 }
79978
79979 /*
79980 ** Invoke the authorization callback for permission to read column zCol from
79981 ** table zTab in database zDb. This function assumes that an authorization
79982 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
79983 **
79984 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
79985 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
79986 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
79987 */
79988 SQLITE_PRIVATE int sqlite3AuthReadCol(
79989   Parse *pParse,                  /* The parser context */
79990   const char *zTab,               /* Table name */
79991   const char *zCol,               /* Column name */
79992   int iDb                         /* Index of containing database. */
79993 ){
79994   sqlite3 *db = pParse->db;       /* Database handle */
79995   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
79996   int rc;                         /* Auth callback return code */
79997
79998   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
79999   if( rc==SQLITE_DENY ){
80000     if( db->nDb>2 || iDb!=0 ){
80001       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80002     }else{
80003       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80004     }
80005     pParse->rc = SQLITE_AUTH;
80006   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
80007     sqliteAuthBadReturnCode(pParse);
80008   }
80009   return rc;
80010 }
80011
80012 /*
80013 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80014 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
80015 ** Check to see if it is OK to read this particular column.
80016 **
80017 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
80018 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
80019 ** then generate an error.
80020 */
80021 SQLITE_PRIVATE void sqlite3AuthRead(
80022   Parse *pParse,        /* The parser context */
80023   Expr *pExpr,          /* The expression to check authorization on */
80024   Schema *pSchema,      /* The schema of the expression */
80025   SrcList *pTabList     /* All table that pExpr might refer to */
80026 ){
80027   sqlite3 *db = pParse->db;
80028   Table *pTab = 0;      /* The table being read */
80029   const char *zCol;     /* Name of the column of the table */
80030   int iSrc;             /* Index in pTabList->a[] of table being read */
80031   int iDb;              /* The index of the database the expression refers to */
80032   int iCol;             /* Index of column in table */
80033
80034   if( db->xAuth==0 ) return;
80035   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
80036   if( iDb<0 ){
80037     /* An attempt to read a column out of a subquery or other
80038     ** temporary table. */
80039     return;
80040   }
80041
80042   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80043   if( pExpr->op==TK_TRIGGER ){
80044     pTab = pParse->pTriggerTab;
80045   }else{
80046     assert( pTabList );
80047     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80048       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80049         pTab = pTabList->a[iSrc].pTab;
80050         break;
80051       }
80052     }
80053   }
80054   iCol = pExpr->iColumn;
80055   if( NEVER(pTab==0) ) return;
80056
80057   if( iCol>=0 ){
80058     assert( iCol<pTab->nCol );
80059     zCol = pTab->aCol[iCol].zName;
80060   }else if( pTab->iPKey>=0 ){
80061     assert( pTab->iPKey<pTab->nCol );
80062     zCol = pTab->aCol[pTab->iPKey].zName;
80063   }else{
80064     zCol = "ROWID";
80065   }
80066   assert( iDb>=0 && iDb<db->nDb );
80067   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80068     pExpr->op = TK_NULL;
80069   }
80070 }
80071
80072 /*
80073 ** Do an authorization check using the code and arguments given.  Return
80074 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
80075 ** is returned, then the error count and error message in pParse are
80076 ** modified appropriately.
80077 */
80078 SQLITE_PRIVATE int sqlite3AuthCheck(
80079   Parse *pParse,
80080   int code,
80081   const char *zArg1,
80082   const char *zArg2,
80083   const char *zArg3
80084 ){
80085   sqlite3 *db = pParse->db;
80086   int rc;
80087
80088   /* Don't do any authorization checks if the database is initialising
80089   ** or if the parser is being invoked from within sqlite3_declare_vtab.
80090   */
80091   if( db->init.busy || IN_DECLARE_VTAB ){
80092     return SQLITE_OK;
80093   }
80094
80095   if( db->xAuth==0 ){
80096     return SQLITE_OK;
80097   }
80098   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80099   if( rc==SQLITE_DENY ){
80100     sqlite3ErrorMsg(pParse, "not authorized");
80101     pParse->rc = SQLITE_AUTH;
80102   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
80103     rc = SQLITE_DENY;
80104     sqliteAuthBadReturnCode(pParse);
80105   }
80106   return rc;
80107 }
80108
80109 /*
80110 ** Push an authorization context.  After this routine is called, the
80111 ** zArg3 argument to authorization callbacks will be zContext until
80112 ** popped.  Or if pParse==0, this routine is a no-op.
80113 */
80114 SQLITE_PRIVATE void sqlite3AuthContextPush(
80115   Parse *pParse,
80116   AuthContext *pContext, 
80117   const char *zContext
80118 ){
80119   assert( pParse );
80120   pContext->pParse = pParse;
80121   pContext->zAuthContext = pParse->zAuthContext;
80122   pParse->zAuthContext = zContext;
80123 }
80124
80125 /*
80126 ** Pop an authorization context that was previously pushed
80127 ** by sqlite3AuthContextPush
80128 */
80129 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
80130   if( pContext->pParse ){
80131     pContext->pParse->zAuthContext = pContext->zAuthContext;
80132     pContext->pParse = 0;
80133   }
80134 }
80135
80136 #endif /* SQLITE_OMIT_AUTHORIZATION */
80137
80138 /************** End of auth.c ************************************************/
80139 /************** Begin file build.c *******************************************/
80140 /*
80141 ** 2001 September 15
80142 **
80143 ** The author disclaims copyright to this source code.  In place of
80144 ** a legal notice, here is a blessing:
80145 **
80146 **    May you do good and not evil.
80147 **    May you find forgiveness for yourself and forgive others.
80148 **    May you share freely, never taking more than you give.
80149 **
80150 *************************************************************************
80151 ** This file contains C code routines that are called by the SQLite parser
80152 ** when syntax rules are reduced.  The routines in this file handle the
80153 ** following kinds of SQL syntax:
80154 **
80155 **     CREATE TABLE
80156 **     DROP TABLE
80157 **     CREATE INDEX
80158 **     DROP INDEX
80159 **     creating ID lists
80160 **     BEGIN TRANSACTION
80161 **     COMMIT
80162 **     ROLLBACK
80163 */
80164
80165 /*
80166 ** This routine is called when a new SQL statement is beginning to
80167 ** be parsed.  Initialize the pParse structure as needed.
80168 */
80169 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
80170   pParse->explain = (u8)explainFlag;
80171   pParse->nVar = 0;
80172 }
80173
80174 #ifndef SQLITE_OMIT_SHARED_CACHE
80175 /*
80176 ** The TableLock structure is only used by the sqlite3TableLock() and
80177 ** codeTableLocks() functions.
80178 */
80179 struct TableLock {
80180   int iDb;             /* The database containing the table to be locked */
80181   int iTab;            /* The root page of the table to be locked */
80182   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80183   const char *zName;   /* Name of the table */
80184 };
80185
80186 /*
80187 ** Record the fact that we want to lock a table at run-time.  
80188 **
80189 ** The table to be locked has root page iTab and is found in database iDb.
80190 ** A read or a write lock can be taken depending on isWritelock.
80191 **
80192 ** This routine just records the fact that the lock is desired.  The
80193 ** code to make the lock occur is generated by a later call to
80194 ** codeTableLocks() which occurs during sqlite3FinishCoding().
80195 */
80196 SQLITE_PRIVATE void sqlite3TableLock(
80197   Parse *pParse,     /* Parsing context */
80198   int iDb,           /* Index of the database containing the table to lock */
80199   int iTab,          /* Root page number of the table to be locked */
80200   u8 isWriteLock,    /* True for a write lock */
80201   const char *zName  /* Name of the table to be locked */
80202 ){
80203   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80204   int i;
80205   int nBytes;
80206   TableLock *p;
80207   assert( iDb>=0 );
80208
80209   for(i=0; i<pToplevel->nTableLock; i++){
80210     p = &pToplevel->aTableLock[i];
80211     if( p->iDb==iDb && p->iTab==iTab ){
80212       p->isWriteLock = (p->isWriteLock || isWriteLock);
80213       return;
80214     }
80215   }
80216
80217   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80218   pToplevel->aTableLock =
80219       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
80220   if( pToplevel->aTableLock ){
80221     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
80222     p->iDb = iDb;
80223     p->iTab = iTab;
80224     p->isWriteLock = isWriteLock;
80225     p->zName = zName;
80226   }else{
80227     pToplevel->nTableLock = 0;
80228     pToplevel->db->mallocFailed = 1;
80229   }
80230 }
80231
80232 /*
80233 ** Code an OP_TableLock instruction for each table locked by the
80234 ** statement (configured by calls to sqlite3TableLock()).
80235 */
80236 static void codeTableLocks(Parse *pParse){
80237   int i;
80238   Vdbe *pVdbe; 
80239
80240   pVdbe = sqlite3GetVdbe(pParse);
80241   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
80242
80243   for(i=0; i<pParse->nTableLock; i++){
80244     TableLock *p = &pParse->aTableLock[i];
80245     int p1 = p->iDb;
80246     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
80247                       p->zName, P4_STATIC);
80248   }
80249 }
80250 #else
80251   #define codeTableLocks(x)
80252 #endif
80253
80254 /*
80255 ** This routine is called after a single SQL statement has been
80256 ** parsed and a VDBE program to execute that statement has been
80257 ** prepared.  This routine puts the finishing touches on the
80258 ** VDBE program and resets the pParse structure for the next
80259 ** parse.
80260 **
80261 ** Note that if an error occurred, it might be the case that
80262 ** no VDBE code was generated.
80263 */
80264 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
80265   sqlite3 *db;
80266   Vdbe *v;
80267
80268   db = pParse->db;
80269   if( db->mallocFailed ) return;
80270   if( pParse->nested ) return;
80271   if( pParse->nErr ) return;
80272
80273   /* Begin by generating some termination code at the end of the
80274   ** vdbe program
80275   */
80276   v = sqlite3GetVdbe(pParse);
80277   assert( !pParse->isMultiWrite 
80278        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
80279   if( v ){
80280     sqlite3VdbeAddOp0(v, OP_Halt);
80281
80282     /* The cookie mask contains one bit for each database file open.
80283     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
80284     ** set for each database that is used.  Generate code to start a
80285     ** transaction on each used database and to verify the schema cookie
80286     ** on each used database.
80287     */
80288     if( pParse->cookieGoto>0 ){
80289       yDbMask mask;
80290       int iDb;
80291       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
80292       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
80293         if( (mask & pParse->cookieMask)==0 ) continue;
80294         sqlite3VdbeUsesBtree(v, iDb);
80295         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
80296         if( db->init.busy==0 ){
80297           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80298           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
80299                             iDb, pParse->cookieValue[iDb],
80300                             db->aDb[iDb].pSchema->iGeneration);
80301         }
80302       }
80303 #ifndef SQLITE_OMIT_VIRTUALTABLE
80304       {
80305         int i;
80306         for(i=0; i<pParse->nVtabLock; i++){
80307           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
80308           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
80309         }
80310         pParse->nVtabLock = 0;
80311       }
80312 #endif
80313
80314       /* Once all the cookies have been verified and transactions opened, 
80315       ** obtain the required table-locks. This is a no-op unless the 
80316       ** shared-cache feature is enabled.
80317       */
80318       codeTableLocks(pParse);
80319
80320       /* Initialize any AUTOINCREMENT data structures required.
80321       */
80322       sqlite3AutoincrementBegin(pParse);
80323
80324       /* Finally, jump back to the beginning of the executable code. */
80325       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
80326     }
80327   }
80328
80329
80330   /* Get the VDBE program ready for execution
80331   */
80332   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
80333 #ifdef SQLITE_DEBUG
80334     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
80335     sqlite3VdbeTrace(v, trace);
80336 #endif
80337     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
80338     /* A minimum of one cursor is required if autoincrement is used
80339     *  See ticket [a696379c1f08866] */
80340     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
80341     sqlite3VdbeMakeReady(v, pParse);
80342     pParse->rc = SQLITE_DONE;
80343     pParse->colNamesSet = 0;
80344   }else{
80345     pParse->rc = SQLITE_ERROR;
80346   }
80347   pParse->nTab = 0;
80348   pParse->nMem = 0;
80349   pParse->nSet = 0;
80350   pParse->nVar = 0;
80351   pParse->cookieMask = 0;
80352   pParse->cookieGoto = 0;
80353 }
80354
80355 /*
80356 ** Run the parser and code generator recursively in order to generate
80357 ** code for the SQL statement given onto the end of the pParse context
80358 ** currently under construction.  When the parser is run recursively
80359 ** this way, the final OP_Halt is not appended and other initialization
80360 ** and finalization steps are omitted because those are handling by the
80361 ** outermost parser.
80362 **
80363 ** Not everything is nestable.  This facility is designed to permit
80364 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
80365 ** care if you decide to try to use this routine for some other purposes.
80366 */
80367 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
80368   va_list ap;
80369   char *zSql;
80370   char *zErrMsg = 0;
80371   sqlite3 *db = pParse->db;
80372 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
80373   char saveBuf[SAVE_SZ];
80374
80375   if( pParse->nErr ) return;
80376   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
80377   va_start(ap, zFormat);
80378   zSql = sqlite3VMPrintf(db, zFormat, ap);
80379   va_end(ap);
80380   if( zSql==0 ){
80381     return;   /* A malloc must have failed */
80382   }
80383   pParse->nested++;
80384   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
80385   memset(&pParse->nVar, 0, SAVE_SZ);
80386   sqlite3RunParser(pParse, zSql, &zErrMsg);
80387   sqlite3DbFree(db, zErrMsg);
80388   sqlite3DbFree(db, zSql);
80389   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
80390   pParse->nested--;
80391 }
80392
80393 /*
80394 ** Locate the in-memory structure that describes a particular database
80395 ** table given the name of that table and (optionally) the name of the
80396 ** database containing the table.  Return NULL if not found.
80397 **
80398 ** If zDatabase is 0, all databases are searched for the table and the
80399 ** first matching table is returned.  (No checking for duplicate table
80400 ** names is done.)  The search order is TEMP first, then MAIN, then any
80401 ** auxiliary databases added using the ATTACH command.
80402 **
80403 ** See also sqlite3LocateTable().
80404 */
80405 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
80406   Table *p = 0;
80407   int i;
80408   int nName;
80409   assert( zName!=0 );
80410   nName = sqlite3Strlen30(zName);
80411   /* All mutexes are required for schema access.  Make sure we hold them. */
80412   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
80413   for(i=OMIT_TEMPDB; i<db->nDb; i++){
80414     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
80415     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
80416     assert( sqlite3SchemaMutexHeld(db, j, 0) );
80417     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
80418     if( p ) break;
80419   }
80420   return p;
80421 }
80422
80423 /*
80424 ** Locate the in-memory structure that describes a particular database
80425 ** table given the name of that table and (optionally) the name of the
80426 ** database containing the table.  Return NULL if not found.  Also leave an
80427 ** error message in pParse->zErrMsg.
80428 **
80429 ** The difference between this routine and sqlite3FindTable() is that this
80430 ** routine leaves an error message in pParse->zErrMsg where
80431 ** sqlite3FindTable() does not.
80432 */
80433 SQLITE_PRIVATE Table *sqlite3LocateTable(
80434   Parse *pParse,         /* context in which to report errors */
80435   int isView,            /* True if looking for a VIEW rather than a TABLE */
80436   const char *zName,     /* Name of the table we are looking for */
80437   const char *zDbase     /* Name of the database.  Might be NULL */
80438 ){
80439   Table *p;
80440
80441   /* Read the database schema. If an error occurs, leave an error message
80442   ** and code in pParse and return NULL. */
80443   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80444     return 0;
80445   }
80446
80447   p = sqlite3FindTable(pParse->db, zName, zDbase);
80448   if( p==0 ){
80449     const char *zMsg = isView ? "no such view" : "no such table";
80450     if( zDbase ){
80451       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
80452     }else{
80453       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
80454     }
80455     pParse->checkSchema = 1;
80456   }
80457   return p;
80458 }
80459
80460 /*
80461 ** Locate the in-memory structure that describes 
80462 ** a particular index given the name of that index
80463 ** and the name of the database that contains the index.
80464 ** Return NULL if not found.
80465 **
80466 ** If zDatabase is 0, all databases are searched for the
80467 ** table and the first matching index is returned.  (No checking
80468 ** for duplicate index names is done.)  The search order is
80469 ** TEMP first, then MAIN, then any auxiliary databases added
80470 ** using the ATTACH command.
80471 */
80472 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
80473   Index *p = 0;
80474   int i;
80475   int nName = sqlite3Strlen30(zName);
80476   /* All mutexes are required for schema access.  Make sure we hold them. */
80477   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
80478   for(i=OMIT_TEMPDB; i<db->nDb; i++){
80479     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
80480     Schema *pSchema = db->aDb[j].pSchema;
80481     assert( pSchema );
80482     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
80483     assert( sqlite3SchemaMutexHeld(db, j, 0) );
80484     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
80485     if( p ) break;
80486   }
80487   return p;
80488 }
80489
80490 /*
80491 ** Reclaim the memory used by an index
80492 */
80493 static void freeIndex(sqlite3 *db, Index *p){
80494 #ifndef SQLITE_OMIT_ANALYZE
80495   sqlite3DeleteIndexSamples(db, p);
80496 #endif
80497   sqlite3DbFree(db, p->zColAff);
80498   sqlite3DbFree(db, p);
80499 }
80500
80501 /*
80502 ** For the index called zIdxName which is found in the database iDb,
80503 ** unlike that index from its Table then remove the index from
80504 ** the index hash table and free all memory structures associated
80505 ** with the index.
80506 */
80507 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
80508   Index *pIndex;
80509   int len;
80510   Hash *pHash;
80511
80512   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80513   pHash = &db->aDb[iDb].pSchema->idxHash;
80514   len = sqlite3Strlen30(zIdxName);
80515   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
80516   if( ALWAYS(pIndex) ){
80517     if( pIndex->pTable->pIndex==pIndex ){
80518       pIndex->pTable->pIndex = pIndex->pNext;
80519     }else{
80520       Index *p;
80521       /* Justification of ALWAYS();  The index must be on the list of
80522       ** indices. */
80523       p = pIndex->pTable->pIndex;
80524       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
80525       if( ALWAYS(p && p->pNext==pIndex) ){
80526         p->pNext = pIndex->pNext;
80527       }
80528     }
80529     freeIndex(db, pIndex);
80530   }
80531   db->flags |= SQLITE_InternChanges;
80532 }
80533
80534 /*
80535 ** Look through the list of open database files in db->aDb[] and if
80536 ** any have been closed, remove them from the list.  Reallocate the
80537 ** db->aDb[] structure to a smaller size, if possible.
80538 **
80539 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
80540 ** are never candidates for being collapsed.
80541 */
80542 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
80543   int i, j;
80544   for(i=j=2; i<db->nDb; i++){
80545     struct Db *pDb = &db->aDb[i];
80546     if( pDb->pBt==0 ){
80547       sqlite3DbFree(db, pDb->zName);
80548       pDb->zName = 0;
80549       continue;
80550     }
80551     if( j<i ){
80552       db->aDb[j] = db->aDb[i];
80553     }
80554     j++;
80555   }
80556   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
80557   db->nDb = j;
80558   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
80559     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
80560     sqlite3DbFree(db, db->aDb);
80561     db->aDb = db->aDbStatic;
80562   }
80563 }
80564
80565 /*
80566 ** Reset the schema for the database at index iDb.  Also reset the
80567 ** TEMP schema.
80568 */
80569 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
80570   Db *pDb;
80571   assert( iDb<db->nDb );
80572
80573   /* Case 1:  Reset the single schema identified by iDb */
80574   pDb = &db->aDb[iDb];
80575   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80576   assert( pDb->pSchema!=0 );
80577   sqlite3SchemaClear(pDb->pSchema);
80578
80579   /* If any database other than TEMP is reset, then also reset TEMP
80580   ** since TEMP might be holding triggers that reference tables in the
80581   ** other database.
80582   */
80583   if( iDb!=1 ){
80584     pDb = &db->aDb[1];
80585     assert( pDb->pSchema!=0 );
80586     sqlite3SchemaClear(pDb->pSchema);
80587   }
80588   return;
80589 }
80590
80591 /*
80592 ** Erase all schema information from all attached databases (including
80593 ** "main" and "temp") for a single database connection.
80594 */
80595 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
80596   int i;
80597   sqlite3BtreeEnterAll(db);
80598   for(i=0; i<db->nDb; i++){
80599     Db *pDb = &db->aDb[i];
80600     if( pDb->pSchema ){
80601       sqlite3SchemaClear(pDb->pSchema);
80602     }
80603   }
80604   db->flags &= ~SQLITE_InternChanges;
80605   sqlite3VtabUnlockList(db);
80606   sqlite3BtreeLeaveAll(db);
80607   sqlite3CollapseDatabaseArray(db);
80608 }
80609
80610 /*
80611 ** This routine is called when a commit occurs.
80612 */
80613 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
80614   db->flags &= ~SQLITE_InternChanges;
80615 }
80616
80617 /*
80618 ** Delete memory allocated for the column names of a table or view (the
80619 ** Table.aCol[] array).
80620 */
80621 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
80622   int i;
80623   Column *pCol;
80624   assert( pTable!=0 );
80625   if( (pCol = pTable->aCol)!=0 ){
80626     for(i=0; i<pTable->nCol; i++, pCol++){
80627       sqlite3DbFree(db, pCol->zName);
80628       sqlite3ExprDelete(db, pCol->pDflt);
80629       sqlite3DbFree(db, pCol->zDflt);
80630       sqlite3DbFree(db, pCol->zType);
80631       sqlite3DbFree(db, pCol->zColl);
80632     }
80633     sqlite3DbFree(db, pTable->aCol);
80634   }
80635 }
80636
80637 /*
80638 ** Remove the memory data structures associated with the given
80639 ** Table.  No changes are made to disk by this routine.
80640 **
80641 ** This routine just deletes the data structure.  It does not unlink
80642 ** the table data structure from the hash table.  But it does destroy
80643 ** memory structures of the indices and foreign keys associated with 
80644 ** the table.
80645 **
80646 ** The db parameter is optional.  It is needed if the Table object 
80647 ** contains lookaside memory.  (Table objects in the schema do not use
80648 ** lookaside memory, but some ephemeral Table objects do.)  Or the
80649 ** db parameter can be used with db->pnBytesFreed to measure the memory
80650 ** used by the Table object.
80651 */
80652 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
80653   Index *pIndex, *pNext;
80654   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
80655
80656   assert( !pTable || pTable->nRef>0 );
80657
80658   /* Do not delete the table until the reference count reaches zero. */
80659   if( !pTable ) return;
80660   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
80661
80662   /* Record the number of outstanding lookaside allocations in schema Tables
80663   ** prior to doing any free() operations.  Since schema Tables do not use
80664   ** lookaside, this number should not change. */
80665   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
80666                          db->lookaside.nOut : 0 );
80667
80668   /* Delete all indices associated with this table. */
80669   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
80670     pNext = pIndex->pNext;
80671     assert( pIndex->pSchema==pTable->pSchema );
80672     if( !db || db->pnBytesFreed==0 ){
80673       char *zName = pIndex->zName; 
80674       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
80675          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
80676       );
80677       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
80678       assert( pOld==pIndex || pOld==0 );
80679     }
80680     freeIndex(db, pIndex);
80681   }
80682
80683   /* Delete any foreign keys attached to this table. */
80684   sqlite3FkDelete(db, pTable);
80685
80686   /* Delete the Table structure itself.
80687   */
80688   sqliteDeleteColumnNames(db, pTable);
80689   sqlite3DbFree(db, pTable->zName);
80690   sqlite3DbFree(db, pTable->zColAff);
80691   sqlite3SelectDelete(db, pTable->pSelect);
80692 #ifndef SQLITE_OMIT_CHECK
80693   sqlite3ExprListDelete(db, pTable->pCheck);
80694 #endif
80695 #ifndef SQLITE_OMIT_VIRTUALTABLE
80696   sqlite3VtabClear(db, pTable);
80697 #endif
80698   sqlite3DbFree(db, pTable);
80699
80700   /* Verify that no lookaside memory was used by schema tables */
80701   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
80702 }
80703
80704 /*
80705 ** Unlink the given table from the hash tables and the delete the
80706 ** table structure with all its indices and foreign keys.
80707 */
80708 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
80709   Table *p;
80710   Db *pDb;
80711
80712   assert( db!=0 );
80713   assert( iDb>=0 && iDb<db->nDb );
80714   assert( zTabName );
80715   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80716   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
80717   pDb = &db->aDb[iDb];
80718   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
80719                         sqlite3Strlen30(zTabName),0);
80720   sqlite3DeleteTable(db, p);
80721   db->flags |= SQLITE_InternChanges;
80722 }
80723
80724 /*
80725 ** Given a token, return a string that consists of the text of that
80726 ** token.  Space to hold the returned string
80727 ** is obtained from sqliteMalloc() and must be freed by the calling
80728 ** function.
80729 **
80730 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
80731 ** surround the body of the token are removed.
80732 **
80733 ** Tokens are often just pointers into the original SQL text and so
80734 ** are not \000 terminated and are not persistent.  The returned string
80735 ** is \000 terminated and is persistent.
80736 */
80737 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
80738   char *zName;
80739   if( pName ){
80740     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
80741     sqlite3Dequote(zName);
80742   }else{
80743     zName = 0;
80744   }
80745   return zName;
80746 }
80747
80748 /*
80749 ** Open the sqlite_master table stored in database number iDb for
80750 ** writing. The table is opened using cursor 0.
80751 */
80752 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
80753   Vdbe *v = sqlite3GetVdbe(p);
80754   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
80755   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
80756   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
80757   if( p->nTab==0 ){
80758     p->nTab = 1;
80759   }
80760 }
80761
80762 /*
80763 ** Parameter zName points to a nul-terminated buffer containing the name
80764 ** of a database ("main", "temp" or the name of an attached db). This
80765 ** function returns the index of the named database in db->aDb[], or
80766 ** -1 if the named db cannot be found.
80767 */
80768 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
80769   int i = -1;         /* Database number */
80770   if( zName ){
80771     Db *pDb;
80772     int n = sqlite3Strlen30(zName);
80773     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
80774       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
80775           0==sqlite3StrICmp(pDb->zName, zName) ){
80776         break;
80777       }
80778     }
80779   }
80780   return i;
80781 }
80782
80783 /*
80784 ** The token *pName contains the name of a database (either "main" or
80785 ** "temp" or the name of an attached db). This routine returns the
80786 ** index of the named database in db->aDb[], or -1 if the named db 
80787 ** does not exist.
80788 */
80789 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
80790   int i;                               /* Database number */
80791   char *zName;                         /* Name we are searching for */
80792   zName = sqlite3NameFromToken(db, pName);
80793   i = sqlite3FindDbName(db, zName);
80794   sqlite3DbFree(db, zName);
80795   return i;
80796 }
80797
80798 /* The table or view or trigger name is passed to this routine via tokens
80799 ** pName1 and pName2. If the table name was fully qualified, for example:
80800 **
80801 ** CREATE TABLE xxx.yyy (...);
80802 ** 
80803 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
80804 ** the table name is not fully qualified, i.e.:
80805 **
80806 ** CREATE TABLE yyy(...);
80807 **
80808 ** Then pName1 is set to "yyy" and pName2 is "".
80809 **
80810 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
80811 ** pName2) that stores the unqualified table name.  The index of the
80812 ** database "xxx" is returned.
80813 */
80814 SQLITE_PRIVATE int sqlite3TwoPartName(
80815   Parse *pParse,      /* Parsing and code generating context */
80816   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
80817   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
80818   Token **pUnqual     /* Write the unqualified object name here */
80819 ){
80820   int iDb;                    /* Database holding the object */
80821   sqlite3 *db = pParse->db;
80822
80823   if( ALWAYS(pName2!=0) && pName2->n>0 ){
80824     if( db->init.busy ) {
80825       sqlite3ErrorMsg(pParse, "corrupt database");
80826       pParse->nErr++;
80827       return -1;
80828     }
80829     *pUnqual = pName2;
80830     iDb = sqlite3FindDb(db, pName1);
80831     if( iDb<0 ){
80832       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
80833       pParse->nErr++;
80834       return -1;
80835     }
80836   }else{
80837     assert( db->init.iDb==0 || db->init.busy );
80838     iDb = db->init.iDb;
80839     *pUnqual = pName1;
80840   }
80841   return iDb;
80842 }
80843
80844 /*
80845 ** This routine is used to check if the UTF-8 string zName is a legal
80846 ** unqualified name for a new schema object (table, index, view or
80847 ** trigger). All names are legal except those that begin with the string
80848 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
80849 ** is reserved for internal use.
80850 */
80851 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
80852   if( !pParse->db->init.busy && pParse->nested==0 
80853           && (pParse->db->flags & SQLITE_WriteSchema)==0
80854           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
80855     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
80856     return SQLITE_ERROR;
80857   }
80858   return SQLITE_OK;
80859 }
80860
80861 /*
80862 ** Begin constructing a new table representation in memory.  This is
80863 ** the first of several action routines that get called in response
80864 ** to a CREATE TABLE statement.  In particular, this routine is called
80865 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
80866 ** flag is true if the table should be stored in the auxiliary database
80867 ** file instead of in the main database file.  This is normally the case
80868 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
80869 ** CREATE and TABLE.
80870 **
80871 ** The new table record is initialized and put in pParse->pNewTable.
80872 ** As more of the CREATE TABLE statement is parsed, additional action
80873 ** routines will be called to add more information to this record.
80874 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
80875 ** is called to complete the construction of the new table record.
80876 */
80877 SQLITE_PRIVATE void sqlite3StartTable(
80878   Parse *pParse,   /* Parser context */
80879   Token *pName1,   /* First part of the name of the table or view */
80880   Token *pName2,   /* Second part of the name of the table or view */
80881   int isTemp,      /* True if this is a TEMP table */
80882   int isView,      /* True if this is a VIEW */
80883   int isVirtual,   /* True if this is a VIRTUAL table */
80884   int noErr        /* Do nothing if table already exists */
80885 ){
80886   Table *pTable;
80887   char *zName = 0; /* The name of the new table */
80888   sqlite3 *db = pParse->db;
80889   Vdbe *v;
80890   int iDb;         /* Database number to create the table in */
80891   Token *pName;    /* Unqualified name of the table to create */
80892
80893   /* The table or view name to create is passed to this routine via tokens
80894   ** pName1 and pName2. If the table name was fully qualified, for example:
80895   **
80896   ** CREATE TABLE xxx.yyy (...);
80897   ** 
80898   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
80899   ** the table name is not fully qualified, i.e.:
80900   **
80901   ** CREATE TABLE yyy(...);
80902   **
80903   ** Then pName1 is set to "yyy" and pName2 is "".
80904   **
80905   ** The call below sets the pName pointer to point at the token (pName1 or
80906   ** pName2) that stores the unqualified table name. The variable iDb is
80907   ** set to the index of the database that the table or view is to be
80908   ** created in.
80909   */
80910   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
80911   if( iDb<0 ) return;
80912   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
80913     /* If creating a temp table, the name may not be qualified. Unless 
80914     ** the database name is "temp" anyway.  */
80915     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
80916     return;
80917   }
80918   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
80919
80920   pParse->sNameToken = *pName;
80921   zName = sqlite3NameFromToken(db, pName);
80922   if( zName==0 ) return;
80923   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
80924     goto begin_table_error;
80925   }
80926   if( db->init.iDb==1 ) isTemp = 1;
80927 #ifndef SQLITE_OMIT_AUTHORIZATION
80928   assert( (isTemp & 1)==isTemp );
80929   {
80930     int code;
80931     char *zDb = db->aDb[iDb].zName;
80932     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
80933       goto begin_table_error;
80934     }
80935     if( isView ){
80936       if( !OMIT_TEMPDB && isTemp ){
80937         code = SQLITE_CREATE_TEMP_VIEW;
80938       }else{
80939         code = SQLITE_CREATE_VIEW;
80940       }
80941     }else{
80942       if( !OMIT_TEMPDB && isTemp ){
80943         code = SQLITE_CREATE_TEMP_TABLE;
80944       }else{
80945         code = SQLITE_CREATE_TABLE;
80946       }
80947     }
80948     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
80949       goto begin_table_error;
80950     }
80951   }
80952 #endif
80953
80954   /* Make sure the new table name does not collide with an existing
80955   ** index or table name in the same database.  Issue an error message if
80956   ** it does. The exception is if the statement being parsed was passed
80957   ** to an sqlite3_declare_vtab() call. In that case only the column names
80958   ** and types will be used, so there is no need to test for namespace
80959   ** collisions.
80960   */
80961   if( !IN_DECLARE_VTAB ){
80962     char *zDb = db->aDb[iDb].zName;
80963     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80964       goto begin_table_error;
80965     }
80966     pTable = sqlite3FindTable(db, zName, zDb);
80967     if( pTable ){
80968       if( !noErr ){
80969         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
80970       }else{
80971         assert( !db->init.busy );
80972         sqlite3CodeVerifySchema(pParse, iDb);
80973       }
80974       goto begin_table_error;
80975     }
80976     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
80977       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
80978       goto begin_table_error;
80979     }
80980   }
80981
80982   pTable = sqlite3DbMallocZero(db, sizeof(Table));
80983   if( pTable==0 ){
80984     db->mallocFailed = 1;
80985     pParse->rc = SQLITE_NOMEM;
80986     pParse->nErr++;
80987     goto begin_table_error;
80988   }
80989   pTable->zName = zName;
80990   pTable->iPKey = -1;
80991   pTable->pSchema = db->aDb[iDb].pSchema;
80992   pTable->nRef = 1;
80993   pTable->nRowEst = 1000000;
80994   assert( pParse->pNewTable==0 );
80995   pParse->pNewTable = pTable;
80996
80997   /* If this is the magic sqlite_sequence table used by autoincrement,
80998   ** then record a pointer to this table in the main database structure
80999   ** so that INSERT can find the table easily.
81000   */
81001 #ifndef SQLITE_OMIT_AUTOINCREMENT
81002   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
81003     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81004     pTable->pSchema->pSeqTab = pTable;
81005   }
81006 #endif
81007
81008   /* Begin generating the code that will insert the table record into
81009   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
81010   ** and allocate the record number for the table entry now.  Before any
81011   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81012   ** indices to be created and the table record must come before the 
81013   ** indices.  Hence, the record number for the table must be allocated
81014   ** now.
81015   */
81016   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
81017     int j1;
81018     int fileFormat;
81019     int reg1, reg2, reg3;
81020     sqlite3BeginWriteOperation(pParse, 0, iDb);
81021
81022 #ifndef SQLITE_OMIT_VIRTUALTABLE
81023     if( isVirtual ){
81024       sqlite3VdbeAddOp0(v, OP_VBegin);
81025     }
81026 #endif
81027
81028     /* If the file format and encoding in the database have not been set, 
81029     ** set them now.
81030     */
81031     reg1 = pParse->regRowid = ++pParse->nMem;
81032     reg2 = pParse->regRoot = ++pParse->nMem;
81033     reg3 = ++pParse->nMem;
81034     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81035     sqlite3VdbeUsesBtree(v, iDb);
81036     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
81037     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
81038                   1 : SQLITE_MAX_FILE_FORMAT;
81039     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81040     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81041     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81042     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81043     sqlite3VdbeJumpHere(v, j1);
81044
81045     /* This just creates a place-holder record in the sqlite_master table.
81046     ** The record created does not contain anything yet.  It will be replaced
81047     ** by the real entry in code generated at sqlite3EndTable().
81048     **
81049     ** The rowid for the new entry is left in register pParse->regRowid.
81050     ** The root page number of the new table is left in reg pParse->regRoot.
81051     ** The rowid and root page number values are needed by the code that
81052     ** sqlite3EndTable will generate.
81053     */
81054 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81055     if( isView || isVirtual ){
81056       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
81057     }else
81058 #endif
81059     {
81060       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81061     }
81062     sqlite3OpenMasterTable(pParse, iDb);
81063     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81064     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
81065     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81066     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81067     sqlite3VdbeAddOp0(v, OP_Close);
81068   }
81069
81070   /* Normal (non-error) return. */
81071   return;
81072
81073   /* If an error occurs, we jump here */
81074 begin_table_error:
81075   sqlite3DbFree(db, zName);
81076   return;
81077 }
81078
81079 /*
81080 ** This macro is used to compare two strings in a case-insensitive manner.
81081 ** It is slightly faster than calling sqlite3StrICmp() directly, but
81082 ** produces larger code.
81083 **
81084 ** WARNING: This macro is not compatible with the strcmp() family. It
81085 ** returns true if the two strings are equal, otherwise false.
81086 */
81087 #define STRICMP(x, y) (\
81088 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
81089 sqlite3UpperToLower[*(unsigned char *)(y)]     \
81090 && sqlite3StrICmp((x)+1,(y)+1)==0 )
81091
81092 /*
81093 ** Add a new column to the table currently being constructed.
81094 **
81095 ** The parser calls this routine once for each column declaration
81096 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
81097 ** first to get things going.  Then this routine is called for each
81098 ** column.
81099 */
81100 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
81101   Table *p;
81102   int i;
81103   char *z;
81104   Column *pCol;
81105   sqlite3 *db = pParse->db;
81106   if( (p = pParse->pNewTable)==0 ) return;
81107 #if SQLITE_MAX_COLUMN
81108   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81109     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
81110     return;
81111   }
81112 #endif
81113   z = sqlite3NameFromToken(db, pName);
81114   if( z==0 ) return;
81115   for(i=0; i<p->nCol; i++){
81116     if( STRICMP(z, p->aCol[i].zName) ){
81117       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
81118       sqlite3DbFree(db, z);
81119       return;
81120     }
81121   }
81122   if( (p->nCol & 0x7)==0 ){
81123     Column *aNew;
81124     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81125     if( aNew==0 ){
81126       sqlite3DbFree(db, z);
81127       return;
81128     }
81129     p->aCol = aNew;
81130   }
81131   pCol = &p->aCol[p->nCol];
81132   memset(pCol, 0, sizeof(p->aCol[0]));
81133   pCol->zName = z;
81134  
81135   /* If there is no type specified, columns have the default affinity
81136   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
81137   ** be called next to set pCol->affinity correctly.
81138   */
81139   pCol->affinity = SQLITE_AFF_NONE;
81140   p->nCol++;
81141 }
81142
81143 /*
81144 ** This routine is called by the parser while in the middle of
81145 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81146 ** been seen on a column.  This routine sets the notNull flag on
81147 ** the column currently under construction.
81148 */
81149 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
81150   Table *p;
81151   p = pParse->pNewTable;
81152   if( p==0 || NEVER(p->nCol<1) ) return;
81153   p->aCol[p->nCol-1].notNull = (u8)onError;
81154 }
81155
81156 /*
81157 ** Scan the column type name zType (length nType) and return the
81158 ** associated affinity type.
81159 **
81160 ** This routine does a case-independent search of zType for the 
81161 ** substrings in the following table. If one of the substrings is
81162 ** found, the corresponding affinity is returned. If zType contains
81163 ** more than one of the substrings, entries toward the top of 
81164 ** the table take priority. For example, if zType is 'BLOBINT', 
81165 ** SQLITE_AFF_INTEGER is returned.
81166 **
81167 ** Substring     | Affinity
81168 ** --------------------------------
81169 ** 'INT'         | SQLITE_AFF_INTEGER
81170 ** 'CHAR'        | SQLITE_AFF_TEXT
81171 ** 'CLOB'        | SQLITE_AFF_TEXT
81172 ** 'TEXT'        | SQLITE_AFF_TEXT
81173 ** 'BLOB'        | SQLITE_AFF_NONE
81174 ** 'REAL'        | SQLITE_AFF_REAL
81175 ** 'FLOA'        | SQLITE_AFF_REAL
81176 ** 'DOUB'        | SQLITE_AFF_REAL
81177 **
81178 ** If none of the substrings in the above table are found,
81179 ** SQLITE_AFF_NUMERIC is returned.
81180 */
81181 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
81182   u32 h = 0;
81183   char aff = SQLITE_AFF_NUMERIC;
81184
81185   if( zIn ) while( zIn[0] ){
81186     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
81187     zIn++;
81188     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
81189       aff = SQLITE_AFF_TEXT; 
81190     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
81191       aff = SQLITE_AFF_TEXT;
81192     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
81193       aff = SQLITE_AFF_TEXT;
81194     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
81195         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
81196       aff = SQLITE_AFF_NONE;
81197 #ifndef SQLITE_OMIT_FLOATING_POINT
81198     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
81199         && aff==SQLITE_AFF_NUMERIC ){
81200       aff = SQLITE_AFF_REAL;
81201     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
81202         && aff==SQLITE_AFF_NUMERIC ){
81203       aff = SQLITE_AFF_REAL;
81204     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
81205         && aff==SQLITE_AFF_NUMERIC ){
81206       aff = SQLITE_AFF_REAL;
81207 #endif
81208     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
81209       aff = SQLITE_AFF_INTEGER;
81210       break;
81211     }
81212   }
81213
81214   return aff;
81215 }
81216
81217 /*
81218 ** This routine is called by the parser while in the middle of
81219 ** parsing a CREATE TABLE statement.  The pFirst token is the first
81220 ** token in the sequence of tokens that describe the type of the
81221 ** column currently under construction.   pLast is the last token
81222 ** in the sequence.  Use this information to construct a string
81223 ** that contains the typename of the column and store that string
81224 ** in zType.
81225 */ 
81226 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
81227   Table *p;
81228   Column *pCol;
81229
81230   p = pParse->pNewTable;
81231   if( p==0 || NEVER(p->nCol<1) ) return;
81232   pCol = &p->aCol[p->nCol-1];
81233   assert( pCol->zType==0 );
81234   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
81235   pCol->affinity = sqlite3AffinityType(pCol->zType);
81236 }
81237
81238 /*
81239 ** The expression is the default value for the most recently added column
81240 ** of the table currently under construction.
81241 **
81242 ** Default value expressions must be constant.  Raise an exception if this
81243 ** is not the case.
81244 **
81245 ** This routine is called by the parser while in the middle of
81246 ** parsing a CREATE TABLE statement.
81247 */
81248 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
81249   Table *p;
81250   Column *pCol;
81251   sqlite3 *db = pParse->db;
81252   p = pParse->pNewTable;
81253   if( p!=0 ){
81254     pCol = &(p->aCol[p->nCol-1]);
81255     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
81256       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
81257           pCol->zName);
81258     }else{
81259       /* A copy of pExpr is used instead of the original, as pExpr contains
81260       ** tokens that point to volatile memory. The 'span' of the expression
81261       ** is required by pragma table_info.
81262       */
81263       sqlite3ExprDelete(db, pCol->pDflt);
81264       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
81265       sqlite3DbFree(db, pCol->zDflt);
81266       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
81267                                      (int)(pSpan->zEnd - pSpan->zStart));
81268     }
81269   }
81270   sqlite3ExprDelete(db, pSpan->pExpr);
81271 }
81272
81273 /*
81274 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
81275 ** of columns that form the primary key.  If pList is NULL, then the
81276 ** most recently added column of the table is the primary key.
81277 **
81278 ** A table can have at most one primary key.  If the table already has
81279 ** a primary key (and this is the second primary key) then create an
81280 ** error.
81281 **
81282 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
81283 ** then we will try to use that column as the rowid.  Set the Table.iPKey
81284 ** field of the table under construction to be the index of the
81285 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
81286 ** no INTEGER PRIMARY KEY.
81287 **
81288 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
81289 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
81290 */
81291 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
81292   Parse *pParse,    /* Parsing context */
81293   ExprList *pList,  /* List of field names to be indexed */
81294   int onError,      /* What to do with a uniqueness conflict */
81295   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
81296   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
81297 ){
81298   Table *pTab = pParse->pNewTable;
81299   char *zType = 0;
81300   int iCol = -1, i;
81301   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
81302   if( pTab->tabFlags & TF_HasPrimaryKey ){
81303     sqlite3ErrorMsg(pParse, 
81304       "table \"%s\" has more than one primary key", pTab->zName);
81305     goto primary_key_exit;
81306   }
81307   pTab->tabFlags |= TF_HasPrimaryKey;
81308   if( pList==0 ){
81309     iCol = pTab->nCol - 1;
81310     pTab->aCol[iCol].isPrimKey = 1;
81311   }else{
81312     for(i=0; i<pList->nExpr; i++){
81313       for(iCol=0; iCol<pTab->nCol; iCol++){
81314         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
81315           break;
81316         }
81317       }
81318       if( iCol<pTab->nCol ){
81319         pTab->aCol[iCol].isPrimKey = 1;
81320       }
81321     }
81322     if( pList->nExpr>1 ) iCol = -1;
81323   }
81324   if( iCol>=0 && iCol<pTab->nCol ){
81325     zType = pTab->aCol[iCol].zType;
81326   }
81327   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
81328         && sortOrder==SQLITE_SO_ASC ){
81329     pTab->iPKey = iCol;
81330     pTab->keyConf = (u8)onError;
81331     assert( autoInc==0 || autoInc==1 );
81332     pTab->tabFlags |= autoInc*TF_Autoincrement;
81333   }else if( autoInc ){
81334 #ifndef SQLITE_OMIT_AUTOINCREMENT
81335     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
81336        "INTEGER PRIMARY KEY");
81337 #endif
81338   }else{
81339     Index *p;
81340     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
81341     if( p ){
81342       p->autoIndex = 2;
81343     }
81344     pList = 0;
81345   }
81346
81347 primary_key_exit:
81348   sqlite3ExprListDelete(pParse->db, pList);
81349   return;
81350 }
81351
81352 /*
81353 ** Add a new CHECK constraint to the table currently under construction.
81354 */
81355 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
81356   Parse *pParse,    /* Parsing context */
81357   Expr *pCheckExpr  /* The check expression */
81358 ){
81359 #ifndef SQLITE_OMIT_CHECK
81360   Table *pTab = pParse->pNewTable;
81361   if( pTab && !IN_DECLARE_VTAB ){
81362     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
81363     if( pParse->constraintName.n ){
81364       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
81365     }
81366   }else
81367 #endif
81368   {
81369     sqlite3ExprDelete(pParse->db, pCheckExpr);
81370   }
81371 }
81372
81373 /*
81374 ** Set the collation function of the most recently parsed table column
81375 ** to the CollSeq given.
81376 */
81377 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
81378   Table *p;
81379   int i;
81380   char *zColl;              /* Dequoted name of collation sequence */
81381   sqlite3 *db;
81382
81383   if( (p = pParse->pNewTable)==0 ) return;
81384   i = p->nCol-1;
81385   db = pParse->db;
81386   zColl = sqlite3NameFromToken(db, pToken);
81387   if( !zColl ) return;
81388
81389   if( sqlite3LocateCollSeq(pParse, zColl) ){
81390     Index *pIdx;
81391     p->aCol[i].zColl = zColl;
81392   
81393     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
81394     ** then an index may have been created on this column before the
81395     ** collation type was added. Correct this if it is the case.
81396     */
81397     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
81398       assert( pIdx->nColumn==1 );
81399       if( pIdx->aiColumn[0]==i ){
81400         pIdx->azColl[0] = p->aCol[i].zColl;
81401       }
81402     }
81403   }else{
81404     sqlite3DbFree(db, zColl);
81405   }
81406 }
81407
81408 /*
81409 ** This function returns the collation sequence for database native text
81410 ** encoding identified by the string zName, length nName.
81411 **
81412 ** If the requested collation sequence is not available, or not available
81413 ** in the database native encoding, the collation factory is invoked to
81414 ** request it. If the collation factory does not supply such a sequence,
81415 ** and the sequence is available in another text encoding, then that is
81416 ** returned instead.
81417 **
81418 ** If no versions of the requested collations sequence are available, or
81419 ** another error occurs, NULL is returned and an error message written into
81420 ** pParse.
81421 **
81422 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
81423 ** invokes the collation factory if the named collation cannot be found
81424 ** and generates an error message.
81425 **
81426 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
81427 */
81428 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
81429   sqlite3 *db = pParse->db;
81430   u8 enc = ENC(db);
81431   u8 initbusy = db->init.busy;
81432   CollSeq *pColl;
81433
81434   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
81435   if( !initbusy && (!pColl || !pColl->xCmp) ){
81436     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
81437     if( !pColl ){
81438       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
81439     }
81440   }
81441
81442   return pColl;
81443 }
81444
81445
81446 /*
81447 ** Generate code that will increment the schema cookie.
81448 **
81449 ** The schema cookie is used to determine when the schema for the
81450 ** database changes.  After each schema change, the cookie value
81451 ** changes.  When a process first reads the schema it records the
81452 ** cookie.  Thereafter, whenever it goes to access the database,
81453 ** it checks the cookie to make sure the schema has not changed
81454 ** since it was last read.
81455 **
81456 ** This plan is not completely bullet-proof.  It is possible for
81457 ** the schema to change multiple times and for the cookie to be
81458 ** set back to prior value.  But schema changes are infrequent
81459 ** and the probability of hitting the same cookie value is only
81460 ** 1 chance in 2^32.  So we're safe enough.
81461 */
81462 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
81463   int r1 = sqlite3GetTempReg(pParse);
81464   sqlite3 *db = pParse->db;
81465   Vdbe *v = pParse->pVdbe;
81466   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81467   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
81468   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
81469   sqlite3ReleaseTempReg(pParse, r1);
81470 }
81471
81472 /*
81473 ** Measure the number of characters needed to output the given
81474 ** identifier.  The number returned includes any quotes used
81475 ** but does not include the null terminator.
81476 **
81477 ** The estimate is conservative.  It might be larger that what is
81478 ** really needed.
81479 */
81480 static int identLength(const char *z){
81481   int n;
81482   for(n=0; *z; n++, z++){
81483     if( *z=='"' ){ n++; }
81484   }
81485   return n + 2;
81486 }
81487
81488 /*
81489 ** The first parameter is a pointer to an output buffer. The second 
81490 ** parameter is a pointer to an integer that contains the offset at
81491 ** which to write into the output buffer. This function copies the
81492 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
81493 ** to the specified offset in the buffer and updates *pIdx to refer
81494 ** to the first byte after the last byte written before returning.
81495 ** 
81496 ** If the string zSignedIdent consists entirely of alpha-numeric
81497 ** characters, does not begin with a digit and is not an SQL keyword,
81498 ** then it is copied to the output buffer exactly as it is. Otherwise,
81499 ** it is quoted using double-quotes.
81500 */
81501 static void identPut(char *z, int *pIdx, char *zSignedIdent){
81502   unsigned char *zIdent = (unsigned char*)zSignedIdent;
81503   int i, j, needQuote;
81504   i = *pIdx;
81505
81506   for(j=0; zIdent[j]; j++){
81507     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
81508   }
81509   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
81510   if( !needQuote ){
81511     needQuote = zIdent[j];
81512   }
81513
81514   if( needQuote ) z[i++] = '"';
81515   for(j=0; zIdent[j]; j++){
81516     z[i++] = zIdent[j];
81517     if( zIdent[j]=='"' ) z[i++] = '"';
81518   }
81519   if( needQuote ) z[i++] = '"';
81520   z[i] = 0;
81521   *pIdx = i;
81522 }
81523
81524 /*
81525 ** Generate a CREATE TABLE statement appropriate for the given
81526 ** table.  Memory to hold the text of the statement is obtained
81527 ** from sqliteMalloc() and must be freed by the calling function.
81528 */
81529 static char *createTableStmt(sqlite3 *db, Table *p){
81530   int i, k, n;
81531   char *zStmt;
81532   char *zSep, *zSep2, *zEnd;
81533   Column *pCol;
81534   n = 0;
81535   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
81536     n += identLength(pCol->zName) + 5;
81537   }
81538   n += identLength(p->zName);
81539   if( n<50 ){ 
81540     zSep = "";
81541     zSep2 = ",";
81542     zEnd = ")";
81543   }else{
81544     zSep = "\n  ";
81545     zSep2 = ",\n  ";
81546     zEnd = "\n)";
81547   }
81548   n += 35 + 6*p->nCol;
81549   zStmt = sqlite3DbMallocRaw(0, n);
81550   if( zStmt==0 ){
81551     db->mallocFailed = 1;
81552     return 0;
81553   }
81554   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
81555   k = sqlite3Strlen30(zStmt);
81556   identPut(zStmt, &k, p->zName);
81557   zStmt[k++] = '(';
81558   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
81559     static const char * const azType[] = {
81560         /* SQLITE_AFF_TEXT    */ " TEXT",
81561         /* SQLITE_AFF_NONE    */ "",
81562         /* SQLITE_AFF_NUMERIC */ " NUM",
81563         /* SQLITE_AFF_INTEGER */ " INT",
81564         /* SQLITE_AFF_REAL    */ " REAL"
81565     };
81566     int len;
81567     const char *zType;
81568
81569     sqlite3_snprintf(n-k, &zStmt[k], zSep);
81570     k += sqlite3Strlen30(&zStmt[k]);
81571     zSep = zSep2;
81572     identPut(zStmt, &k, pCol->zName);
81573     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
81574     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
81575     testcase( pCol->affinity==SQLITE_AFF_TEXT );
81576     testcase( pCol->affinity==SQLITE_AFF_NONE );
81577     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
81578     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
81579     testcase( pCol->affinity==SQLITE_AFF_REAL );
81580     
81581     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
81582     len = sqlite3Strlen30(zType);
81583     assert( pCol->affinity==SQLITE_AFF_NONE 
81584             || pCol->affinity==sqlite3AffinityType(zType) );
81585     memcpy(&zStmt[k], zType, len);
81586     k += len;
81587     assert( k<=n );
81588   }
81589   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
81590   return zStmt;
81591 }
81592
81593 /*
81594 ** This routine is called to report the final ")" that terminates
81595 ** a CREATE TABLE statement.
81596 **
81597 ** The table structure that other action routines have been building
81598 ** is added to the internal hash tables, assuming no errors have
81599 ** occurred.
81600 **
81601 ** An entry for the table is made in the master table on disk, unless
81602 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
81603 ** it means we are reading the sqlite_master table because we just
81604 ** connected to the database or because the sqlite_master table has
81605 ** recently changed, so the entry for this table already exists in
81606 ** the sqlite_master table.  We do not want to create it again.
81607 **
81608 ** If the pSelect argument is not NULL, it means that this routine
81609 ** was called to create a table generated from a 
81610 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
81611 ** the new table will match the result set of the SELECT.
81612 */
81613 SQLITE_PRIVATE void sqlite3EndTable(
81614   Parse *pParse,          /* Parse context */
81615   Token *pCons,           /* The ',' token after the last column defn. */
81616   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
81617   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
81618 ){
81619   Table *p;
81620   sqlite3 *db = pParse->db;
81621   int iDb;
81622
81623   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
81624     return;
81625   }
81626   p = pParse->pNewTable;
81627   if( p==0 ) return;
81628
81629   assert( !db->init.busy || !pSelect );
81630
81631   iDb = sqlite3SchemaToIndex(db, p->pSchema);
81632
81633 #ifndef SQLITE_OMIT_CHECK
81634   /* Resolve names in all CHECK constraint expressions.
81635   */
81636   if( p->pCheck ){
81637     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
81638     NameContext sNC;                /* Name context for pParse->pNewTable */
81639     ExprList *pList;                /* List of all CHECK constraints */
81640     int i;                          /* Loop counter */
81641
81642     memset(&sNC, 0, sizeof(sNC));
81643     memset(&sSrc, 0, sizeof(sSrc));
81644     sSrc.nSrc = 1;
81645     sSrc.a[0].zName = p->zName;
81646     sSrc.a[0].pTab = p;
81647     sSrc.a[0].iCursor = -1;
81648     sNC.pParse = pParse;
81649     sNC.pSrcList = &sSrc;
81650     sNC.ncFlags = NC_IsCheck;
81651     pList = p->pCheck;
81652     for(i=0; i<pList->nExpr; i++){
81653       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
81654         return;
81655       }
81656     }
81657   }
81658 #endif /* !defined(SQLITE_OMIT_CHECK) */
81659
81660   /* If the db->init.busy is 1 it means we are reading the SQL off the
81661   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
81662   ** So do not write to the disk again.  Extract the root page number
81663   ** for the table from the db->init.newTnum field.  (The page number
81664   ** should have been put there by the sqliteOpenCb routine.)
81665   */
81666   if( db->init.busy ){
81667     p->tnum = db->init.newTnum;
81668   }
81669
81670   /* If not initializing, then create a record for the new table
81671   ** in the SQLITE_MASTER table of the database.
81672   **
81673   ** If this is a TEMPORARY table, write the entry into the auxiliary
81674   ** file instead of into the main database file.
81675   */
81676   if( !db->init.busy ){
81677     int n;
81678     Vdbe *v;
81679     char *zType;    /* "view" or "table" */
81680     char *zType2;   /* "VIEW" or "TABLE" */
81681     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
81682
81683     v = sqlite3GetVdbe(pParse);
81684     if( NEVER(v==0) ) return;
81685
81686     sqlite3VdbeAddOp1(v, OP_Close, 0);
81687
81688     /* 
81689     ** Initialize zType for the new view or table.
81690     */
81691     if( p->pSelect==0 ){
81692       /* A regular table */
81693       zType = "table";
81694       zType2 = "TABLE";
81695 #ifndef SQLITE_OMIT_VIEW
81696     }else{
81697       /* A view */
81698       zType = "view";
81699       zType2 = "VIEW";
81700 #endif
81701     }
81702
81703     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
81704     ** statement to populate the new table. The root-page number for the
81705     ** new table is in register pParse->regRoot.
81706     **
81707     ** Once the SELECT has been coded by sqlite3Select(), it is in a
81708     ** suitable state to query for the column names and types to be used
81709     ** by the new table.
81710     **
81711     ** A shared-cache write-lock is not required to write to the new table,
81712     ** as a schema-lock must have already been obtained to create it. Since
81713     ** a schema-lock excludes all other database users, the write-lock would
81714     ** be redundant.
81715     */
81716     if( pSelect ){
81717       SelectDest dest;
81718       Table *pSelTab;
81719
81720       assert(pParse->nTab==1);
81721       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
81722       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
81723       pParse->nTab = 2;
81724       sqlite3SelectDestInit(&dest, SRT_Table, 1);
81725       sqlite3Select(pParse, pSelect, &dest);
81726       sqlite3VdbeAddOp1(v, OP_Close, 1);
81727       if( pParse->nErr==0 ){
81728         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
81729         if( pSelTab==0 ) return;
81730         assert( p->aCol==0 );
81731         p->nCol = pSelTab->nCol;
81732         p->aCol = pSelTab->aCol;
81733         pSelTab->nCol = 0;
81734         pSelTab->aCol = 0;
81735         sqlite3DeleteTable(db, pSelTab);
81736       }
81737     }
81738
81739     /* Compute the complete text of the CREATE statement */
81740     if( pSelect ){
81741       zStmt = createTableStmt(db, p);
81742     }else{
81743       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
81744       zStmt = sqlite3MPrintf(db, 
81745           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
81746       );
81747     }
81748
81749     /* A slot for the record has already been allocated in the 
81750     ** SQLITE_MASTER table.  We just need to update that slot with all
81751     ** the information we've collected.
81752     */
81753     sqlite3NestedParse(pParse,
81754       "UPDATE %Q.%s "
81755          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
81756        "WHERE rowid=#%d",
81757       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
81758       zType,
81759       p->zName,
81760       p->zName,
81761       pParse->regRoot,
81762       zStmt,
81763       pParse->regRowid
81764     );
81765     sqlite3DbFree(db, zStmt);
81766     sqlite3ChangeCookie(pParse, iDb);
81767
81768 #ifndef SQLITE_OMIT_AUTOINCREMENT
81769     /* Check to see if we need to create an sqlite_sequence table for
81770     ** keeping track of autoincrement keys.
81771     */
81772     if( p->tabFlags & TF_Autoincrement ){
81773       Db *pDb = &db->aDb[iDb];
81774       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81775       if( pDb->pSchema->pSeqTab==0 ){
81776         sqlite3NestedParse(pParse,
81777           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
81778           pDb->zName
81779         );
81780       }
81781     }
81782 #endif
81783
81784     /* Reparse everything to update our internal data structures */
81785     sqlite3VdbeAddParseSchemaOp(v, iDb,
81786                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
81787   }
81788
81789
81790   /* Add the table to the in-memory representation of the database.
81791   */
81792   if( db->init.busy ){
81793     Table *pOld;
81794     Schema *pSchema = p->pSchema;
81795     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81796     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
81797                              sqlite3Strlen30(p->zName),p);
81798     if( pOld ){
81799       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
81800       db->mallocFailed = 1;
81801       return;
81802     }
81803     pParse->pNewTable = 0;
81804     db->flags |= SQLITE_InternChanges;
81805
81806 #ifndef SQLITE_OMIT_ALTERTABLE
81807     if( !p->pSelect ){
81808       const char *zName = (const char *)pParse->sNameToken.z;
81809       int nName;
81810       assert( !pSelect && pCons && pEnd );
81811       if( pCons->z==0 ){
81812         pCons = pEnd;
81813       }
81814       nName = (int)((const char *)pCons->z - zName);
81815       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
81816     }
81817 #endif
81818   }
81819 }
81820
81821 #ifndef SQLITE_OMIT_VIEW
81822 /*
81823 ** The parser calls this routine in order to create a new VIEW
81824 */
81825 SQLITE_PRIVATE void sqlite3CreateView(
81826   Parse *pParse,     /* The parsing context */
81827   Token *pBegin,     /* The CREATE token that begins the statement */
81828   Token *pName1,     /* The token that holds the name of the view */
81829   Token *pName2,     /* The token that holds the name of the view */
81830   Select *pSelect,   /* A SELECT statement that will become the new view */
81831   int isTemp,        /* TRUE for a TEMPORARY view */
81832   int noErr          /* Suppress error messages if VIEW already exists */
81833 ){
81834   Table *p;
81835   int n;
81836   const char *z;
81837   Token sEnd;
81838   DbFixer sFix;
81839   Token *pName = 0;
81840   int iDb;
81841   sqlite3 *db = pParse->db;
81842
81843   if( pParse->nVar>0 ){
81844     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
81845     sqlite3SelectDelete(db, pSelect);
81846     return;
81847   }
81848   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
81849   p = pParse->pNewTable;
81850   if( p==0 || pParse->nErr ){
81851     sqlite3SelectDelete(db, pSelect);
81852     return;
81853   }
81854   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81855   iDb = sqlite3SchemaToIndex(db, p->pSchema);
81856   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
81857     && sqlite3FixSelect(&sFix, pSelect)
81858   ){
81859     sqlite3SelectDelete(db, pSelect);
81860     return;
81861   }
81862
81863   /* Make a copy of the entire SELECT statement that defines the view.
81864   ** This will force all the Expr.token.z values to be dynamically
81865   ** allocated rather than point to the input string - which means that
81866   ** they will persist after the current sqlite3_exec() call returns.
81867   */
81868   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
81869   sqlite3SelectDelete(db, pSelect);
81870   if( db->mallocFailed ){
81871     return;
81872   }
81873   if( !db->init.busy ){
81874     sqlite3ViewGetColumnNames(pParse, p);
81875   }
81876
81877   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
81878   ** the end.
81879   */
81880   sEnd = pParse->sLastToken;
81881   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
81882     sEnd.z += sEnd.n;
81883   }
81884   sEnd.n = 0;
81885   n = (int)(sEnd.z - pBegin->z);
81886   z = pBegin->z;
81887   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
81888   sEnd.z = &z[n-1];
81889   sEnd.n = 1;
81890
81891   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
81892   sqlite3EndTable(pParse, 0, &sEnd, 0);
81893   return;
81894 }
81895 #endif /* SQLITE_OMIT_VIEW */
81896
81897 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81898 /*
81899 ** The Table structure pTable is really a VIEW.  Fill in the names of
81900 ** the columns of the view in the pTable structure.  Return the number
81901 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
81902 */
81903 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
81904   Table *pSelTab;   /* A fake table from which we get the result set */
81905   Select *pSel;     /* Copy of the SELECT that implements the view */
81906   int nErr = 0;     /* Number of errors encountered */
81907   int n;            /* Temporarily holds the number of cursors assigned */
81908   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
81909   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
81910
81911   assert( pTable );
81912
81913 #ifndef SQLITE_OMIT_VIRTUALTABLE
81914   if( sqlite3VtabCallConnect(pParse, pTable) ){
81915     return SQLITE_ERROR;
81916   }
81917   if( IsVirtual(pTable) ) return 0;
81918 #endif
81919
81920 #ifndef SQLITE_OMIT_VIEW
81921   /* A positive nCol means the columns names for this view are
81922   ** already known.
81923   */
81924   if( pTable->nCol>0 ) return 0;
81925
81926   /* A negative nCol is a special marker meaning that we are currently
81927   ** trying to compute the column names.  If we enter this routine with
81928   ** a negative nCol, it means two or more views form a loop, like this:
81929   **
81930   **     CREATE VIEW one AS SELECT * FROM two;
81931   **     CREATE VIEW two AS SELECT * FROM one;
81932   **
81933   ** Actually, the error above is now caught prior to reaching this point.
81934   ** But the following test is still important as it does come up
81935   ** in the following:
81936   ** 
81937   **     CREATE TABLE main.ex1(a);
81938   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
81939   **     SELECT * FROM temp.ex1;
81940   */
81941   if( pTable->nCol<0 ){
81942     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
81943     return 1;
81944   }
81945   assert( pTable->nCol>=0 );
81946
81947   /* If we get this far, it means we need to compute the table names.
81948   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
81949   ** "*" elements in the results set of the view and will assign cursors
81950   ** to the elements of the FROM clause.  But we do not want these changes
81951   ** to be permanent.  So the computation is done on a copy of the SELECT
81952   ** statement that defines the view.
81953   */
81954   assert( pTable->pSelect );
81955   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
81956   if( pSel ){
81957     u8 enableLookaside = db->lookaside.bEnabled;
81958     n = pParse->nTab;
81959     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
81960     pTable->nCol = -1;
81961     db->lookaside.bEnabled = 0;
81962 #ifndef SQLITE_OMIT_AUTHORIZATION
81963     xAuth = db->xAuth;
81964     db->xAuth = 0;
81965     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
81966     db->xAuth = xAuth;
81967 #else
81968     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
81969 #endif
81970     db->lookaside.bEnabled = enableLookaside;
81971     pParse->nTab = n;
81972     if( pSelTab ){
81973       assert( pTable->aCol==0 );
81974       pTable->nCol = pSelTab->nCol;
81975       pTable->aCol = pSelTab->aCol;
81976       pSelTab->nCol = 0;
81977       pSelTab->aCol = 0;
81978       sqlite3DeleteTable(db, pSelTab);
81979       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
81980       pTable->pSchema->flags |= DB_UnresetViews;
81981     }else{
81982       pTable->nCol = 0;
81983       nErr++;
81984     }
81985     sqlite3SelectDelete(db, pSel);
81986   } else {
81987     nErr++;
81988   }
81989 #endif /* SQLITE_OMIT_VIEW */
81990   return nErr;  
81991 }
81992 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
81993
81994 #ifndef SQLITE_OMIT_VIEW
81995 /*
81996 ** Clear the column names from every VIEW in database idx.
81997 */
81998 static void sqliteViewResetAll(sqlite3 *db, int idx){
81999   HashElem *i;
82000   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
82001   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82002   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
82003     Table *pTab = sqliteHashData(i);
82004     if( pTab->pSelect ){
82005       sqliteDeleteColumnNames(db, pTab);
82006       pTab->aCol = 0;
82007       pTab->nCol = 0;
82008     }
82009   }
82010   DbClearProperty(db, idx, DB_UnresetViews);
82011 }
82012 #else
82013 # define sqliteViewResetAll(A,B)
82014 #endif /* SQLITE_OMIT_VIEW */
82015
82016 /*
82017 ** This function is called by the VDBE to adjust the internal schema
82018 ** used by SQLite when the btree layer moves a table root page. The
82019 ** root-page of a table or index in database iDb has changed from iFrom
82020 ** to iTo.
82021 **
82022 ** Ticket #1728:  The symbol table might still contain information
82023 ** on tables and/or indices that are the process of being deleted.
82024 ** If you are unlucky, one of those deleted indices or tables might
82025 ** have the same rootpage number as the real table or index that is
82026 ** being moved.  So we cannot stop searching after the first match 
82027 ** because the first match might be for one of the deleted indices
82028 ** or tables and not the table/index that is actually being moved.
82029 ** We must continue looping until all tables and indices with
82030 ** rootpage==iFrom have been converted to have a rootpage of iTo
82031 ** in order to be certain that we got the right one.
82032 */
82033 #ifndef SQLITE_OMIT_AUTOVACUUM
82034 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
82035   HashElem *pElem;
82036   Hash *pHash;
82037   Db *pDb;
82038
82039   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82040   pDb = &db->aDb[iDb];
82041   pHash = &pDb->pSchema->tblHash;
82042   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82043     Table *pTab = sqliteHashData(pElem);
82044     if( pTab->tnum==iFrom ){
82045       pTab->tnum = iTo;
82046     }
82047   }
82048   pHash = &pDb->pSchema->idxHash;
82049   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82050     Index *pIdx = sqliteHashData(pElem);
82051     if( pIdx->tnum==iFrom ){
82052       pIdx->tnum = iTo;
82053     }
82054   }
82055 }
82056 #endif
82057
82058 /*
82059 ** Write code to erase the table with root-page iTable from database iDb.
82060 ** Also write code to modify the sqlite_master table and internal schema
82061 ** if a root-page of another table is moved by the btree-layer whilst
82062 ** erasing iTable (this can happen with an auto-vacuum database).
82063 */ 
82064 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82065   Vdbe *v = sqlite3GetVdbe(pParse);
82066   int r1 = sqlite3GetTempReg(pParse);
82067   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82068   sqlite3MayAbort(pParse);
82069 #ifndef SQLITE_OMIT_AUTOVACUUM
82070   /* OP_Destroy stores an in integer r1. If this integer
82071   ** is non-zero, then it is the root page number of a table moved to
82072   ** location iTable. The following code modifies the sqlite_master table to
82073   ** reflect this.
82074   **
82075   ** The "#NNN" in the SQL is a special constant that means whatever value
82076   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82077   ** token for additional information.
82078   */
82079   sqlite3NestedParse(pParse, 
82080      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82081      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82082 #endif
82083   sqlite3ReleaseTempReg(pParse, r1);
82084 }
82085
82086 /*
82087 ** Write VDBE code to erase table pTab and all associated indices on disk.
82088 ** Code to update the sqlite_master tables and internal schema definitions
82089 ** in case a root-page belonging to another table is moved by the btree layer
82090 ** is also added (this can happen with an auto-vacuum database).
82091 */
82092 static void destroyTable(Parse *pParse, Table *pTab){
82093 #ifdef SQLITE_OMIT_AUTOVACUUM
82094   Index *pIdx;
82095   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82096   destroyRootPage(pParse, pTab->tnum, iDb);
82097   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82098     destroyRootPage(pParse, pIdx->tnum, iDb);
82099   }
82100 #else
82101   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
82102   ** is not defined), then it is important to call OP_Destroy on the
82103   ** table and index root-pages in order, starting with the numerically 
82104   ** largest root-page number. This guarantees that none of the root-pages
82105   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82106   ** following were coded:
82107   **
82108   ** OP_Destroy 4 0
82109   ** ...
82110   ** OP_Destroy 5 0
82111   **
82112   ** and root page 5 happened to be the largest root-page number in the
82113   ** database, then root page 5 would be moved to page 4 by the 
82114   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82115   ** a free-list page.
82116   */
82117   int iTab = pTab->tnum;
82118   int iDestroyed = 0;
82119
82120   while( 1 ){
82121     Index *pIdx;
82122     int iLargest = 0;
82123
82124     if( iDestroyed==0 || iTab<iDestroyed ){
82125       iLargest = iTab;
82126     }
82127     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82128       int iIdx = pIdx->tnum;
82129       assert( pIdx->pSchema==pTab->pSchema );
82130       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82131         iLargest = iIdx;
82132       }
82133     }
82134     if( iLargest==0 ){
82135       return;
82136     }else{
82137       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82138       destroyRootPage(pParse, iLargest, iDb);
82139       iDestroyed = iLargest;
82140     }
82141   }
82142 #endif
82143 }
82144
82145 /*
82146 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
82147 ** after a DROP INDEX or DROP TABLE command.
82148 */
82149 static void sqlite3ClearStatTables(
82150   Parse *pParse,         /* The parsing context */
82151   int iDb,               /* The database number */
82152   const char *zType,     /* "idx" or "tbl" */
82153   const char *zName      /* Name of index or table */
82154 ){
82155   int i;
82156   const char *zDbName = pParse->db->aDb[iDb].zName;
82157   for(i=1; i<=3; i++){
82158     char zTab[24];
82159     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
82160     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
82161       sqlite3NestedParse(pParse,
82162         "DELETE FROM %Q.%s WHERE %s=%Q",
82163         zDbName, zTab, zType, zName
82164       );
82165     }
82166   }
82167 }
82168
82169 /*
82170 ** Generate code to drop a table.
82171 */
82172 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82173   Vdbe *v;
82174   sqlite3 *db = pParse->db;
82175   Trigger *pTrigger;
82176   Db *pDb = &db->aDb[iDb];
82177
82178   v = sqlite3GetVdbe(pParse);
82179   assert( v!=0 );
82180   sqlite3BeginWriteOperation(pParse, 1, iDb);
82181
82182 #ifndef SQLITE_OMIT_VIRTUALTABLE
82183   if( IsVirtual(pTab) ){
82184     sqlite3VdbeAddOp0(v, OP_VBegin);
82185   }
82186 #endif
82187
82188   /* Drop all triggers associated with the table being dropped. Code
82189   ** is generated to remove entries from sqlite_master and/or
82190   ** sqlite_temp_master if required.
82191   */
82192   pTrigger = sqlite3TriggerList(pParse, pTab);
82193   while( pTrigger ){
82194     assert( pTrigger->pSchema==pTab->pSchema || 
82195         pTrigger->pSchema==db->aDb[1].pSchema );
82196     sqlite3DropTriggerPtr(pParse, pTrigger);
82197     pTrigger = pTrigger->pNext;
82198   }
82199
82200 #ifndef SQLITE_OMIT_AUTOINCREMENT
82201   /* Remove any entries of the sqlite_sequence table associated with
82202   ** the table being dropped. This is done before the table is dropped
82203   ** at the btree level, in case the sqlite_sequence table needs to
82204   ** move as a result of the drop (can happen in auto-vacuum mode).
82205   */
82206   if( pTab->tabFlags & TF_Autoincrement ){
82207     sqlite3NestedParse(pParse,
82208       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
82209       pDb->zName, pTab->zName
82210     );
82211   }
82212 #endif
82213
82214   /* Drop all SQLITE_MASTER table and index entries that refer to the
82215   ** table. The program name loops through the master table and deletes
82216   ** every row that refers to a table of the same name as the one being
82217   ** dropped. Triggers are handled seperately because a trigger can be
82218   ** created in the temp database that refers to a table in another
82219   ** database.
82220   */
82221   sqlite3NestedParse(pParse, 
82222       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
82223       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
82224   if( !isView && !IsVirtual(pTab) ){
82225     destroyTable(pParse, pTab);
82226   }
82227
82228   /* Remove the table entry from SQLite's internal schema and modify
82229   ** the schema cookie.
82230   */
82231   if( IsVirtual(pTab) ){
82232     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
82233   }
82234   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
82235   sqlite3ChangeCookie(pParse, iDb);
82236   sqliteViewResetAll(db, iDb);
82237 }
82238
82239 /*
82240 ** This routine is called to do the work of a DROP TABLE statement.
82241 ** pName is the name of the table to be dropped.
82242 */
82243 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
82244   Table *pTab;
82245   Vdbe *v;
82246   sqlite3 *db = pParse->db;
82247   int iDb;
82248
82249   if( db->mallocFailed ){
82250     goto exit_drop_table;
82251   }
82252   assert( pParse->nErr==0 );
82253   assert( pName->nSrc==1 );
82254   if( noErr ) db->suppressErr++;
82255   pTab = sqlite3LocateTable(pParse, isView, 
82256                             pName->a[0].zName, pName->a[0].zDatabase);
82257   if( noErr ) db->suppressErr--;
82258
82259   if( pTab==0 ){
82260     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82261     goto exit_drop_table;
82262   }
82263   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82264   assert( iDb>=0 && iDb<db->nDb );
82265
82266   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
82267   ** it is initialized.
82268   */
82269   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
82270     goto exit_drop_table;
82271   }
82272 #ifndef SQLITE_OMIT_AUTHORIZATION
82273   {
82274     int code;
82275     const char *zTab = SCHEMA_TABLE(iDb);
82276     const char *zDb = db->aDb[iDb].zName;
82277     const char *zArg2 = 0;
82278     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
82279       goto exit_drop_table;
82280     }
82281     if( isView ){
82282       if( !OMIT_TEMPDB && iDb==1 ){
82283         code = SQLITE_DROP_TEMP_VIEW;
82284       }else{
82285         code = SQLITE_DROP_VIEW;
82286       }
82287 #ifndef SQLITE_OMIT_VIRTUALTABLE
82288     }else if( IsVirtual(pTab) ){
82289       code = SQLITE_DROP_VTABLE;
82290       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
82291 #endif
82292     }else{
82293       if( !OMIT_TEMPDB && iDb==1 ){
82294         code = SQLITE_DROP_TEMP_TABLE;
82295       }else{
82296         code = SQLITE_DROP_TABLE;
82297       }
82298     }
82299     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
82300       goto exit_drop_table;
82301     }
82302     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
82303       goto exit_drop_table;
82304     }
82305   }
82306 #endif
82307   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
82308     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
82309     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
82310     goto exit_drop_table;
82311   }
82312
82313 #ifndef SQLITE_OMIT_VIEW
82314   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
82315   ** on a table.
82316   */
82317   if( isView && pTab->pSelect==0 ){
82318     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
82319     goto exit_drop_table;
82320   }
82321   if( !isView && pTab->pSelect ){
82322     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
82323     goto exit_drop_table;
82324   }
82325 #endif
82326
82327   /* Generate code to remove the table from the master table
82328   ** on disk.
82329   */
82330   v = sqlite3GetVdbe(pParse);
82331   if( v ){
82332     sqlite3BeginWriteOperation(pParse, 1, iDb);
82333     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
82334     sqlite3FkDropTable(pParse, pName, pTab);
82335     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
82336   }
82337
82338 exit_drop_table:
82339   sqlite3SrcListDelete(db, pName);
82340 }
82341
82342 /*
82343 ** This routine is called to create a new foreign key on the table
82344 ** currently under construction.  pFromCol determines which columns
82345 ** in the current table point to the foreign key.  If pFromCol==0 then
82346 ** connect the key to the last column inserted.  pTo is the name of
82347 ** the table referred to.  pToCol is a list of tables in the other
82348 ** pTo table that the foreign key points to.  flags contains all
82349 ** information about the conflict resolution algorithms specified
82350 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
82351 **
82352 ** An FKey structure is created and added to the table currently
82353 ** under construction in the pParse->pNewTable field.
82354 **
82355 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
82356 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
82357 */
82358 SQLITE_PRIVATE void sqlite3CreateForeignKey(
82359   Parse *pParse,       /* Parsing context */
82360   ExprList *pFromCol,  /* Columns in this table that point to other table */
82361   Token *pTo,          /* Name of the other table */
82362   ExprList *pToCol,    /* Columns in the other table */
82363   int flags            /* Conflict resolution algorithms. */
82364 ){
82365   sqlite3 *db = pParse->db;
82366 #ifndef SQLITE_OMIT_FOREIGN_KEY
82367   FKey *pFKey = 0;
82368   FKey *pNextTo;
82369   Table *p = pParse->pNewTable;
82370   int nByte;
82371   int i;
82372   int nCol;
82373   char *z;
82374
82375   assert( pTo!=0 );
82376   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
82377   if( pFromCol==0 ){
82378     int iCol = p->nCol-1;
82379     if( NEVER(iCol<0) ) goto fk_end;
82380     if( pToCol && pToCol->nExpr!=1 ){
82381       sqlite3ErrorMsg(pParse, "foreign key on %s"
82382          " should reference only one column of table %T",
82383          p->aCol[iCol].zName, pTo);
82384       goto fk_end;
82385     }
82386     nCol = 1;
82387   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
82388     sqlite3ErrorMsg(pParse,
82389         "number of columns in foreign key does not match the number of "
82390         "columns in the referenced table");
82391     goto fk_end;
82392   }else{
82393     nCol = pFromCol->nExpr;
82394   }
82395   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
82396   if( pToCol ){
82397     for(i=0; i<pToCol->nExpr; i++){
82398       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
82399     }
82400   }
82401   pFKey = sqlite3DbMallocZero(db, nByte );
82402   if( pFKey==0 ){
82403     goto fk_end;
82404   }
82405   pFKey->pFrom = p;
82406   pFKey->pNextFrom = p->pFKey;
82407   z = (char*)&pFKey->aCol[nCol];
82408   pFKey->zTo = z;
82409   memcpy(z, pTo->z, pTo->n);
82410   z[pTo->n] = 0;
82411   sqlite3Dequote(z);
82412   z += pTo->n+1;
82413   pFKey->nCol = nCol;
82414   if( pFromCol==0 ){
82415     pFKey->aCol[0].iFrom = p->nCol-1;
82416   }else{
82417     for(i=0; i<nCol; i++){
82418       int j;
82419       for(j=0; j<p->nCol; j++){
82420         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
82421           pFKey->aCol[i].iFrom = j;
82422           break;
82423         }
82424       }
82425       if( j>=p->nCol ){
82426         sqlite3ErrorMsg(pParse, 
82427           "unknown column \"%s\" in foreign key definition", 
82428           pFromCol->a[i].zName);
82429         goto fk_end;
82430       }
82431     }
82432   }
82433   if( pToCol ){
82434     for(i=0; i<nCol; i++){
82435       int n = sqlite3Strlen30(pToCol->a[i].zName);
82436       pFKey->aCol[i].zCol = z;
82437       memcpy(z, pToCol->a[i].zName, n);
82438       z[n] = 0;
82439       z += n+1;
82440     }
82441   }
82442   pFKey->isDeferred = 0;
82443   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
82444   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
82445
82446   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
82447   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
82448       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
82449   );
82450   if( pNextTo==pFKey ){
82451     db->mallocFailed = 1;
82452     goto fk_end;
82453   }
82454   if( pNextTo ){
82455     assert( pNextTo->pPrevTo==0 );
82456     pFKey->pNextTo = pNextTo;
82457     pNextTo->pPrevTo = pFKey;
82458   }
82459
82460   /* Link the foreign key to the table as the last step.
82461   */
82462   p->pFKey = pFKey;
82463   pFKey = 0;
82464
82465 fk_end:
82466   sqlite3DbFree(db, pFKey);
82467 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
82468   sqlite3ExprListDelete(db, pFromCol);
82469   sqlite3ExprListDelete(db, pToCol);
82470 }
82471
82472 /*
82473 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
82474 ** clause is seen as part of a foreign key definition.  The isDeferred
82475 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
82476 ** The behavior of the most recently created foreign key is adjusted
82477 ** accordingly.
82478 */
82479 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
82480 #ifndef SQLITE_OMIT_FOREIGN_KEY
82481   Table *pTab;
82482   FKey *pFKey;
82483   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
82484   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
82485   pFKey->isDeferred = (u8)isDeferred;
82486 #endif
82487 }
82488
82489 /*
82490 ** Generate code that will erase and refill index *pIdx.  This is
82491 ** used to initialize a newly created index or to recompute the
82492 ** content of an index in response to a REINDEX command.
82493 **
82494 ** if memRootPage is not negative, it means that the index is newly
82495 ** created.  The register specified by memRootPage contains the
82496 ** root page number of the index.  If memRootPage is negative, then
82497 ** the index already exists and must be cleared before being refilled and
82498 ** the root page number of the index is taken from pIndex->tnum.
82499 */
82500 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
82501   Table *pTab = pIndex->pTable;  /* The table that is indexed */
82502   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
82503   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
82504   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
82505   int addr1;                     /* Address of top of loop */
82506   int addr2;                     /* Address to jump to for next iteration */
82507   int tnum;                      /* Root page of index */
82508   Vdbe *v;                       /* Generate code into this virtual machine */
82509   KeyInfo *pKey;                 /* KeyInfo for index */
82510 #ifdef SQLITE_OMIT_MERGE_SORT
82511   int regIdxKey;                 /* Registers containing the index key */
82512 #endif
82513   int regRecord;                 /* Register holding assemblied index record */
82514   sqlite3 *db = pParse->db;      /* The database connection */
82515   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
82516
82517 #ifndef SQLITE_OMIT_AUTHORIZATION
82518   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
82519       db->aDb[iDb].zName ) ){
82520     return;
82521   }
82522 #endif
82523
82524   /* Require a write-lock on the table to perform this operation */
82525   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
82526
82527   v = sqlite3GetVdbe(pParse);
82528   if( v==0 ) return;
82529   if( memRootPage>=0 ){
82530     tnum = memRootPage;
82531   }else{
82532     tnum = pIndex->tnum;
82533     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
82534   }
82535   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
82536   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
82537                     (char *)pKey, P4_KEYINFO_HANDOFF);
82538   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
82539
82540 #ifndef SQLITE_OMIT_MERGE_SORT
82541   /* Open the sorter cursor if we are to use one. */
82542   iSorter = pParse->nTab++;
82543   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
82544 #else
82545   iSorter = iTab;
82546 #endif
82547
82548   /* Open the table. Loop through all rows of the table, inserting index
82549   ** records into the sorter. */
82550   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
82551   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
82552   regRecord = sqlite3GetTempReg(pParse);
82553
82554 #ifndef SQLITE_OMIT_MERGE_SORT
82555   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
82556   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
82557   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
82558   sqlite3VdbeJumpHere(v, addr1);
82559   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
82560   if( pIndex->onError!=OE_None ){
82561     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
82562     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
82563     addr2 = sqlite3VdbeCurrentAddr(v);
82564     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
82565     sqlite3HaltConstraint(
82566         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
82567     );
82568   }else{
82569     addr2 = sqlite3VdbeCurrentAddr(v);
82570   }
82571   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
82572   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
82573   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
82574 #else
82575   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
82576   addr2 = addr1 + 1;
82577   if( pIndex->onError!=OE_None ){
82578     const int regRowid = regIdxKey + pIndex->nColumn;
82579     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
82580     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
82581
82582     /* The registers accessed by the OP_IsUnique opcode were allocated
82583     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
82584     ** call above. Just before that function was freed they were released
82585     ** (made available to the compiler for reuse) using 
82586     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
82587     ** opcode use the values stored within seems dangerous. However, since
82588     ** we can be sure that no other temp registers have been allocated
82589     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
82590     */
82591     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
82592     sqlite3HaltConstraint(
82593         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
82594   }
82595   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
82596   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
82597 #endif
82598   sqlite3ReleaseTempReg(pParse, regRecord);
82599   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
82600   sqlite3VdbeJumpHere(v, addr1);
82601
82602   sqlite3VdbeAddOp1(v, OP_Close, iTab);
82603   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
82604   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
82605 }
82606
82607 /*
82608 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
82609 ** and pTblList is the name of the table that is to be indexed.  Both will 
82610 ** be NULL for a primary key or an index that is created to satisfy a
82611 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
82612 ** as the table to be indexed.  pParse->pNewTable is a table that is
82613 ** currently being constructed by a CREATE TABLE statement.
82614 **
82615 ** pList is a list of columns to be indexed.  pList will be NULL if this
82616 ** is a primary key or unique-constraint on the most recent column added
82617 ** to the table currently under construction.  
82618 **
82619 ** If the index is created successfully, return a pointer to the new Index
82620 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
82621 ** as the tables primary key (Index.autoIndex==2).
82622 */
82623 SQLITE_PRIVATE Index *sqlite3CreateIndex(
82624   Parse *pParse,     /* All information about this parse */
82625   Token *pName1,     /* First part of index name. May be NULL */
82626   Token *pName2,     /* Second part of index name. May be NULL */
82627   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
82628   ExprList *pList,   /* A list of columns to be indexed */
82629   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
82630   Token *pStart,     /* The CREATE token that begins this statement */
82631   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
82632   int sortOrder,     /* Sort order of primary key when pList==NULL */
82633   int ifNotExist     /* Omit error if index already exists */
82634 ){
82635   Index *pRet = 0;     /* Pointer to return */
82636   Table *pTab = 0;     /* Table to be indexed */
82637   Index *pIndex = 0;   /* The index to be created */
82638   char *zName = 0;     /* Name of the index */
82639   int nName;           /* Number of characters in zName */
82640   int i, j;
82641   Token nullId;        /* Fake token for an empty ID list */
82642   DbFixer sFix;        /* For assigning database names to pTable */
82643   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
82644   sqlite3 *db = pParse->db;
82645   Db *pDb;             /* The specific table containing the indexed database */
82646   int iDb;             /* Index of the database that is being written */
82647   Token *pName = 0;    /* Unqualified name of the index to create */
82648   struct ExprList_item *pListItem; /* For looping over pList */
82649   int nCol;
82650   int nExtra = 0;
82651   char *zExtra;
82652
82653   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
82654   assert( pParse->nErr==0 );      /* Never called with prior errors */
82655   if( db->mallocFailed || IN_DECLARE_VTAB ){
82656     goto exit_create_index;
82657   }
82658   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82659     goto exit_create_index;
82660   }
82661
82662   /*
82663   ** Find the table that is to be indexed.  Return early if not found.
82664   */
82665   if( pTblName!=0 ){
82666
82667     /* Use the two-part index name to determine the database 
82668     ** to search for the table. 'Fix' the table name to this db
82669     ** before looking up the table.
82670     */
82671     assert( pName1 && pName2 );
82672     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82673     if( iDb<0 ) goto exit_create_index;
82674     assert( pName && pName->z );
82675
82676 #ifndef SQLITE_OMIT_TEMPDB
82677     /* If the index name was unqualified, check if the table
82678     ** is a temp table. If so, set the database to 1. Do not do this
82679     ** if initialising a database schema.
82680     */
82681     if( !db->init.busy ){
82682       pTab = sqlite3SrcListLookup(pParse, pTblName);
82683       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
82684         iDb = 1;
82685       }
82686     }
82687 #endif
82688
82689     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
82690         sqlite3FixSrcList(&sFix, pTblName)
82691     ){
82692       /* Because the parser constructs pTblName from a single identifier,
82693       ** sqlite3FixSrcList can never fail. */
82694       assert(0);
82695     }
82696     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
82697         pTblName->a[0].zDatabase);
82698     if( !pTab || db->mallocFailed ) goto exit_create_index;
82699     assert( db->aDb[iDb].pSchema==pTab->pSchema );
82700   }else{
82701     assert( pName==0 );
82702     assert( pStart==0 );
82703     pTab = pParse->pNewTable;
82704     if( !pTab ) goto exit_create_index;
82705     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82706   }
82707   pDb = &db->aDb[iDb];
82708
82709   assert( pTab!=0 );
82710   assert( pParse->nErr==0 );
82711   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
82712        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
82713     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
82714     goto exit_create_index;
82715   }
82716 #ifndef SQLITE_OMIT_VIEW
82717   if( pTab->pSelect ){
82718     sqlite3ErrorMsg(pParse, "views may not be indexed");
82719     goto exit_create_index;
82720   }
82721 #endif
82722 #ifndef SQLITE_OMIT_VIRTUALTABLE
82723   if( IsVirtual(pTab) ){
82724     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
82725     goto exit_create_index;
82726   }
82727 #endif
82728
82729   /*
82730   ** Find the name of the index.  Make sure there is not already another
82731   ** index or table with the same name.  
82732   **
82733   ** Exception:  If we are reading the names of permanent indices from the
82734   ** sqlite_master table (because some other process changed the schema) and
82735   ** one of the index names collides with the name of a temporary table or
82736   ** index, then we will continue to process this index.
82737   **
82738   ** If pName==0 it means that we are
82739   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
82740   ** own name.
82741   */
82742   if( pName ){
82743     zName = sqlite3NameFromToken(db, pName);
82744     if( zName==0 ) goto exit_create_index;
82745     assert( pName->z!=0 );
82746     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
82747       goto exit_create_index;
82748     }
82749     if( !db->init.busy ){
82750       if( sqlite3FindTable(db, zName, 0)!=0 ){
82751         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
82752         goto exit_create_index;
82753       }
82754     }
82755     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
82756       if( !ifNotExist ){
82757         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
82758       }else{
82759         assert( !db->init.busy );
82760         sqlite3CodeVerifySchema(pParse, iDb);
82761       }
82762       goto exit_create_index;
82763     }
82764   }else{
82765     int n;
82766     Index *pLoop;
82767     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
82768     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
82769     if( zName==0 ){
82770       goto exit_create_index;
82771     }
82772   }
82773
82774   /* Check for authorization to create an index.
82775   */
82776 #ifndef SQLITE_OMIT_AUTHORIZATION
82777   {
82778     const char *zDb = pDb->zName;
82779     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
82780       goto exit_create_index;
82781     }
82782     i = SQLITE_CREATE_INDEX;
82783     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
82784     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
82785       goto exit_create_index;
82786     }
82787   }
82788 #endif
82789
82790   /* If pList==0, it means this routine was called to make a primary
82791   ** key out of the last column added to the table under construction.
82792   ** So create a fake list to simulate this.
82793   */
82794   if( pList==0 ){
82795     nullId.z = pTab->aCol[pTab->nCol-1].zName;
82796     nullId.n = sqlite3Strlen30((char*)nullId.z);
82797     pList = sqlite3ExprListAppend(pParse, 0, 0);
82798     if( pList==0 ) goto exit_create_index;
82799     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
82800     pList->a[0].sortOrder = (u8)sortOrder;
82801   }
82802
82803   /* Figure out how many bytes of space are required to store explicitly
82804   ** specified collation sequence names.
82805   */
82806   for(i=0; i<pList->nExpr; i++){
82807     Expr *pExpr = pList->a[i].pExpr;
82808     if( pExpr ){
82809       CollSeq *pColl = pExpr->pColl;
82810       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
82811       ** failure we have quit before reaching this point. */
82812       if( ALWAYS(pColl) ){
82813         nExtra += (1 + sqlite3Strlen30(pColl->zName));
82814       }
82815     }
82816   }
82817
82818   /* 
82819   ** Allocate the index structure. 
82820   */
82821   nName = sqlite3Strlen30(zName);
82822   nCol = pList->nExpr;
82823   pIndex = sqlite3DbMallocZero(db, 
82824       ROUND8(sizeof(Index)) +              /* Index structure  */
82825       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
82826       sizeof(char *)*nCol +                /* Index.azColl     */
82827       sizeof(int)*nCol +                   /* Index.aiColumn   */
82828       sizeof(u8)*nCol +                    /* Index.aSortOrder */
82829       nName + 1 +                          /* Index.zName      */
82830       nExtra                               /* Collation sequence names */
82831   );
82832   if( db->mallocFailed ){
82833     goto exit_create_index;
82834   }
82835   zExtra = (char*)pIndex;
82836   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
82837   pIndex->azColl = (char**)
82838      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
82839   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
82840   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
82841   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
82842   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
82843   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
82844   zExtra = (char *)(&pIndex->zName[nName+1]);
82845   memcpy(pIndex->zName, zName, nName+1);
82846   pIndex->pTable = pTab;
82847   pIndex->nColumn = pList->nExpr;
82848   pIndex->onError = (u8)onError;
82849   pIndex->autoIndex = (u8)(pName==0);
82850   pIndex->pSchema = db->aDb[iDb].pSchema;
82851   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82852
82853   /* Check to see if we should honor DESC requests on index columns
82854   */
82855   if( pDb->pSchema->file_format>=4 ){
82856     sortOrderMask = -1;   /* Honor DESC */
82857   }else{
82858     sortOrderMask = 0;    /* Ignore DESC */
82859   }
82860
82861   /* Scan the names of the columns of the table to be indexed and
82862   ** load the column indices into the Index structure.  Report an error
82863   ** if any column is not found.
82864   **
82865   ** TODO:  Add a test to make sure that the same column is not named
82866   ** more than once within the same index.  Only the first instance of
82867   ** the column will ever be used by the optimizer.  Note that using the
82868   ** same column more than once cannot be an error because that would 
82869   ** break backwards compatibility - it needs to be a warning.
82870   */
82871   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
82872     const char *zColName = pListItem->zName;
82873     Column *pTabCol;
82874     int requestedSortOrder;
82875     char *zColl;                   /* Collation sequence name */
82876
82877     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
82878       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
82879     }
82880     if( j>=pTab->nCol ){
82881       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
82882         pTab->zName, zColName);
82883       pParse->checkSchema = 1;
82884       goto exit_create_index;
82885     }
82886     pIndex->aiColumn[i] = j;
82887     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
82888     ** the way the "idxlist" non-terminal is constructed by the parser,
82889     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
82890     ** must exist or else there must have been an OOM error.  But if there
82891     ** was an OOM error, we would never reach this point. */
82892     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
82893       int nColl;
82894       zColl = pListItem->pExpr->pColl->zName;
82895       nColl = sqlite3Strlen30(zColl) + 1;
82896       assert( nExtra>=nColl );
82897       memcpy(zExtra, zColl, nColl);
82898       zColl = zExtra;
82899       zExtra += nColl;
82900       nExtra -= nColl;
82901     }else{
82902       zColl = pTab->aCol[j].zColl;
82903       if( !zColl ){
82904         zColl = "BINARY";
82905       }
82906     }
82907     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
82908       goto exit_create_index;
82909     }
82910     pIndex->azColl[i] = zColl;
82911     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
82912     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
82913   }
82914   sqlite3DefaultRowEst(pIndex);
82915
82916   if( pTab==pParse->pNewTable ){
82917     /* This routine has been called to create an automatic index as a
82918     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
82919     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
82920     ** i.e. one of:
82921     **
82922     ** CREATE TABLE t(x PRIMARY KEY, y);
82923     ** CREATE TABLE t(x, y, UNIQUE(x, y));
82924     **
82925     ** Either way, check to see if the table already has such an index. If
82926     ** so, don't bother creating this one. This only applies to
82927     ** automatically created indices. Users can do as they wish with
82928     ** explicit indices.
82929     **
82930     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
82931     ** (and thus suppressing the second one) even if they have different
82932     ** sort orders.
82933     **
82934     ** If there are different collating sequences or if the columns of
82935     ** the constraint occur in different orders, then the constraints are
82936     ** considered distinct and both result in separate indices.
82937     */
82938     Index *pIdx;
82939     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82940       int k;
82941       assert( pIdx->onError!=OE_None );
82942       assert( pIdx->autoIndex );
82943       assert( pIndex->onError!=OE_None );
82944
82945       if( pIdx->nColumn!=pIndex->nColumn ) continue;
82946       for(k=0; k<pIdx->nColumn; k++){
82947         const char *z1;
82948         const char *z2;
82949         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
82950         z1 = pIdx->azColl[k];
82951         z2 = pIndex->azColl[k];
82952         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
82953       }
82954       if( k==pIdx->nColumn ){
82955         if( pIdx->onError!=pIndex->onError ){
82956           /* This constraint creates the same index as a previous
82957           ** constraint specified somewhere in the CREATE TABLE statement.
82958           ** However the ON CONFLICT clauses are different. If both this 
82959           ** constraint and the previous equivalent constraint have explicit
82960           ** ON CONFLICT clauses this is an error. Otherwise, use the
82961           ** explicitly specified behaviour for the index.
82962           */
82963           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
82964             sqlite3ErrorMsg(pParse, 
82965                 "conflicting ON CONFLICT clauses specified", 0);
82966           }
82967           if( pIdx->onError==OE_Default ){
82968             pIdx->onError = pIndex->onError;
82969           }
82970         }
82971         goto exit_create_index;
82972       }
82973     }
82974   }
82975
82976   /* Link the new Index structure to its table and to the other
82977   ** in-memory database structures. 
82978   */
82979   if( db->init.busy ){
82980     Index *p;
82981     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82982     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
82983                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
82984                           pIndex);
82985     if( p ){
82986       assert( p==pIndex );  /* Malloc must have failed */
82987       db->mallocFailed = 1;
82988       goto exit_create_index;
82989     }
82990     db->flags |= SQLITE_InternChanges;
82991     if( pTblName!=0 ){
82992       pIndex->tnum = db->init.newTnum;
82993     }
82994   }
82995
82996   /* If the db->init.busy is 0 then create the index on disk.  This
82997   ** involves writing the index into the master table and filling in the
82998   ** index with the current table contents.
82999   **
83000   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
83001   ** command.  db->init.busy is 1 when a database is opened and 
83002   ** CREATE INDEX statements are read out of the master table.  In
83003   ** the latter case the index already exists on disk, which is why
83004   ** we don't want to recreate it.
83005   **
83006   ** If pTblName==0 it means this index is generated as a primary key
83007   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83008   ** has just been created, it contains no data and the index initialization
83009   ** step can be skipped.
83010   */
83011   else{ /* if( db->init.busy==0 ) */
83012     Vdbe *v;
83013     char *zStmt;
83014     int iMem = ++pParse->nMem;
83015
83016     v = sqlite3GetVdbe(pParse);
83017     if( v==0 ) goto exit_create_index;
83018
83019
83020     /* Create the rootpage for the index
83021     */
83022     sqlite3BeginWriteOperation(pParse, 1, iDb);
83023     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83024
83025     /* Gather the complete text of the CREATE INDEX statement into
83026     ** the zStmt variable
83027     */
83028     if( pStart ){
83029       assert( pEnd!=0 );
83030       /* A named index with an explicit CREATE INDEX statement */
83031       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
83032         onError==OE_None ? "" : " UNIQUE",
83033         (int)(pEnd->z - pName->z) + 1,
83034         pName->z);
83035     }else{
83036       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83037       /* zStmt = sqlite3MPrintf(""); */
83038       zStmt = 0;
83039     }
83040
83041     /* Add an entry in sqlite_master for this index
83042     */
83043     sqlite3NestedParse(pParse, 
83044         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83045         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83046         pIndex->zName,
83047         pTab->zName,
83048         iMem,
83049         zStmt
83050     );
83051     sqlite3DbFree(db, zStmt);
83052
83053     /* Fill the index with data and reparse the schema. Code an OP_Expire
83054     ** to invalidate all pre-compiled statements.
83055     */
83056     if( pTblName ){
83057       sqlite3RefillIndex(pParse, pIndex, iMem);
83058       sqlite3ChangeCookie(pParse, iDb);
83059       sqlite3VdbeAddParseSchemaOp(v, iDb,
83060          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83061       sqlite3VdbeAddOp1(v, OP_Expire, 0);
83062     }
83063   }
83064
83065   /* When adding an index to the list of indices for a table, make
83066   ** sure all indices labeled OE_Replace come after all those labeled
83067   ** OE_Ignore.  This is necessary for the correct constraint check
83068   ** processing (in sqlite3GenerateConstraintChecks()) as part of
83069   ** UPDATE and INSERT statements.  
83070   */
83071   if( db->init.busy || pTblName==0 ){
83072     if( onError!=OE_Replace || pTab->pIndex==0
83073          || pTab->pIndex->onError==OE_Replace){
83074       pIndex->pNext = pTab->pIndex;
83075       pTab->pIndex = pIndex;
83076     }else{
83077       Index *pOther = pTab->pIndex;
83078       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83079         pOther = pOther->pNext;
83080       }
83081       pIndex->pNext = pOther->pNext;
83082       pOther->pNext = pIndex;
83083     }
83084     pRet = pIndex;
83085     pIndex = 0;
83086   }
83087
83088   /* Clean up before exiting */
83089 exit_create_index:
83090   if( pIndex ){
83091     sqlite3DbFree(db, pIndex->zColAff);
83092     sqlite3DbFree(db, pIndex);
83093   }
83094   sqlite3ExprListDelete(db, pList);
83095   sqlite3SrcListDelete(db, pTblName);
83096   sqlite3DbFree(db, zName);
83097   return pRet;
83098 }
83099
83100 /*
83101 ** Fill the Index.aiRowEst[] array with default information - information
83102 ** to be used when we have not run the ANALYZE command.
83103 **
83104 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83105 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83106 ** number of rows in the table that match any particular value of the
83107 ** first column of the index.  aiRowEst[2] is an estimate of the number
83108 ** of rows that match any particular combiniation of the first 2 columns
83109 ** of the index.  And so forth.  It must always be the case that
83110 *
83111 **           aiRowEst[N]<=aiRowEst[N-1]
83112 **           aiRowEst[N]>=1
83113 **
83114 ** Apart from that, we have little to go on besides intuition as to
83115 ** how aiRowEst[] should be initialized.  The numbers generated here
83116 ** are based on typical values found in actual indices.
83117 */
83118 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
83119   tRowcnt *a = pIdx->aiRowEst;
83120   int i;
83121   tRowcnt n;
83122   assert( a!=0 );
83123   a[0] = pIdx->pTable->nRowEst;
83124   if( a[0]<10 ) a[0] = 10;
83125   n = 10;
83126   for(i=1; i<=pIdx->nColumn; i++){
83127     a[i] = n;
83128     if( n>5 ) n--;
83129   }
83130   if( pIdx->onError!=OE_None ){
83131     a[pIdx->nColumn] = 1;
83132   }
83133 }
83134
83135 /*
83136 ** This routine will drop an existing named index.  This routine
83137 ** implements the DROP INDEX statement.
83138 */
83139 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83140   Index *pIndex;
83141   Vdbe *v;
83142   sqlite3 *db = pParse->db;
83143   int iDb;
83144
83145   assert( pParse->nErr==0 );   /* Never called with prior errors */
83146   if( db->mallocFailed ){
83147     goto exit_drop_index;
83148   }
83149   assert( pName->nSrc==1 );
83150   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83151     goto exit_drop_index;
83152   }
83153   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83154   if( pIndex==0 ){
83155     if( !ifExists ){
83156       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
83157     }else{
83158       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83159     }
83160     pParse->checkSchema = 1;
83161     goto exit_drop_index;
83162   }
83163   if( pIndex->autoIndex ){
83164     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
83165       "or PRIMARY KEY constraint cannot be dropped", 0);
83166     goto exit_drop_index;
83167   }
83168   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83169 #ifndef SQLITE_OMIT_AUTHORIZATION
83170   {
83171     int code = SQLITE_DROP_INDEX;
83172     Table *pTab = pIndex->pTable;
83173     const char *zDb = db->aDb[iDb].zName;
83174     const char *zTab = SCHEMA_TABLE(iDb);
83175     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
83176       goto exit_drop_index;
83177     }
83178     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
83179     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83180       goto exit_drop_index;
83181     }
83182   }
83183 #endif
83184
83185   /* Generate code to remove the index and from the master table */
83186   v = sqlite3GetVdbe(pParse);
83187   if( v ){
83188     sqlite3BeginWriteOperation(pParse, 1, iDb);
83189     sqlite3NestedParse(pParse,
83190        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83191        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83192     );
83193     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83194     sqlite3ChangeCookie(pParse, iDb);
83195     destroyRootPage(pParse, pIndex->tnum, iDb);
83196     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83197   }
83198
83199 exit_drop_index:
83200   sqlite3SrcListDelete(db, pName);
83201 }
83202
83203 /*
83204 ** pArray is a pointer to an array of objects. Each object in the
83205 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
83206 ** to extend the array so that there is space for a new object at the end.
83207 **
83208 ** When this function is called, *pnEntry contains the current size of
83209 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
83210 ** in total).
83211 **
83212 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
83213 ** space allocated for the new object is zeroed, *pnEntry updated to
83214 ** reflect the new size of the array and a pointer to the new allocation
83215 ** returned. *pIdx is set to the index of the new array entry in this case.
83216 **
83217 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
83218 ** unchanged and a copy of pArray returned.
83219 */
83220 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
83221   sqlite3 *db,      /* Connection to notify of malloc failures */
83222   void *pArray,     /* Array of objects.  Might be reallocated */
83223   int szEntry,      /* Size of each object in the array */
83224   int *pnEntry,     /* Number of objects currently in use */
83225   int *pIdx         /* Write the index of a new slot here */
83226 ){
83227   char *z;
83228   int n = *pnEntry;
83229   if( (n & (n-1))==0 ){
83230     int sz = (n==0) ? 1 : 2*n;
83231     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
83232     if( pNew==0 ){
83233       *pIdx = -1;
83234       return pArray;
83235     }
83236     pArray = pNew;
83237   }
83238   z = (char*)pArray;
83239   memset(&z[n * szEntry], 0, szEntry);
83240   *pIdx = n;
83241   ++*pnEntry;
83242   return pArray;
83243 }
83244
83245 /*
83246 ** Append a new element to the given IdList.  Create a new IdList if
83247 ** need be.
83248 **
83249 ** A new IdList is returned, or NULL if malloc() fails.
83250 */
83251 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
83252   int i;
83253   if( pList==0 ){
83254     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
83255     if( pList==0 ) return 0;
83256   }
83257   pList->a = sqlite3ArrayAllocate(
83258       db,
83259       pList->a,
83260       sizeof(pList->a[0]),
83261       &pList->nId,
83262       &i
83263   );
83264   if( i<0 ){
83265     sqlite3IdListDelete(db, pList);
83266     return 0;
83267   }
83268   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
83269   return pList;
83270 }
83271
83272 /*
83273 ** Delete an IdList.
83274 */
83275 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
83276   int i;
83277   if( pList==0 ) return;
83278   for(i=0; i<pList->nId; i++){
83279     sqlite3DbFree(db, pList->a[i].zName);
83280   }
83281   sqlite3DbFree(db, pList->a);
83282   sqlite3DbFree(db, pList);
83283 }
83284
83285 /*
83286 ** Return the index in pList of the identifier named zId.  Return -1
83287 ** if not found.
83288 */
83289 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
83290   int i;
83291   if( pList==0 ) return -1;
83292   for(i=0; i<pList->nId; i++){
83293     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
83294   }
83295   return -1;
83296 }
83297
83298 /*
83299 ** Expand the space allocated for the given SrcList object by
83300 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
83301 ** New slots are zeroed.
83302 **
83303 ** For example, suppose a SrcList initially contains two entries: A,B.
83304 ** To append 3 new entries onto the end, do this:
83305 **
83306 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
83307 **
83308 ** After the call above it would contain:  A, B, nil, nil, nil.
83309 ** If the iStart argument had been 1 instead of 2, then the result
83310 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
83311 ** the iStart value would be 0.  The result then would
83312 ** be: nil, nil, nil, A, B.
83313 **
83314 ** If a memory allocation fails the SrcList is unchanged.  The
83315 ** db->mallocFailed flag will be set to true.
83316 */
83317 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
83318   sqlite3 *db,       /* Database connection to notify of OOM errors */
83319   SrcList *pSrc,     /* The SrcList to be enlarged */
83320   int nExtra,        /* Number of new slots to add to pSrc->a[] */
83321   int iStart         /* Index in pSrc->a[] of first new slot */
83322 ){
83323   int i;
83324
83325   /* Sanity checking on calling parameters */
83326   assert( iStart>=0 );
83327   assert( nExtra>=1 );
83328   assert( pSrc!=0 );
83329   assert( iStart<=pSrc->nSrc );
83330
83331   /* Allocate additional space if needed */
83332   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
83333     SrcList *pNew;
83334     int nAlloc = pSrc->nSrc+nExtra;
83335     int nGot;
83336     pNew = sqlite3DbRealloc(db, pSrc,
83337                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
83338     if( pNew==0 ){
83339       assert( db->mallocFailed );
83340       return pSrc;
83341     }
83342     pSrc = pNew;
83343     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
83344     pSrc->nAlloc = (u16)nGot;
83345   }
83346
83347   /* Move existing slots that come after the newly inserted slots
83348   ** out of the way */
83349   for(i=pSrc->nSrc-1; i>=iStart; i--){
83350     pSrc->a[i+nExtra] = pSrc->a[i];
83351   }
83352   pSrc->nSrc += (i16)nExtra;
83353
83354   /* Zero the newly allocated slots */
83355   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
83356   for(i=iStart; i<iStart+nExtra; i++){
83357     pSrc->a[i].iCursor = -1;
83358   }
83359
83360   /* Return a pointer to the enlarged SrcList */
83361   return pSrc;
83362 }
83363
83364
83365 /*
83366 ** Append a new table name to the given SrcList.  Create a new SrcList if
83367 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
83368 **
83369 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
83370 ** SrcList might be the same as the SrcList that was input or it might be
83371 ** a new one.  If an OOM error does occurs, then the prior value of pList
83372 ** that is input to this routine is automatically freed.
83373 **
83374 ** If pDatabase is not null, it means that the table has an optional
83375 ** database name prefix.  Like this:  "database.table".  The pDatabase
83376 ** points to the table name and the pTable points to the database name.
83377 ** The SrcList.a[].zName field is filled with the table name which might
83378 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
83379 ** SrcList.a[].zDatabase is filled with the database name from pTable,
83380 ** or with NULL if no database is specified.
83381 **
83382 ** In other words, if call like this:
83383 **
83384 **         sqlite3SrcListAppend(D,A,B,0);
83385 **
83386 ** Then B is a table name and the database name is unspecified.  If called
83387 ** like this:
83388 **
83389 **         sqlite3SrcListAppend(D,A,B,C);
83390 **
83391 ** Then C is the table name and B is the database name.  If C is defined
83392 ** then so is B.  In other words, we never have a case where:
83393 **
83394 **         sqlite3SrcListAppend(D,A,0,C);
83395 **
83396 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
83397 ** before being added to the SrcList.
83398 */
83399 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
83400   sqlite3 *db,        /* Connection to notify of malloc failures */
83401   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
83402   Token *pTable,      /* Table to append */
83403   Token *pDatabase    /* Database of the table */
83404 ){
83405   struct SrcList_item *pItem;
83406   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
83407   if( pList==0 ){
83408     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
83409     if( pList==0 ) return 0;
83410     pList->nAlloc = 1;
83411   }
83412   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
83413   if( db->mallocFailed ){
83414     sqlite3SrcListDelete(db, pList);
83415     return 0;
83416   }
83417   pItem = &pList->a[pList->nSrc-1];
83418   if( pDatabase && pDatabase->z==0 ){
83419     pDatabase = 0;
83420   }
83421   if( pDatabase ){
83422     Token *pTemp = pDatabase;
83423     pDatabase = pTable;
83424     pTable = pTemp;
83425   }
83426   pItem->zName = sqlite3NameFromToken(db, pTable);
83427   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
83428   return pList;
83429 }
83430
83431 /*
83432 ** Assign VdbeCursor index numbers to all tables in a SrcList
83433 */
83434 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
83435   int i;
83436   struct SrcList_item *pItem;
83437   assert(pList || pParse->db->mallocFailed );
83438   if( pList ){
83439     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
83440       if( pItem->iCursor>=0 ) break;
83441       pItem->iCursor = pParse->nTab++;
83442       if( pItem->pSelect ){
83443         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
83444       }
83445     }
83446   }
83447 }
83448
83449 /*
83450 ** Delete an entire SrcList including all its substructure.
83451 */
83452 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
83453   int i;
83454   struct SrcList_item *pItem;
83455   if( pList==0 ) return;
83456   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
83457     sqlite3DbFree(db, pItem->zDatabase);
83458     sqlite3DbFree(db, pItem->zName);
83459     sqlite3DbFree(db, pItem->zAlias);
83460     sqlite3DbFree(db, pItem->zIndex);
83461     sqlite3DeleteTable(db, pItem->pTab);
83462     sqlite3SelectDelete(db, pItem->pSelect);
83463     sqlite3ExprDelete(db, pItem->pOn);
83464     sqlite3IdListDelete(db, pItem->pUsing);
83465   }
83466   sqlite3DbFree(db, pList);
83467 }
83468
83469 /*
83470 ** This routine is called by the parser to add a new term to the
83471 ** end of a growing FROM clause.  The "p" parameter is the part of
83472 ** the FROM clause that has already been constructed.  "p" is NULL
83473 ** if this is the first term of the FROM clause.  pTable and pDatabase
83474 ** are the name of the table and database named in the FROM clause term.
83475 ** pDatabase is NULL if the database name qualifier is missing - the
83476 ** usual case.  If the term has a alias, then pAlias points to the
83477 ** alias token.  If the term is a subquery, then pSubquery is the
83478 ** SELECT statement that the subquery encodes.  The pTable and
83479 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
83480 ** parameters are the content of the ON and USING clauses.
83481 **
83482 ** Return a new SrcList which encodes is the FROM with the new
83483 ** term added.
83484 */
83485 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
83486   Parse *pParse,          /* Parsing context */
83487   SrcList *p,             /* The left part of the FROM clause already seen */
83488   Token *pTable,          /* Name of the table to add to the FROM clause */
83489   Token *pDatabase,       /* Name of the database containing pTable */
83490   Token *pAlias,          /* The right-hand side of the AS subexpression */
83491   Select *pSubquery,      /* A subquery used in place of a table name */
83492   Expr *pOn,              /* The ON clause of a join */
83493   IdList *pUsing          /* The USING clause of a join */
83494 ){
83495   struct SrcList_item *pItem;
83496   sqlite3 *db = pParse->db;
83497   if( !p && (pOn || pUsing) ){
83498     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
83499       (pOn ? "ON" : "USING")
83500     );
83501     goto append_from_error;
83502   }
83503   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
83504   if( p==0 || NEVER(p->nSrc==0) ){
83505     goto append_from_error;
83506   }
83507   pItem = &p->a[p->nSrc-1];
83508   assert( pAlias!=0 );
83509   if( pAlias->n ){
83510     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
83511   }
83512   pItem->pSelect = pSubquery;
83513   pItem->pOn = pOn;
83514   pItem->pUsing = pUsing;
83515   return p;
83516
83517  append_from_error:
83518   assert( p==0 );
83519   sqlite3ExprDelete(db, pOn);
83520   sqlite3IdListDelete(db, pUsing);
83521   sqlite3SelectDelete(db, pSubquery);
83522   return 0;
83523 }
83524
83525 /*
83526 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
83527 ** element of the source-list passed as the second argument.
83528 */
83529 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
83530   assert( pIndexedBy!=0 );
83531   if( p && ALWAYS(p->nSrc>0) ){
83532     struct SrcList_item *pItem = &p->a[p->nSrc-1];
83533     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
83534     if( pIndexedBy->n==1 && !pIndexedBy->z ){
83535       /* A "NOT INDEXED" clause was supplied. See parse.y 
83536       ** construct "indexed_opt" for details. */
83537       pItem->notIndexed = 1;
83538     }else{
83539       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
83540     }
83541   }
83542 }
83543
83544 /*
83545 ** When building up a FROM clause in the parser, the join operator
83546 ** is initially attached to the left operand.  But the code generator
83547 ** expects the join operator to be on the right operand.  This routine
83548 ** Shifts all join operators from left to right for an entire FROM
83549 ** clause.
83550 **
83551 ** Example: Suppose the join is like this:
83552 **
83553 **           A natural cross join B
83554 **
83555 ** The operator is "natural cross join".  The A and B operands are stored
83556 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
83557 ** operator with A.  This routine shifts that operator over to B.
83558 */
83559 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
83560   if( p ){
83561     int i;
83562     assert( p->a || p->nSrc==0 );
83563     for(i=p->nSrc-1; i>0; i--){
83564       p->a[i].jointype = p->a[i-1].jointype;
83565     }
83566     p->a[0].jointype = 0;
83567   }
83568 }
83569
83570 /*
83571 ** Begin a transaction
83572 */
83573 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
83574   sqlite3 *db;
83575   Vdbe *v;
83576   int i;
83577
83578   assert( pParse!=0 );
83579   db = pParse->db;
83580   assert( db!=0 );
83581 /*  if( db->aDb[0].pBt==0 ) return; */
83582   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
83583     return;
83584   }
83585   v = sqlite3GetVdbe(pParse);
83586   if( !v ) return;
83587   if( type!=TK_DEFERRED ){
83588     for(i=0; i<db->nDb; i++){
83589       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
83590       sqlite3VdbeUsesBtree(v, i);
83591     }
83592   }
83593   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
83594 }
83595
83596 /*
83597 ** Commit a transaction
83598 */
83599 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
83600   Vdbe *v;
83601
83602   assert( pParse!=0 );
83603   assert( pParse->db!=0 );
83604   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
83605     return;
83606   }
83607   v = sqlite3GetVdbe(pParse);
83608   if( v ){
83609     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
83610   }
83611 }
83612
83613 /*
83614 ** Rollback a transaction
83615 */
83616 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
83617   Vdbe *v;
83618
83619   assert( pParse!=0 );
83620   assert( pParse->db!=0 );
83621   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
83622     return;
83623   }
83624   v = sqlite3GetVdbe(pParse);
83625   if( v ){
83626     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
83627   }
83628 }
83629
83630 /*
83631 ** This function is called by the parser when it parses a command to create,
83632 ** release or rollback an SQL savepoint. 
83633 */
83634 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
83635   char *zName = sqlite3NameFromToken(pParse->db, pName);
83636   if( zName ){
83637     Vdbe *v = sqlite3GetVdbe(pParse);
83638 #ifndef SQLITE_OMIT_AUTHORIZATION
83639     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
83640     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
83641 #endif
83642     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
83643       sqlite3DbFree(pParse->db, zName);
83644       return;
83645     }
83646     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
83647   }
83648 }
83649
83650 /*
83651 ** Make sure the TEMP database is open and available for use.  Return
83652 ** the number of errors.  Leave any error messages in the pParse structure.
83653 */
83654 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
83655   sqlite3 *db = pParse->db;
83656   if( db->aDb[1].pBt==0 && !pParse->explain ){
83657     int rc;
83658     Btree *pBt;
83659     static const int flags = 
83660           SQLITE_OPEN_READWRITE |
83661           SQLITE_OPEN_CREATE |
83662           SQLITE_OPEN_EXCLUSIVE |
83663           SQLITE_OPEN_DELETEONCLOSE |
83664           SQLITE_OPEN_TEMP_DB;
83665
83666     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
83667     if( rc!=SQLITE_OK ){
83668       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
83669         "file for storing temporary tables");
83670       pParse->rc = rc;
83671       return 1;
83672     }
83673     db->aDb[1].pBt = pBt;
83674     assert( db->aDb[1].pSchema );
83675     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
83676       db->mallocFailed = 1;
83677       return 1;
83678     }
83679   }
83680   return 0;
83681 }
83682
83683 /*
83684 ** Generate VDBE code that will verify the schema cookie and start
83685 ** a read-transaction for all named database files.
83686 **
83687 ** It is important that all schema cookies be verified and all
83688 ** read transactions be started before anything else happens in
83689 ** the VDBE program.  But this routine can be called after much other
83690 ** code has been generated.  So here is what we do:
83691 **
83692 ** The first time this routine is called, we code an OP_Goto that
83693 ** will jump to a subroutine at the end of the program.  Then we
83694 ** record every database that needs its schema verified in the
83695 ** pParse->cookieMask field.  Later, after all other code has been
83696 ** generated, the subroutine that does the cookie verifications and
83697 ** starts the transactions will be coded and the OP_Goto P2 value
83698 ** will be made to point to that subroutine.  The generation of the
83699 ** cookie verification subroutine code happens in sqlite3FinishCoding().
83700 **
83701 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
83702 ** schema on any databases.  This can be used to position the OP_Goto
83703 ** early in the code, before we know if any database tables will be used.
83704 */
83705 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
83706   Parse *pToplevel = sqlite3ParseToplevel(pParse);
83707
83708   if( pToplevel->cookieGoto==0 ){
83709     Vdbe *v = sqlite3GetVdbe(pToplevel);
83710     if( v==0 ) return;  /* This only happens if there was a prior error */
83711     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
83712   }
83713   if( iDb>=0 ){
83714     sqlite3 *db = pToplevel->db;
83715     yDbMask mask;
83716
83717     assert( iDb<db->nDb );
83718     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
83719     assert( iDb<SQLITE_MAX_ATTACHED+2 );
83720     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83721     mask = ((yDbMask)1)<<iDb;
83722     if( (pToplevel->cookieMask & mask)==0 ){
83723       pToplevel->cookieMask |= mask;
83724       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
83725       if( !OMIT_TEMPDB && iDb==1 ){
83726         sqlite3OpenTempDatabase(pToplevel);
83727       }
83728     }
83729   }
83730 }
83731
83732 /*
83733 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
83734 ** attached database. Otherwise, invoke it for the database named zDb only.
83735 */
83736 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
83737   sqlite3 *db = pParse->db;
83738   int i;
83739   for(i=0; i<db->nDb; i++){
83740     Db *pDb = &db->aDb[i];
83741     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
83742       sqlite3CodeVerifySchema(pParse, i);
83743     }
83744   }
83745 }
83746
83747 /*
83748 ** Generate VDBE code that prepares for doing an operation that
83749 ** might change the database.
83750 **
83751 ** This routine starts a new transaction if we are not already within
83752 ** a transaction.  If we are already within a transaction, then a checkpoint
83753 ** is set if the setStatement parameter is true.  A checkpoint should
83754 ** be set for operations that might fail (due to a constraint) part of
83755 ** the way through and which will need to undo some writes without having to
83756 ** rollback the whole transaction.  For operations where all constraints
83757 ** can be checked before any changes are made to the database, it is never
83758 ** necessary to undo a write and the checkpoint should not be set.
83759 */
83760 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
83761   Parse *pToplevel = sqlite3ParseToplevel(pParse);
83762   sqlite3CodeVerifySchema(pParse, iDb);
83763   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
83764   pToplevel->isMultiWrite |= setStatement;
83765 }
83766
83767 /*
83768 ** Indicate that the statement currently under construction might write
83769 ** more than one entry (example: deleting one row then inserting another,
83770 ** inserting multiple rows in a table, or inserting a row and index entries.)
83771 ** If an abort occurs after some of these writes have completed, then it will
83772 ** be necessary to undo the completed writes.
83773 */
83774 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
83775   Parse *pToplevel = sqlite3ParseToplevel(pParse);
83776   pToplevel->isMultiWrite = 1;
83777 }
83778
83779 /* 
83780 ** The code generator calls this routine if is discovers that it is
83781 ** possible to abort a statement prior to completion.  In order to 
83782 ** perform this abort without corrupting the database, we need to make
83783 ** sure that the statement is protected by a statement transaction.
83784 **
83785 ** Technically, we only need to set the mayAbort flag if the
83786 ** isMultiWrite flag was previously set.  There is a time dependency
83787 ** such that the abort must occur after the multiwrite.  This makes
83788 ** some statements involving the REPLACE conflict resolution algorithm
83789 ** go a little faster.  But taking advantage of this time dependency
83790 ** makes it more difficult to prove that the code is correct (in 
83791 ** particular, it prevents us from writing an effective
83792 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
83793 ** to take the safe route and skip the optimization.
83794 */
83795 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
83796   Parse *pToplevel = sqlite3ParseToplevel(pParse);
83797   pToplevel->mayAbort = 1;
83798 }
83799
83800 /*
83801 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
83802 ** error. The onError parameter determines which (if any) of the statement
83803 ** and/or current transaction is rolled back.
83804 */
83805 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
83806   Vdbe *v = sqlite3GetVdbe(pParse);
83807   if( onError==OE_Abort ){
83808     sqlite3MayAbort(pParse);
83809   }
83810   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
83811 }
83812
83813 /*
83814 ** Check to see if pIndex uses the collating sequence pColl.  Return
83815 ** true if it does and false if it does not.
83816 */
83817 #ifndef SQLITE_OMIT_REINDEX
83818 static int collationMatch(const char *zColl, Index *pIndex){
83819   int i;
83820   assert( zColl!=0 );
83821   for(i=0; i<pIndex->nColumn; i++){
83822     const char *z = pIndex->azColl[i];
83823     assert( z!=0 );
83824     if( 0==sqlite3StrICmp(z, zColl) ){
83825       return 1;
83826     }
83827   }
83828   return 0;
83829 }
83830 #endif
83831
83832 /*
83833 ** Recompute all indices of pTab that use the collating sequence pColl.
83834 ** If pColl==0 then recompute all indices of pTab.
83835 */
83836 #ifndef SQLITE_OMIT_REINDEX
83837 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
83838   Index *pIndex;              /* An index associated with pTab */
83839
83840   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
83841     if( zColl==0 || collationMatch(zColl, pIndex) ){
83842       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83843       sqlite3BeginWriteOperation(pParse, 0, iDb);
83844       sqlite3RefillIndex(pParse, pIndex, -1);
83845     }
83846   }
83847 }
83848 #endif
83849
83850 /*
83851 ** Recompute all indices of all tables in all databases where the
83852 ** indices use the collating sequence pColl.  If pColl==0 then recompute
83853 ** all indices everywhere.
83854 */
83855 #ifndef SQLITE_OMIT_REINDEX
83856 static void reindexDatabases(Parse *pParse, char const *zColl){
83857   Db *pDb;                    /* A single database */
83858   int iDb;                    /* The database index number */
83859   sqlite3 *db = pParse->db;   /* The database connection */
83860   HashElem *k;                /* For looping over tables in pDb */
83861   Table *pTab;                /* A table in the database */
83862
83863   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
83864   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
83865     assert( pDb!=0 );
83866     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
83867       pTab = (Table*)sqliteHashData(k);
83868       reindexTable(pParse, pTab, zColl);
83869     }
83870   }
83871 }
83872 #endif
83873
83874 /*
83875 ** Generate code for the REINDEX command.
83876 **
83877 **        REINDEX                            -- 1
83878 **        REINDEX  <collation>               -- 2
83879 **        REINDEX  ?<database>.?<tablename>  -- 3
83880 **        REINDEX  ?<database>.?<indexname>  -- 4
83881 **
83882 ** Form 1 causes all indices in all attached databases to be rebuilt.
83883 ** Form 2 rebuilds all indices in all databases that use the named
83884 ** collating function.  Forms 3 and 4 rebuild the named index or all
83885 ** indices associated with the named table.
83886 */
83887 #ifndef SQLITE_OMIT_REINDEX
83888 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
83889   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
83890   char *z;                    /* Name of a table or index */
83891   const char *zDb;            /* Name of the database */
83892   Table *pTab;                /* A table in the database */
83893   Index *pIndex;              /* An index associated with pTab */
83894   int iDb;                    /* The database index number */
83895   sqlite3 *db = pParse->db;   /* The database connection */
83896   Token *pObjName;            /* Name of the table or index to be reindexed */
83897
83898   /* Read the database schema. If an error occurs, leave an error message
83899   ** and code in pParse and return NULL. */
83900   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83901     return;
83902   }
83903
83904   if( pName1==0 ){
83905     reindexDatabases(pParse, 0);
83906     return;
83907   }else if( NEVER(pName2==0) || pName2->z==0 ){
83908     char *zColl;
83909     assert( pName1->z );
83910     zColl = sqlite3NameFromToken(pParse->db, pName1);
83911     if( !zColl ) return;
83912     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
83913     if( pColl ){
83914       reindexDatabases(pParse, zColl);
83915       sqlite3DbFree(db, zColl);
83916       return;
83917     }
83918     sqlite3DbFree(db, zColl);
83919   }
83920   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
83921   if( iDb<0 ) return;
83922   z = sqlite3NameFromToken(db, pObjName);
83923   if( z==0 ) return;
83924   zDb = db->aDb[iDb].zName;
83925   pTab = sqlite3FindTable(db, z, zDb);
83926   if( pTab ){
83927     reindexTable(pParse, pTab, 0);
83928     sqlite3DbFree(db, z);
83929     return;
83930   }
83931   pIndex = sqlite3FindIndex(db, z, zDb);
83932   sqlite3DbFree(db, z);
83933   if( pIndex ){
83934     sqlite3BeginWriteOperation(pParse, 0, iDb);
83935     sqlite3RefillIndex(pParse, pIndex, -1);
83936     return;
83937   }
83938   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
83939 }
83940 #endif
83941
83942 /*
83943 ** Return a dynamicly allocated KeyInfo structure that can be used
83944 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
83945 **
83946 ** If successful, a pointer to the new structure is returned. In this case
83947 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
83948 ** pointer. If an error occurs (out of memory or missing collation 
83949 ** sequence), NULL is returned and the state of pParse updated to reflect
83950 ** the error.
83951 */
83952 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
83953   int i;
83954   int nCol = pIdx->nColumn;
83955   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
83956   sqlite3 *db = pParse->db;
83957   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
83958
83959   if( pKey ){
83960     pKey->db = pParse->db;
83961     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
83962     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
83963     for(i=0; i<nCol; i++){
83964       char *zColl = pIdx->azColl[i];
83965       assert( zColl );
83966       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
83967       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
83968     }
83969     pKey->nField = (u16)nCol;
83970   }
83971
83972   if( pParse->nErr ){
83973     sqlite3DbFree(db, pKey);
83974     pKey = 0;
83975   }
83976   return pKey;
83977 }
83978
83979 /************** End of build.c ***********************************************/
83980 /************** Begin file callback.c ****************************************/
83981 /*
83982 ** 2005 May 23 
83983 **
83984 ** The author disclaims copyright to this source code.  In place of
83985 ** a legal notice, here is a blessing:
83986 **
83987 **    May you do good and not evil.
83988 **    May you find forgiveness for yourself and forgive others.
83989 **    May you share freely, never taking more than you give.
83990 **
83991 *************************************************************************
83992 **
83993 ** This file contains functions used to access the internal hash tables
83994 ** of user defined functions and collation sequences.
83995 */
83996
83997
83998 /*
83999 ** Invoke the 'collation needed' callback to request a collation sequence
84000 ** in the encoding enc of name zName, length nName.
84001 */
84002 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
84003   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84004   if( db->xCollNeeded ){
84005     char *zExternal = sqlite3DbStrDup(db, zName);
84006     if( !zExternal ) return;
84007     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84008     sqlite3DbFree(db, zExternal);
84009   }
84010 #ifndef SQLITE_OMIT_UTF16
84011   if( db->xCollNeeded16 ){
84012     char const *zExternal;
84013     sqlite3_value *pTmp = sqlite3ValueNew(db);
84014     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
84015     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
84016     if( zExternal ){
84017       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84018     }
84019     sqlite3ValueFree(pTmp);
84020   }
84021 #endif
84022 }
84023
84024 /*
84025 ** This routine is called if the collation factory fails to deliver a
84026 ** collation function in the best encoding but there may be other versions
84027 ** of this collation function (for other text encodings) available. Use one
84028 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84029 ** possible.
84030 */
84031 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
84032   CollSeq *pColl2;
84033   char *z = pColl->zName;
84034   int i;
84035   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
84036   for(i=0; i<3; i++){
84037     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
84038     if( pColl2->xCmp!=0 ){
84039       memcpy(pColl, pColl2, sizeof(CollSeq));
84040       pColl->xDel = 0;         /* Do not copy the destructor */
84041       return SQLITE_OK;
84042     }
84043   }
84044   return SQLITE_ERROR;
84045 }
84046
84047 /*
84048 ** This function is responsible for invoking the collation factory callback
84049 ** or substituting a collation sequence of a different encoding when the
84050 ** requested collation sequence is not available in the desired encoding.
84051 ** 
84052 ** If it is not NULL, then pColl must point to the database native encoding 
84053 ** collation sequence with name zName, length nName.
84054 **
84055 ** The return value is either the collation sequence to be used in database
84056 ** db for collation type name zName, length nName, or NULL, if no collation
84057 ** sequence can be found.
84058 **
84059 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
84060 */
84061 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
84062   sqlite3* db,          /* The database connection */
84063   u8 enc,               /* The desired encoding for the collating sequence */
84064   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84065   const char *zName     /* Collating sequence name */
84066 ){
84067   CollSeq *p;
84068
84069   p = pColl;
84070   if( !p ){
84071     p = sqlite3FindCollSeq(db, enc, zName, 0);
84072   }
84073   if( !p || !p->xCmp ){
84074     /* No collation sequence of this type for this encoding is registered.
84075     ** Call the collation factory to see if it can supply us with one.
84076     */
84077     callCollNeeded(db, enc, zName);
84078     p = sqlite3FindCollSeq(db, enc, zName, 0);
84079   }
84080   if( p && !p->xCmp && synthCollSeq(db, p) ){
84081     p = 0;
84082   }
84083   assert( !p || p->xCmp );
84084   return p;
84085 }
84086
84087 /*
84088 ** This routine is called on a collation sequence before it is used to
84089 ** check that it is defined. An undefined collation sequence exists when
84090 ** a database is loaded that contains references to collation sequences
84091 ** that have not been defined by sqlite3_create_collation() etc.
84092 **
84093 ** If required, this routine calls the 'collation needed' callback to
84094 ** request a definition of the collating sequence. If this doesn't work, 
84095 ** an equivalent collating sequence that uses a text encoding different
84096 ** from the main database is substituted, if one is available.
84097 */
84098 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84099   if( pColl ){
84100     const char *zName = pColl->zName;
84101     sqlite3 *db = pParse->db;
84102     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
84103     if( !p ){
84104       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84105       pParse->nErr++;
84106       return SQLITE_ERROR;
84107     }
84108     assert( p==pColl );
84109   }
84110   return SQLITE_OK;
84111 }
84112
84113
84114
84115 /*
84116 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84117 ** specified by zName and nName is not found and parameter 'create' is
84118 ** true, then create a new entry. Otherwise return NULL.
84119 **
84120 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
84121 ** array of three CollSeq structures. The first is the collation sequence
84122 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84123 **
84124 ** Stored immediately after the three collation sequences is a copy of
84125 ** the collation sequence name. A pointer to this string is stored in
84126 ** each collation sequence structure.
84127 */
84128 static CollSeq *findCollSeqEntry(
84129   sqlite3 *db,          /* Database connection */
84130   const char *zName,    /* Name of the collating sequence */
84131   int create            /* Create a new entry if true */
84132 ){
84133   CollSeq *pColl;
84134   int nName = sqlite3Strlen30(zName);
84135   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
84136
84137   if( 0==pColl && create ){
84138     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84139     if( pColl ){
84140       CollSeq *pDel = 0;
84141       pColl[0].zName = (char*)&pColl[3];
84142       pColl[0].enc = SQLITE_UTF8;
84143       pColl[1].zName = (char*)&pColl[3];
84144       pColl[1].enc = SQLITE_UTF16LE;
84145       pColl[2].zName = (char*)&pColl[3];
84146       pColl[2].enc = SQLITE_UTF16BE;
84147       memcpy(pColl[0].zName, zName, nName);
84148       pColl[0].zName[nName] = 0;
84149       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84150
84151       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
84152       ** return the pColl pointer to be deleted (because it wasn't added
84153       ** to the hash table).
84154       */
84155       assert( pDel==0 || pDel==pColl );
84156       if( pDel!=0 ){
84157         db->mallocFailed = 1;
84158         sqlite3DbFree(db, pDel);
84159         pColl = 0;
84160       }
84161     }
84162   }
84163   return pColl;
84164 }
84165
84166 /*
84167 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84168 ** Return the CollSeq* pointer for the collation sequence named zName
84169 ** for the encoding 'enc' from the database 'db'.
84170 **
84171 ** If the entry specified is not found and 'create' is true, then create a
84172 ** new entry.  Otherwise return NULL.
84173 **
84174 ** A separate function sqlite3LocateCollSeq() is a wrapper around
84175 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
84176 ** if necessary and generates an error message if the collating sequence
84177 ** cannot be found.
84178 **
84179 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
84180 */
84181 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
84182   sqlite3 *db,
84183   u8 enc,
84184   const char *zName,
84185   int create
84186 ){
84187   CollSeq *pColl;
84188   if( zName ){
84189     pColl = findCollSeqEntry(db, zName, create);
84190   }else{
84191     pColl = db->pDfltColl;
84192   }
84193   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
84194   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
84195   if( pColl ) pColl += enc-1;
84196   return pColl;
84197 }
84198
84199 /* During the search for the best function definition, this procedure
84200 ** is called to test how well the function passed as the first argument
84201 ** matches the request for a function with nArg arguments in a system
84202 ** that uses encoding enc. The value returned indicates how well the
84203 ** request is matched. A higher value indicates a better match.
84204 **
84205 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
84206 ** is also -1.  In other words, we are searching for a function that
84207 ** takes a variable number of arguments.
84208 **
84209 ** If nArg is -2 that means that we are searching for any function 
84210 ** regardless of the number of arguments it uses, so return a positive
84211 ** match score for any
84212 **
84213 ** The returned value is always between 0 and 6, as follows:
84214 **
84215 ** 0: Not a match.
84216 ** 1: UTF8/16 conversion required and function takes any number of arguments.
84217 ** 2: UTF16 byte order change required and function takes any number of args.
84218 ** 3: encoding matches and function takes any number of arguments
84219 ** 4: UTF8/16 conversion required - argument count matches exactly
84220 ** 5: UTF16 byte order conversion required - argument count matches exactly
84221 ** 6: Perfect match:  encoding and argument count match exactly.
84222 **
84223 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
84224 ** a perfect match and any function with both xStep and xFunc NULL is
84225 ** a non-match.
84226 */
84227 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
84228 static int matchQuality(
84229   FuncDef *p,     /* The function we are evaluating for match quality */
84230   int nArg,       /* Desired number of arguments.  (-1)==any */
84231   u8 enc          /* Desired text encoding */
84232 ){
84233   int match;
84234
84235   /* nArg of -2 is a special case */
84236   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
84237
84238   /* Wrong number of arguments means "no match" */
84239   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
84240
84241   /* Give a better score to a function with a specific number of arguments
84242   ** than to function that accepts any number of arguments. */
84243   if( p->nArg==nArg ){
84244     match = 4;
84245   }else{
84246     match = 1;
84247   }
84248
84249   /* Bonus points if the text encoding matches */
84250   if( enc==p->iPrefEnc ){
84251     match += 2;  /* Exact encoding match */
84252   }else if( (enc & p->iPrefEnc & 2)!=0 ){
84253     match += 1;  /* Both are UTF16, but with different byte orders */
84254   }
84255
84256   return match;
84257 }
84258
84259 /*
84260 ** Search a FuncDefHash for a function with the given name.  Return
84261 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
84262 */
84263 static FuncDef *functionSearch(
84264   FuncDefHash *pHash,  /* Hash table to search */
84265   int h,               /* Hash of the name */
84266   const char *zFunc,   /* Name of function */
84267   int nFunc            /* Number of bytes in zFunc */
84268 ){
84269   FuncDef *p;
84270   for(p=pHash->a[h]; p; p=p->pHash){
84271     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
84272       return p;
84273     }
84274   }
84275   return 0;
84276 }
84277
84278 /*
84279 ** Insert a new FuncDef into a FuncDefHash hash table.
84280 */
84281 SQLITE_PRIVATE void sqlite3FuncDefInsert(
84282   FuncDefHash *pHash,  /* The hash table into which to insert */
84283   FuncDef *pDef        /* The function definition to insert */
84284 ){
84285   FuncDef *pOther;
84286   int nName = sqlite3Strlen30(pDef->zName);
84287   u8 c1 = (u8)pDef->zName[0];
84288   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
84289   pOther = functionSearch(pHash, h, pDef->zName, nName);
84290   if( pOther ){
84291     assert( pOther!=pDef && pOther->pNext!=pDef );
84292     pDef->pNext = pOther->pNext;
84293     pOther->pNext = pDef;
84294   }else{
84295     pDef->pNext = 0;
84296     pDef->pHash = pHash->a[h];
84297     pHash->a[h] = pDef;
84298   }
84299 }
84300   
84301   
84302
84303 /*
84304 ** Locate a user function given a name, a number of arguments and a flag
84305 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
84306 ** pointer to the FuncDef structure that defines that function, or return
84307 ** NULL if the function does not exist.
84308 **
84309 ** If the createFlag argument is true, then a new (blank) FuncDef
84310 ** structure is created and liked into the "db" structure if a
84311 ** no matching function previously existed.
84312 **
84313 ** If nArg is -2, then the first valid function found is returned.  A
84314 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
84315 ** case is used to see if zName is a valid function name for some number
84316 ** of arguments.  If nArg is -2, then createFlag must be 0.
84317 **
84318 ** If createFlag is false, then a function with the required name and
84319 ** number of arguments may be returned even if the eTextRep flag does not
84320 ** match that requested.
84321 */
84322 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
84323   sqlite3 *db,       /* An open database */
84324   const char *zName, /* Name of the function.  Not null-terminated */
84325   int nName,         /* Number of characters in the name */
84326   int nArg,          /* Number of arguments.  -1 means any number */
84327   u8 enc,            /* Preferred text encoding */
84328   u8 createFlag      /* Create new entry if true and does not otherwise exist */
84329 ){
84330   FuncDef *p;         /* Iterator variable */
84331   FuncDef *pBest = 0; /* Best match found so far */
84332   int bestScore = 0;  /* Score of best match */
84333   int h;              /* Hash value */
84334
84335   assert( nArg>=(-2) );
84336   assert( nArg>=(-1) || createFlag==0 );
84337   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
84338   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
84339
84340   /* First search for a match amongst the application-defined functions.
84341   */
84342   p = functionSearch(&db->aFunc, h, zName, nName);
84343   while( p ){
84344     int score = matchQuality(p, nArg, enc);
84345     if( score>bestScore ){
84346       pBest = p;
84347       bestScore = score;
84348     }
84349     p = p->pNext;
84350   }
84351
84352   /* If no match is found, search the built-in functions.
84353   **
84354   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
84355   ** functions even if a prior app-defined function was found.  And give
84356   ** priority to built-in functions.
84357   **
84358   ** Except, if createFlag is true, that means that we are trying to
84359   ** install a new function.  Whatever FuncDef structure is returned it will
84360   ** have fields overwritten with new information appropriate for the
84361   ** new function.  But the FuncDefs for built-in functions are read-only.
84362   ** So we must not search for built-ins when creating a new function.
84363   */ 
84364   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
84365     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
84366     bestScore = 0;
84367     p = functionSearch(pHash, h, zName, nName);
84368     while( p ){
84369       int score = matchQuality(p, nArg, enc);
84370       if( score>bestScore ){
84371         pBest = p;
84372         bestScore = score;
84373       }
84374       p = p->pNext;
84375     }
84376   }
84377
84378   /* If the createFlag parameter is true and the search did not reveal an
84379   ** exact match for the name, number of arguments and encoding, then add a
84380   ** new entry to the hash table and return it.
84381   */
84382   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
84383       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
84384     pBest->zName = (char *)&pBest[1];
84385     pBest->nArg = (u16)nArg;
84386     pBest->iPrefEnc = enc;
84387     memcpy(pBest->zName, zName, nName);
84388     pBest->zName[nName] = 0;
84389     sqlite3FuncDefInsert(&db->aFunc, pBest);
84390   }
84391
84392   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
84393     return pBest;
84394   }
84395   return 0;
84396 }
84397
84398 /*
84399 ** Free all resources held by the schema structure. The void* argument points
84400 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
84401 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
84402 ** of the schema hash tables).
84403 **
84404 ** The Schema.cache_size variable is not cleared.
84405 */
84406 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
84407   Hash temp1;
84408   Hash temp2;
84409   HashElem *pElem;
84410   Schema *pSchema = (Schema *)p;
84411
84412   temp1 = pSchema->tblHash;
84413   temp2 = pSchema->trigHash;
84414   sqlite3HashInit(&pSchema->trigHash);
84415   sqlite3HashClear(&pSchema->idxHash);
84416   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
84417     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
84418   }
84419   sqlite3HashClear(&temp2);
84420   sqlite3HashInit(&pSchema->tblHash);
84421   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
84422     Table *pTab = sqliteHashData(pElem);
84423     sqlite3DeleteTable(0, pTab);
84424   }
84425   sqlite3HashClear(&temp1);
84426   sqlite3HashClear(&pSchema->fkeyHash);
84427   pSchema->pSeqTab = 0;
84428   if( pSchema->flags & DB_SchemaLoaded ){
84429     pSchema->iGeneration++;
84430     pSchema->flags &= ~DB_SchemaLoaded;
84431   }
84432 }
84433
84434 /*
84435 ** Find and return the schema associated with a BTree.  Create
84436 ** a new one if necessary.
84437 */
84438 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
84439   Schema * p;
84440   if( pBt ){
84441     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
84442   }else{
84443     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
84444   }
84445   if( !p ){
84446     db->mallocFailed = 1;
84447   }else if ( 0==p->file_format ){
84448     sqlite3HashInit(&p->tblHash);
84449     sqlite3HashInit(&p->idxHash);
84450     sqlite3HashInit(&p->trigHash);
84451     sqlite3HashInit(&p->fkeyHash);
84452     p->enc = SQLITE_UTF8;
84453   }
84454   return p;
84455 }
84456
84457 /************** End of callback.c ********************************************/
84458 /************** Begin file delete.c ******************************************/
84459 /*
84460 ** 2001 September 15
84461 **
84462 ** The author disclaims copyright to this source code.  In place of
84463 ** a legal notice, here is a blessing:
84464 **
84465 **    May you do good and not evil.
84466 **    May you find forgiveness for yourself and forgive others.
84467 **    May you share freely, never taking more than you give.
84468 **
84469 *************************************************************************
84470 ** This file contains C code routines that are called by the parser
84471 ** in order to generate code for DELETE FROM statements.
84472 */
84473
84474 /*
84475 ** While a SrcList can in general represent multiple tables and subqueries
84476 ** (as in the FROM clause of a SELECT statement) in this case it contains
84477 ** the name of a single table, as one might find in an INSERT, DELETE,
84478 ** or UPDATE statement.  Look up that table in the symbol table and
84479 ** return a pointer.  Set an error message and return NULL if the table 
84480 ** name is not found or if any other error occurs.
84481 **
84482 ** The following fields are initialized appropriate in pSrc:
84483 **
84484 **    pSrc->a[0].pTab       Pointer to the Table object
84485 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
84486 **
84487 */
84488 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
84489   struct SrcList_item *pItem = pSrc->a;
84490   Table *pTab;
84491   assert( pItem && pSrc->nSrc==1 );
84492   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
84493   sqlite3DeleteTable(pParse->db, pItem->pTab);
84494   pItem->pTab = pTab;
84495   if( pTab ){
84496     pTab->nRef++;
84497   }
84498   if( sqlite3IndexedByLookup(pParse, pItem) ){
84499     pTab = 0;
84500   }
84501   return pTab;
84502 }
84503
84504 /*
84505 ** Check to make sure the given table is writable.  If it is not
84506 ** writable, generate an error message and return 1.  If it is
84507 ** writable return 0;
84508 */
84509 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
84510   /* A table is not writable under the following circumstances:
84511   **
84512   **   1) It is a virtual table and no implementation of the xUpdate method
84513   **      has been provided, or
84514   **   2) It is a system table (i.e. sqlite_master), this call is not
84515   **      part of a nested parse and writable_schema pragma has not 
84516   **      been specified.
84517   **
84518   ** In either case leave an error message in pParse and return non-zero.
84519   */
84520   if( ( IsVirtual(pTab) 
84521      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
84522    || ( (pTab->tabFlags & TF_Readonly)!=0
84523      && (pParse->db->flags & SQLITE_WriteSchema)==0
84524      && pParse->nested==0 )
84525   ){
84526     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
84527     return 1;
84528   }
84529
84530 #ifndef SQLITE_OMIT_VIEW
84531   if( !viewOk && pTab->pSelect ){
84532     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
84533     return 1;
84534   }
84535 #endif
84536   return 0;
84537 }
84538
84539
84540 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84541 /*
84542 ** Evaluate a view and store its result in an ephemeral table.  The
84543 ** pWhere argument is an optional WHERE clause that restricts the
84544 ** set of rows in the view that are to be added to the ephemeral table.
84545 */
84546 SQLITE_PRIVATE void sqlite3MaterializeView(
84547   Parse *pParse,       /* Parsing context */
84548   Table *pView,        /* View definition */
84549   Expr *pWhere,        /* Optional WHERE clause to be added */
84550   int iCur             /* Cursor number for ephemerial table */
84551 ){
84552   SelectDest dest;
84553   Select *pDup;
84554   sqlite3 *db = pParse->db;
84555
84556   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
84557   if( pWhere ){
84558     SrcList *pFrom;
84559     
84560     pWhere = sqlite3ExprDup(db, pWhere, 0);
84561     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
84562     if( pFrom ){
84563       assert( pFrom->nSrc==1 );
84564       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
84565       pFrom->a[0].pSelect = pDup;
84566       assert( pFrom->a[0].pOn==0 );
84567       assert( pFrom->a[0].pUsing==0 );
84568     }else{
84569       sqlite3SelectDelete(db, pDup);
84570     }
84571     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
84572   }
84573   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
84574   sqlite3Select(pParse, pDup, &dest);
84575   sqlite3SelectDelete(db, pDup);
84576 }
84577 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
84578
84579 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
84580 /*
84581 ** Generate an expression tree to implement the WHERE, ORDER BY,
84582 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
84583 **
84584 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
84585 **                            \__________________________/
84586 **                               pLimitWhere (pInClause)
84587 */
84588 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
84589   Parse *pParse,               /* The parser context */
84590   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
84591   Expr *pWhere,                /* The WHERE clause.  May be null */
84592   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
84593   Expr *pLimit,                /* The LIMIT clause.  May be null */
84594   Expr *pOffset,               /* The OFFSET clause.  May be null */
84595   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
84596 ){
84597   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
84598   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
84599   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
84600   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
84601   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
84602   Select *pSelect = NULL;      /* Complete SELECT tree */
84603
84604   /* Check that there isn't an ORDER BY without a LIMIT clause.
84605   */
84606   if( pOrderBy && (pLimit == 0) ) {
84607     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
84608     goto limit_where_cleanup_2;
84609   }
84610
84611   /* We only need to generate a select expression if there
84612   ** is a limit/offset term to enforce.
84613   */
84614   if( pLimit == 0 ) {
84615     /* if pLimit is null, pOffset will always be null as well. */
84616     assert( pOffset == 0 );
84617     return pWhere;
84618   }
84619
84620   /* Generate a select expression tree to enforce the limit/offset 
84621   ** term for the DELETE or UPDATE statement.  For example:
84622   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
84623   ** becomes:
84624   **   DELETE FROM table_a WHERE rowid IN ( 
84625   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
84626   **   );
84627   */
84628
84629   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
84630   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
84631   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
84632   if( pEList == 0 ) goto limit_where_cleanup_2;
84633
84634   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
84635   ** and the SELECT subtree. */
84636   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
84637   if( pSelectSrc == 0 ) {
84638     sqlite3ExprListDelete(pParse->db, pEList);
84639     goto limit_where_cleanup_2;
84640   }
84641
84642   /* generate the SELECT expression tree. */
84643   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
84644                              pOrderBy,0,pLimit,pOffset);
84645   if( pSelect == 0 ) return 0;
84646
84647   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
84648   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
84649   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
84650   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
84651   if( pInClause == 0 ) goto limit_where_cleanup_1;
84652
84653   pInClause->x.pSelect = pSelect;
84654   pInClause->flags |= EP_xIsSelect;
84655   sqlite3ExprSetHeight(pParse, pInClause);
84656   return pInClause;
84657
84658   /* something went wrong. clean up anything allocated. */
84659 limit_where_cleanup_1:
84660   sqlite3SelectDelete(pParse->db, pSelect);
84661   return 0;
84662
84663 limit_where_cleanup_2:
84664   sqlite3ExprDelete(pParse->db, pWhere);
84665   sqlite3ExprListDelete(pParse->db, pOrderBy);
84666   sqlite3ExprDelete(pParse->db, pLimit);
84667   sqlite3ExprDelete(pParse->db, pOffset);
84668   return 0;
84669 }
84670 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
84671
84672 /*
84673 ** Generate code for a DELETE FROM statement.
84674 **
84675 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
84676 **                 \________/       \________________/
84677 **                  pTabList              pWhere
84678 */
84679 SQLITE_PRIVATE void sqlite3DeleteFrom(
84680   Parse *pParse,         /* The parser context */
84681   SrcList *pTabList,     /* The table from which we should delete things */
84682   Expr *pWhere           /* The WHERE clause.  May be null */
84683 ){
84684   Vdbe *v;               /* The virtual database engine */
84685   Table *pTab;           /* The table from which records will be deleted */
84686   const char *zDb;       /* Name of database holding pTab */
84687   int end, addr = 0;     /* A couple addresses of generated code */
84688   int i;                 /* Loop counter */
84689   WhereInfo *pWInfo;     /* Information about the WHERE clause */
84690   Index *pIdx;           /* For looping over indices of the table */
84691   int iCur;              /* VDBE Cursor number for pTab */
84692   sqlite3 *db;           /* Main database structure */
84693   AuthContext sContext;  /* Authorization context */
84694   NameContext sNC;       /* Name context to resolve expressions in */
84695   int iDb;               /* Database number */
84696   int memCnt = -1;       /* Memory cell used for change counting */
84697   int rcauth;            /* Value returned by authorization callback */
84698
84699 #ifndef SQLITE_OMIT_TRIGGER
84700   int isView;                  /* True if attempting to delete from a view */
84701   Trigger *pTrigger;           /* List of table triggers, if required */
84702 #endif
84703
84704   memset(&sContext, 0, sizeof(sContext));
84705   db = pParse->db;
84706   if( pParse->nErr || db->mallocFailed ){
84707     goto delete_from_cleanup;
84708   }
84709   assert( pTabList->nSrc==1 );
84710
84711   /* Locate the table which we want to delete.  This table has to be
84712   ** put in an SrcList structure because some of the subroutines we
84713   ** will be calling are designed to work with multiple tables and expect
84714   ** an SrcList* parameter instead of just a Table* parameter.
84715   */
84716   pTab = sqlite3SrcListLookup(pParse, pTabList);
84717   if( pTab==0 )  goto delete_from_cleanup;
84718
84719   /* Figure out if we have any triggers and if the table being
84720   ** deleted from is a view
84721   */
84722 #ifndef SQLITE_OMIT_TRIGGER
84723   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
84724   isView = pTab->pSelect!=0;
84725 #else
84726 # define pTrigger 0
84727 # define isView 0
84728 #endif
84729 #ifdef SQLITE_OMIT_VIEW
84730 # undef isView
84731 # define isView 0
84732 #endif
84733
84734   /* If pTab is really a view, make sure it has been initialized.
84735   */
84736   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84737     goto delete_from_cleanup;
84738   }
84739
84740   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
84741     goto delete_from_cleanup;
84742   }
84743   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84744   assert( iDb<db->nDb );
84745   zDb = db->aDb[iDb].zName;
84746   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
84747   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
84748   if( rcauth==SQLITE_DENY ){
84749     goto delete_from_cleanup;
84750   }
84751   assert(!isView || pTrigger);
84752
84753   /* Assign  cursor number to the table and all its indices.
84754   */
84755   assert( pTabList->nSrc==1 );
84756   iCur = pTabList->a[0].iCursor = pParse->nTab++;
84757   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84758     pParse->nTab++;
84759   }
84760
84761   /* Start the view context
84762   */
84763   if( isView ){
84764     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
84765   }
84766
84767   /* Begin generating code.
84768   */
84769   v = sqlite3GetVdbe(pParse);
84770   if( v==0 ){
84771     goto delete_from_cleanup;
84772   }
84773   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84774   sqlite3BeginWriteOperation(pParse, 1, iDb);
84775
84776   /* If we are trying to delete from a view, realize that view into
84777   ** a ephemeral table.
84778   */
84779 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84780   if( isView ){
84781     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
84782   }
84783 #endif
84784
84785   /* Resolve the column names in the WHERE clause.
84786   */
84787   memset(&sNC, 0, sizeof(sNC));
84788   sNC.pParse = pParse;
84789   sNC.pSrcList = pTabList;
84790   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
84791     goto delete_from_cleanup;
84792   }
84793
84794   /* Initialize the counter of the number of rows deleted, if
84795   ** we are counting rows.
84796   */
84797   if( db->flags & SQLITE_CountRows ){
84798     memCnt = ++pParse->nMem;
84799     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
84800   }
84801
84802 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
84803   /* Special case: A DELETE without a WHERE clause deletes everything.
84804   ** It is easier just to erase the whole table. Prior to version 3.6.5,
84805   ** this optimization caused the row change count (the value returned by 
84806   ** API function sqlite3_count_changes) to be set incorrectly.  */
84807   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
84808    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
84809   ){
84810     assert( !isView );
84811     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
84812                       pTab->zName, P4_STATIC);
84813     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84814       assert( pIdx->pSchema==pTab->pSchema );
84815       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
84816     }
84817   }else
84818 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
84819   /* The usual case: There is a WHERE clause so we have to scan through
84820   ** the table and pick which records to delete.
84821   */
84822   {
84823     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
84824     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
84825     int regRowid;                   /* Actual register containing rowids */
84826
84827     /* Collect rowids of every row to be deleted.
84828     */
84829     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
84830     pWInfo = sqlite3WhereBegin(
84831         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
84832     );
84833     if( pWInfo==0 ) goto delete_from_cleanup;
84834     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
84835     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
84836     if( db->flags & SQLITE_CountRows ){
84837       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
84838     }
84839     sqlite3WhereEnd(pWInfo);
84840
84841     /* Delete every item whose key was written to the list during the
84842     ** database scan.  We have to delete items after the scan is complete
84843     ** because deleting an item can change the scan order.  */
84844     end = sqlite3VdbeMakeLabel(v);
84845
84846     /* Unless this is a view, open cursors for the table we are 
84847     ** deleting from and all its indices. If this is a view, then the
84848     ** only effect this statement has is to fire the INSTEAD OF 
84849     ** triggers.  */
84850     if( !isView ){
84851       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
84852     }
84853
84854     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
84855
84856     /* Delete the row */
84857 #ifndef SQLITE_OMIT_VIRTUALTABLE
84858     if( IsVirtual(pTab) ){
84859       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
84860       sqlite3VtabMakeWritable(pParse, pTab);
84861       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
84862       sqlite3VdbeChangeP5(v, OE_Abort);
84863       sqlite3MayAbort(pParse);
84864     }else
84865 #endif
84866     {
84867       int count = (pParse->nested==0);    /* True to count changes */
84868       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
84869     }
84870
84871     /* End of the delete loop */
84872     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
84873     sqlite3VdbeResolveLabel(v, end);
84874
84875     /* Close the cursors open on the table and its indexes. */
84876     if( !isView && !IsVirtual(pTab) ){
84877       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
84878         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
84879       }
84880       sqlite3VdbeAddOp1(v, OP_Close, iCur);
84881     }
84882   }
84883
84884   /* Update the sqlite_sequence table by storing the content of the
84885   ** maximum rowid counter values recorded while inserting into
84886   ** autoincrement tables.
84887   */
84888   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
84889     sqlite3AutoincrementEnd(pParse);
84890   }
84891
84892   /* Return the number of rows that were deleted. If this routine is 
84893   ** generating code because of a call to sqlite3NestedParse(), do not
84894   ** invoke the callback function.
84895   */
84896   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
84897     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
84898     sqlite3VdbeSetNumCols(v, 1);
84899     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
84900   }
84901
84902 delete_from_cleanup:
84903   sqlite3AuthContextPop(&sContext);
84904   sqlite3SrcListDelete(db, pTabList);
84905   sqlite3ExprDelete(db, pWhere);
84906   return;
84907 }
84908 /* Make sure "isView" and other macros defined above are undefined. Otherwise
84909 ** thely may interfere with compilation of other functions in this file
84910 ** (or in another file, if this file becomes part of the amalgamation).  */
84911 #ifdef isView
84912  #undef isView
84913 #endif
84914 #ifdef pTrigger
84915  #undef pTrigger
84916 #endif
84917
84918 /*
84919 ** This routine generates VDBE code that causes a single row of a
84920 ** single table to be deleted.
84921 **
84922 ** The VDBE must be in a particular state when this routine is called.
84923 ** These are the requirements:
84924 **
84925 **   1.  A read/write cursor pointing to pTab, the table containing the row
84926 **       to be deleted, must be opened as cursor number $iCur.
84927 **
84928 **   2.  Read/write cursors for all indices of pTab must be open as
84929 **       cursor number base+i for the i-th index.
84930 **
84931 **   3.  The record number of the row to be deleted must be stored in
84932 **       memory cell iRowid.
84933 **
84934 ** This routine generates code to remove both the table record and all 
84935 ** index entries that point to that record.
84936 */
84937 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
84938   Parse *pParse,     /* Parsing context */
84939   Table *pTab,       /* Table containing the row to be deleted */
84940   int iCur,          /* Cursor number for the table */
84941   int iRowid,        /* Memory cell that contains the rowid to delete */
84942   int count,         /* If non-zero, increment the row change counter */
84943   Trigger *pTrigger, /* List of triggers to (potentially) fire */
84944   int onconf         /* Default ON CONFLICT policy for triggers */
84945 ){
84946   Vdbe *v = pParse->pVdbe;        /* Vdbe */
84947   int iOld = 0;                   /* First register in OLD.* array */
84948   int iLabel;                     /* Label resolved to end of generated code */
84949
84950   /* Vdbe is guaranteed to have been allocated by this stage. */
84951   assert( v );
84952
84953   /* Seek cursor iCur to the row to delete. If this row no longer exists 
84954   ** (this can happen if a trigger program has already deleted it), do
84955   ** not attempt to delete it or fire any DELETE triggers.  */
84956   iLabel = sqlite3VdbeMakeLabel(v);
84957   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
84958  
84959   /* If there are any triggers to fire, allocate a range of registers to
84960   ** use for the old.* references in the triggers.  */
84961   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
84962     u32 mask;                     /* Mask of OLD.* columns in use */
84963     int iCol;                     /* Iterator used while populating OLD.* */
84964
84965     /* TODO: Could use temporary registers here. Also could attempt to
84966     ** avoid copying the contents of the rowid register.  */
84967     mask = sqlite3TriggerColmask(
84968         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
84969     );
84970     mask |= sqlite3FkOldmask(pParse, pTab);
84971     iOld = pParse->nMem+1;
84972     pParse->nMem += (1 + pTab->nCol);
84973
84974     /* Populate the OLD.* pseudo-table register array. These values will be 
84975     ** used by any BEFORE and AFTER triggers that exist.  */
84976     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
84977     for(iCol=0; iCol<pTab->nCol; iCol++){
84978       if( mask==0xffffffff || mask&(1<<iCol) ){
84979         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
84980       }
84981     }
84982
84983     /* Invoke BEFORE DELETE trigger programs. */
84984     sqlite3CodeRowTrigger(pParse, pTrigger, 
84985         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
84986     );
84987
84988     /* Seek the cursor to the row to be deleted again. It may be that
84989     ** the BEFORE triggers coded above have already removed the row
84990     ** being deleted. Do not attempt to delete the row a second time, and 
84991     ** do not fire AFTER triggers.  */
84992     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
84993
84994     /* Do FK processing. This call checks that any FK constraints that
84995     ** refer to this table (i.e. constraints attached to other tables) 
84996     ** are not violated by deleting this row.  */
84997     sqlite3FkCheck(pParse, pTab, iOld, 0);
84998   }
84999
85000   /* Delete the index and table entries. Skip this step if pTab is really
85001   ** a view (in which case the only effect of the DELETE statement is to
85002   ** fire the INSTEAD OF triggers).  */ 
85003   if( pTab->pSelect==0 ){
85004     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85005     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85006     if( count ){
85007       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85008     }
85009   }
85010
85011   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85012   ** handle rows (possibly in other tables) that refer via a foreign key
85013   ** to the row just deleted. */ 
85014   sqlite3FkActions(pParse, pTab, 0, iOld);
85015
85016   /* Invoke AFTER DELETE trigger programs. */
85017   sqlite3CodeRowTrigger(pParse, pTrigger, 
85018       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85019   );
85020
85021   /* Jump here if the row had already been deleted before any BEFORE
85022   ** trigger programs were invoked. Or if a trigger program throws a 
85023   ** RAISE(IGNORE) exception.  */
85024   sqlite3VdbeResolveLabel(v, iLabel);
85025 }
85026
85027 /*
85028 ** This routine generates VDBE code that causes the deletion of all
85029 ** index entries associated with a single row of a single table.
85030 **
85031 ** The VDBE must be in a particular state when this routine is called.
85032 ** These are the requirements:
85033 **
85034 **   1.  A read/write cursor pointing to pTab, the table containing the row
85035 **       to be deleted, must be opened as cursor number "iCur".
85036 **
85037 **   2.  Read/write cursors for all indices of pTab must be open as
85038 **       cursor number iCur+i for the i-th index.
85039 **
85040 **   3.  The "iCur" cursor must be pointing to the row that is to be
85041 **       deleted.
85042 */
85043 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
85044   Parse *pParse,     /* Parsing and code generating context */
85045   Table *pTab,       /* Table containing the row to be deleted */
85046   int iCur,          /* Cursor number for the table */
85047   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85048 ){
85049   int i;
85050   Index *pIdx;
85051   int r1;
85052
85053   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85054     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85055     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85056     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85057   }
85058 }
85059
85060 /*
85061 ** Generate code that will assemble an index key and put it in register
85062 ** regOut.  The key with be for index pIdx which is an index on pTab.
85063 ** iCur is the index of a cursor open on the pTab table and pointing to
85064 ** the entry that needs indexing.
85065 **
85066 ** Return a register number which is the first in a block of
85067 ** registers that holds the elements of the index key.  The
85068 ** block of registers has already been deallocated by the time
85069 ** this routine returns.
85070 */
85071 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
85072   Parse *pParse,     /* Parsing context */
85073   Index *pIdx,       /* The index for which to generate a key */
85074   int iCur,          /* Cursor number for the pIdx->pTable table */
85075   int regOut,        /* Write the new index key to this register */
85076   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85077 ){
85078   Vdbe *v = pParse->pVdbe;
85079   int j;
85080   Table *pTab = pIdx->pTable;
85081   int regBase;
85082   int nCol;
85083
85084   nCol = pIdx->nColumn;
85085   regBase = sqlite3GetTempRange(pParse, nCol+1);
85086   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85087   for(j=0; j<nCol; j++){
85088     int idx = pIdx->aiColumn[j];
85089     if( idx==pTab->iPKey ){
85090       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85091     }else{
85092       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85093       sqlite3ColumnDefault(v, pTab, idx, -1);
85094     }
85095   }
85096   if( doMakeRec ){
85097     const char *zAff;
85098     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
85099       zAff = 0;
85100     }else{
85101       zAff = sqlite3IndexAffinityStr(v, pIdx);
85102     }
85103     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85104     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85105   }
85106   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
85107   return regBase;
85108 }
85109
85110 /************** End of delete.c **********************************************/
85111 /************** Begin file func.c ********************************************/
85112 /*
85113 ** 2002 February 23
85114 **
85115 ** The author disclaims copyright to this source code.  In place of
85116 ** a legal notice, here is a blessing:
85117 **
85118 **    May you do good and not evil.
85119 **    May you find forgiveness for yourself and forgive others.
85120 **    May you share freely, never taking more than you give.
85121 **
85122 *************************************************************************
85123 ** This file contains the C functions that implement various SQL
85124 ** functions of SQLite.  
85125 **
85126 ** There is only one exported symbol in this file - the function
85127 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
85128 ** All other code has file scope.
85129 */
85130 /* #include <stdlib.h> */
85131 /* #include <assert.h> */
85132
85133 /*
85134 ** Return the collating function associated with a function.
85135 */
85136 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
85137   return context->pColl;
85138 }
85139
85140 /*
85141 ** Indicate that the accumulator load should be skipped on this
85142 ** iteration of the aggregate loop.
85143 */
85144 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
85145   context->skipFlag = 1;
85146 }
85147
85148 /*
85149 ** Implementation of the non-aggregate min() and max() functions
85150 */
85151 static void minmaxFunc(
85152   sqlite3_context *context,
85153   int argc,
85154   sqlite3_value **argv
85155 ){
85156   int i;
85157   int mask;    /* 0 for min() or 0xffffffff for max() */
85158   int iBest;
85159   CollSeq *pColl;
85160
85161   assert( argc>1 );
85162   mask = sqlite3_user_data(context)==0 ? 0 : -1;
85163   pColl = sqlite3GetFuncCollSeq(context);
85164   assert( pColl );
85165   assert( mask==-1 || mask==0 );
85166   iBest = 0;
85167   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85168   for(i=1; i<argc; i++){
85169     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
85170     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85171       testcase( mask==0 );
85172       iBest = i;
85173     }
85174   }
85175   sqlite3_result_value(context, argv[iBest]);
85176 }
85177
85178 /*
85179 ** Return the type of the argument.
85180 */
85181 static void typeofFunc(
85182   sqlite3_context *context,
85183   int NotUsed,
85184   sqlite3_value **argv
85185 ){
85186   const char *z = 0;
85187   UNUSED_PARAMETER(NotUsed);
85188   switch( sqlite3_value_type(argv[0]) ){
85189     case SQLITE_INTEGER: z = "integer"; break;
85190     case SQLITE_TEXT:    z = "text";    break;
85191     case SQLITE_FLOAT:   z = "real";    break;
85192     case SQLITE_BLOB:    z = "blob";    break;
85193     default:             z = "null";    break;
85194   }
85195   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
85196 }
85197
85198
85199 /*
85200 ** Implementation of the length() function
85201 */
85202 static void lengthFunc(
85203   sqlite3_context *context,
85204   int argc,
85205   sqlite3_value **argv
85206 ){
85207   int len;
85208
85209   assert( argc==1 );
85210   UNUSED_PARAMETER(argc);
85211   switch( sqlite3_value_type(argv[0]) ){
85212     case SQLITE_BLOB:
85213     case SQLITE_INTEGER:
85214     case SQLITE_FLOAT: {
85215       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
85216       break;
85217     }
85218     case SQLITE_TEXT: {
85219       const unsigned char *z = sqlite3_value_text(argv[0]);
85220       if( z==0 ) return;
85221       len = 0;
85222       while( *z ){
85223         len++;
85224         SQLITE_SKIP_UTF8(z);
85225       }
85226       sqlite3_result_int(context, len);
85227       break;
85228     }
85229     default: {
85230       sqlite3_result_null(context);
85231       break;
85232     }
85233   }
85234 }
85235
85236 /*
85237 ** Implementation of the abs() function.
85238 **
85239 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
85240 ** the numeric argument X. 
85241 */
85242 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85243   assert( argc==1 );
85244   UNUSED_PARAMETER(argc);
85245   switch( sqlite3_value_type(argv[0]) ){
85246     case SQLITE_INTEGER: {
85247       i64 iVal = sqlite3_value_int64(argv[0]);
85248       if( iVal<0 ){
85249         if( (iVal<<1)==0 ){
85250           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
85251           ** abs(X) throws an integer overflow error since there is no
85252           ** equivalent positive 64-bit two complement value. */
85253           sqlite3_result_error(context, "integer overflow", -1);
85254           return;
85255         }
85256         iVal = -iVal;
85257       } 
85258       sqlite3_result_int64(context, iVal);
85259       break;
85260     }
85261     case SQLITE_NULL: {
85262       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
85263       sqlite3_result_null(context);
85264       break;
85265     }
85266     default: {
85267       /* Because sqlite3_value_double() returns 0.0 if the argument is not
85268       ** something that can be converted into a number, we have:
85269       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
85270       ** cannot be converted to a numeric value. 
85271       */
85272       double rVal = sqlite3_value_double(argv[0]);
85273       if( rVal<0 ) rVal = -rVal;
85274       sqlite3_result_double(context, rVal);
85275       break;
85276     }
85277   }
85278 }
85279
85280 /*
85281 ** Implementation of the substr() function.
85282 **
85283 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
85284 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
85285 ** of x.  If x is text, then we actually count UTF-8 characters.
85286 ** If x is a blob, then we count bytes.
85287 **
85288 ** If p1 is negative, then we begin abs(p1) from the end of x[].
85289 **
85290 ** If p2 is negative, return the p2 characters preceeding p1.
85291 */
85292 static void substrFunc(
85293   sqlite3_context *context,
85294   int argc,
85295   sqlite3_value **argv
85296 ){
85297   const unsigned char *z;
85298   const unsigned char *z2;
85299   int len;
85300   int p0type;
85301   i64 p1, p2;
85302   int negP2 = 0;
85303
85304   assert( argc==3 || argc==2 );
85305   if( sqlite3_value_type(argv[1])==SQLITE_NULL
85306    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
85307   ){
85308     return;
85309   }
85310   p0type = sqlite3_value_type(argv[0]);
85311   p1 = sqlite3_value_int(argv[1]);
85312   if( p0type==SQLITE_BLOB ){
85313     len = sqlite3_value_bytes(argv[0]);
85314     z = sqlite3_value_blob(argv[0]);
85315     if( z==0 ) return;
85316     assert( len==sqlite3_value_bytes(argv[0]) );
85317   }else{
85318     z = sqlite3_value_text(argv[0]);
85319     if( z==0 ) return;
85320     len = 0;
85321     if( p1<0 ){
85322       for(z2=z; *z2; len++){
85323         SQLITE_SKIP_UTF8(z2);
85324       }
85325     }
85326   }
85327   if( argc==3 ){
85328     p2 = sqlite3_value_int(argv[2]);
85329     if( p2<0 ){
85330       p2 = -p2;
85331       negP2 = 1;
85332     }
85333   }else{
85334     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
85335   }
85336   if( p1<0 ){
85337     p1 += len;
85338     if( p1<0 ){
85339       p2 += p1;
85340       if( p2<0 ) p2 = 0;
85341       p1 = 0;
85342     }
85343   }else if( p1>0 ){
85344     p1--;
85345   }else if( p2>0 ){
85346     p2--;
85347   }
85348   if( negP2 ){
85349     p1 -= p2;
85350     if( p1<0 ){
85351       p2 += p1;
85352       p1 = 0;
85353     }
85354   }
85355   assert( p1>=0 && p2>=0 );
85356   if( p0type!=SQLITE_BLOB ){
85357     while( *z && p1 ){
85358       SQLITE_SKIP_UTF8(z);
85359       p1--;
85360     }
85361     for(z2=z; *z2 && p2; p2--){
85362       SQLITE_SKIP_UTF8(z2);
85363     }
85364     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
85365   }else{
85366     if( p1+p2>len ){
85367       p2 = len-p1;
85368       if( p2<0 ) p2 = 0;
85369     }
85370     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
85371   }
85372 }
85373
85374 /*
85375 ** Implementation of the round() function
85376 */
85377 #ifndef SQLITE_OMIT_FLOATING_POINT
85378 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85379   int n = 0;
85380   double r;
85381   char *zBuf;
85382   assert( argc==1 || argc==2 );
85383   if( argc==2 ){
85384     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
85385     n = sqlite3_value_int(argv[1]);
85386     if( n>30 ) n = 30;
85387     if( n<0 ) n = 0;
85388   }
85389   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85390   r = sqlite3_value_double(argv[0]);
85391   /* If Y==0 and X will fit in a 64-bit int,
85392   ** handle the rounding directly,
85393   ** otherwise use printf.
85394   */
85395   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
85396     r = (double)((sqlite_int64)(r+0.5));
85397   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
85398     r = -(double)((sqlite_int64)((-r)+0.5));
85399   }else{
85400     zBuf = sqlite3_mprintf("%.*f",n,r);
85401     if( zBuf==0 ){
85402       sqlite3_result_error_nomem(context);
85403       return;
85404     }
85405     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
85406     sqlite3_free(zBuf);
85407   }
85408   sqlite3_result_double(context, r);
85409 }
85410 #endif
85411
85412 /*
85413 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
85414 ** allocation fails, call sqlite3_result_error_nomem() to notify
85415 ** the database handle that malloc() has failed and return NULL.
85416 ** If nByte is larger than the maximum string or blob length, then
85417 ** raise an SQLITE_TOOBIG exception and return NULL.
85418 */
85419 static void *contextMalloc(sqlite3_context *context, i64 nByte){
85420   char *z;
85421   sqlite3 *db = sqlite3_context_db_handle(context);
85422   assert( nByte>0 );
85423   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
85424   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
85425   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
85426     sqlite3_result_error_toobig(context);
85427     z = 0;
85428   }else{
85429     z = sqlite3Malloc((int)nByte);
85430     if( !z ){
85431       sqlite3_result_error_nomem(context);
85432     }
85433   }
85434   return z;
85435 }
85436
85437 /*
85438 ** Implementation of the upper() and lower() SQL functions.
85439 */
85440 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85441   char *z1;
85442   const char *z2;
85443   int i, n;
85444   UNUSED_PARAMETER(argc);
85445   z2 = (char*)sqlite3_value_text(argv[0]);
85446   n = sqlite3_value_bytes(argv[0]);
85447   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
85448   assert( z2==(char*)sqlite3_value_text(argv[0]) );
85449   if( z2 ){
85450     z1 = contextMalloc(context, ((i64)n)+1);
85451     if( z1 ){
85452       for(i=0; i<n; i++){
85453         z1[i] = (char)sqlite3Toupper(z2[i]);
85454       }
85455       sqlite3_result_text(context, z1, n, sqlite3_free);
85456     }
85457   }
85458 }
85459 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85460   char *z1;
85461   const char *z2;
85462   int i, n;
85463   UNUSED_PARAMETER(argc);
85464   z2 = (char*)sqlite3_value_text(argv[0]);
85465   n = sqlite3_value_bytes(argv[0]);
85466   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
85467   assert( z2==(char*)sqlite3_value_text(argv[0]) );
85468   if( z2 ){
85469     z1 = contextMalloc(context, ((i64)n)+1);
85470     if( z1 ){
85471       for(i=0; i<n; i++){
85472         z1[i] = sqlite3Tolower(z2[i]);
85473       }
85474       sqlite3_result_text(context, z1, n, sqlite3_free);
85475     }
85476   }
85477 }
85478
85479
85480 #if 0  /* This function is never used. */
85481 /*
85482 ** The COALESCE() and IFNULL() functions used to be implemented as shown
85483 ** here.  But now they are implemented as VDBE code so that unused arguments
85484 ** do not have to be computed.  This legacy implementation is retained as
85485 ** comment.
85486 */
85487 /*
85488 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
85489 ** All three do the same thing.  They return the first non-NULL
85490 ** argument.
85491 */
85492 static void ifnullFunc(
85493   sqlite3_context *context,
85494   int argc,
85495   sqlite3_value **argv
85496 ){
85497   int i;
85498   for(i=0; i<argc; i++){
85499     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
85500       sqlite3_result_value(context, argv[i]);
85501       break;
85502     }
85503   }
85504 }
85505 #endif /* NOT USED */
85506 #define ifnullFunc versionFunc   /* Substitute function - never called */
85507
85508 /*
85509 ** Implementation of random().  Return a random integer.  
85510 */
85511 static void randomFunc(
85512   sqlite3_context *context,
85513   int NotUsed,
85514   sqlite3_value **NotUsed2
85515 ){
85516   sqlite_int64 r;
85517   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85518   sqlite3_randomness(sizeof(r), &r);
85519   if( r<0 ){
85520     /* We need to prevent a random number of 0x8000000000000000 
85521     ** (or -9223372036854775808) since when you do abs() of that
85522     ** number of you get the same value back again.  To do this
85523     ** in a way that is testable, mask the sign bit off of negative
85524     ** values, resulting in a positive value.  Then take the 
85525     ** 2s complement of that positive value.  The end result can
85526     ** therefore be no less than -9223372036854775807.
85527     */
85528     r = -(r & LARGEST_INT64);
85529   }
85530   sqlite3_result_int64(context, r);
85531 }
85532
85533 /*
85534 ** Implementation of randomblob(N).  Return a random blob
85535 ** that is N bytes long.
85536 */
85537 static void randomBlob(
85538   sqlite3_context *context,
85539   int argc,
85540   sqlite3_value **argv
85541 ){
85542   int n;
85543   unsigned char *p;
85544   assert( argc==1 );
85545   UNUSED_PARAMETER(argc);
85546   n = sqlite3_value_int(argv[0]);
85547   if( n<1 ){
85548     n = 1;
85549   }
85550   p = contextMalloc(context, n);
85551   if( p ){
85552     sqlite3_randomness(n, p);
85553     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
85554   }
85555 }
85556
85557 /*
85558 ** Implementation of the last_insert_rowid() SQL function.  The return
85559 ** value is the same as the sqlite3_last_insert_rowid() API function.
85560 */
85561 static void last_insert_rowid(
85562   sqlite3_context *context, 
85563   int NotUsed, 
85564   sqlite3_value **NotUsed2
85565 ){
85566   sqlite3 *db = sqlite3_context_db_handle(context);
85567   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85568   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
85569   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
85570   ** function. */
85571   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
85572 }
85573
85574 /*
85575 ** Implementation of the changes() SQL function.
85576 **
85577 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
85578 ** around the sqlite3_changes() C/C++ function and hence follows the same
85579 ** rules for counting changes.
85580 */
85581 static void changes(
85582   sqlite3_context *context,
85583   int NotUsed,
85584   sqlite3_value **NotUsed2
85585 ){
85586   sqlite3 *db = sqlite3_context_db_handle(context);
85587   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85588   sqlite3_result_int(context, sqlite3_changes(db));
85589 }
85590
85591 /*
85592 ** Implementation of the total_changes() SQL function.  The return value is
85593 ** the same as the sqlite3_total_changes() API function.
85594 */
85595 static void total_changes(
85596   sqlite3_context *context,
85597   int NotUsed,
85598   sqlite3_value **NotUsed2
85599 ){
85600   sqlite3 *db = sqlite3_context_db_handle(context);
85601   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85602   /* IMP: R-52756-41993 This function is a wrapper around the
85603   ** sqlite3_total_changes() C/C++ interface. */
85604   sqlite3_result_int(context, sqlite3_total_changes(db));
85605 }
85606
85607 /*
85608 ** A structure defining how to do GLOB-style comparisons.
85609 */
85610 struct compareInfo {
85611   u8 matchAll;
85612   u8 matchOne;
85613   u8 matchSet;
85614   u8 noCase;
85615 };
85616
85617 /*
85618 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
85619 ** character is exactly one byte in size.  Also, all characters are
85620 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
85621 ** whereas only characters less than 0x80 do in ASCII.
85622 */
85623 #if defined(SQLITE_EBCDIC)
85624 # define sqlite3Utf8Read(A,C)  (*(A++))
85625 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
85626 #else
85627 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
85628 #endif
85629
85630 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
85631 /* The correct SQL-92 behavior is for the LIKE operator to ignore
85632 ** case.  Thus  'a' LIKE 'A' would be true. */
85633 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
85634 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
85635 ** is case sensitive causing 'a' LIKE 'A' to be false */
85636 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
85637
85638 /*
85639 ** Compare two UTF-8 strings for equality where the first string can
85640 ** potentially be a "glob" expression.  Return true (1) if they
85641 ** are the same and false (0) if they are different.
85642 **
85643 ** Globbing rules:
85644 **
85645 **      '*'       Matches any sequence of zero or more characters.
85646 **
85647 **      '?'       Matches exactly one character.
85648 **
85649 **     [...]      Matches one character from the enclosed list of
85650 **                characters.
85651 **
85652 **     [^...]     Matches one character not in the enclosed list.
85653 **
85654 ** With the [...] and [^...] matching, a ']' character can be included
85655 ** in the list by making it the first character after '[' or '^'.  A
85656 ** range of characters can be specified using '-'.  Example:
85657 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
85658 ** it the last character in the list.
85659 **
85660 ** This routine is usually quick, but can be N**2 in the worst case.
85661 **
85662 ** Hints: to match '*' or '?', put them in "[]".  Like this:
85663 **
85664 **         abc[*]xyz        Matches "abc*xyz" only
85665 */
85666 static int patternCompare(
85667   const u8 *zPattern,              /* The glob pattern */
85668   const u8 *zString,               /* The string to compare against the glob */
85669   const struct compareInfo *pInfo, /* Information about how to do the compare */
85670   u32 esc                          /* The escape character */
85671 ){
85672   u32 c, c2;
85673   int invert;
85674   int seen;
85675   u8 matchOne = pInfo->matchOne;
85676   u8 matchAll = pInfo->matchAll;
85677   u8 matchSet = pInfo->matchSet;
85678   u8 noCase = pInfo->noCase; 
85679   int prevEscape = 0;     /* True if the previous character was 'escape' */
85680
85681   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
85682     if( !prevEscape && c==matchAll ){
85683       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
85684                || c == matchOne ){
85685         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
85686           return 0;
85687         }
85688       }
85689       if( c==0 ){
85690         return 1;
85691       }else if( c==esc ){
85692         c = sqlite3Utf8Read(zPattern, &zPattern);
85693         if( c==0 ){
85694           return 0;
85695         }
85696       }else if( c==matchSet ){
85697         assert( esc==0 );         /* This is GLOB, not LIKE */
85698         assert( matchSet<0x80 );  /* '[' is a single-byte character */
85699         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
85700           SQLITE_SKIP_UTF8(zString);
85701         }
85702         return *zString!=0;
85703       }
85704       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
85705         if( noCase ){
85706           GlogUpperToLower(c2);
85707           GlogUpperToLower(c);
85708           while( c2 != 0 && c2 != c ){
85709             c2 = sqlite3Utf8Read(zString, &zString);
85710             GlogUpperToLower(c2);
85711           }
85712         }else{
85713           while( c2 != 0 && c2 != c ){
85714             c2 = sqlite3Utf8Read(zString, &zString);
85715           }
85716         }
85717         if( c2==0 ) return 0;
85718         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
85719       }
85720       return 0;
85721     }else if( !prevEscape && c==matchOne ){
85722       if( sqlite3Utf8Read(zString, &zString)==0 ){
85723         return 0;
85724       }
85725     }else if( c==matchSet ){
85726       u32 prior_c = 0;
85727       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
85728       seen = 0;
85729       invert = 0;
85730       c = sqlite3Utf8Read(zString, &zString);
85731       if( c==0 ) return 0;
85732       c2 = sqlite3Utf8Read(zPattern, &zPattern);
85733       if( c2=='^' ){
85734         invert = 1;
85735         c2 = sqlite3Utf8Read(zPattern, &zPattern);
85736       }
85737       if( c2==']' ){
85738         if( c==']' ) seen = 1;
85739         c2 = sqlite3Utf8Read(zPattern, &zPattern);
85740       }
85741       while( c2 && c2!=']' ){
85742         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
85743           c2 = sqlite3Utf8Read(zPattern, &zPattern);
85744           if( c>=prior_c && c<=c2 ) seen = 1;
85745           prior_c = 0;
85746         }else{
85747           if( c==c2 ){
85748             seen = 1;
85749           }
85750           prior_c = c2;
85751         }
85752         c2 = sqlite3Utf8Read(zPattern, &zPattern);
85753       }
85754       if( c2==0 || (seen ^ invert)==0 ){
85755         return 0;
85756       }
85757     }else if( esc==c && !prevEscape ){
85758       prevEscape = 1;
85759     }else{
85760       c2 = sqlite3Utf8Read(zString, &zString);
85761       if( noCase ){
85762         GlogUpperToLower(c);
85763         GlogUpperToLower(c2);
85764       }
85765       if( c!=c2 ){
85766         return 0;
85767       }
85768       prevEscape = 0;
85769     }
85770   }
85771   return *zString==0;
85772 }
85773
85774 /*
85775 ** Count the number of times that the LIKE operator (or GLOB which is
85776 ** just a variation of LIKE) gets called.  This is used for testing
85777 ** only.
85778 */
85779 #ifdef SQLITE_TEST
85780 SQLITE_API int sqlite3_like_count = 0;
85781 #endif
85782
85783
85784 /*
85785 ** Implementation of the like() SQL function.  This function implements
85786 ** the build-in LIKE operator.  The first argument to the function is the
85787 ** pattern and the second argument is the string.  So, the SQL statements:
85788 **
85789 **       A LIKE B
85790 **
85791 ** is implemented as like(B,A).
85792 **
85793 ** This same function (with a different compareInfo structure) computes
85794 ** the GLOB operator.
85795 */
85796 static void likeFunc(
85797   sqlite3_context *context, 
85798   int argc, 
85799   sqlite3_value **argv
85800 ){
85801   const unsigned char *zA, *zB;
85802   u32 escape = 0;
85803   int nPat;
85804   sqlite3 *db = sqlite3_context_db_handle(context);
85805
85806   zB = sqlite3_value_text(argv[0]);
85807   zA = sqlite3_value_text(argv[1]);
85808
85809   /* Limit the length of the LIKE or GLOB pattern to avoid problems
85810   ** of deep recursion and N*N behavior in patternCompare().
85811   */
85812   nPat = sqlite3_value_bytes(argv[0]);
85813   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
85814   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
85815   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
85816     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
85817     return;
85818   }
85819   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
85820
85821   if( argc==3 ){
85822     /* The escape character string must consist of a single UTF-8 character.
85823     ** Otherwise, return an error.
85824     */
85825     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
85826     if( zEsc==0 ) return;
85827     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
85828       sqlite3_result_error(context, 
85829           "ESCAPE expression must be a single character", -1);
85830       return;
85831     }
85832     escape = sqlite3Utf8Read(zEsc, &zEsc);
85833   }
85834   if( zA && zB ){
85835     struct compareInfo *pInfo = sqlite3_user_data(context);
85836 #ifdef SQLITE_TEST
85837     sqlite3_like_count++;
85838 #endif
85839     
85840     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
85841   }
85842 }
85843
85844 /*
85845 ** Implementation of the NULLIF(x,y) function.  The result is the first
85846 ** argument if the arguments are different.  The result is NULL if the
85847 ** arguments are equal to each other.
85848 */
85849 static void nullifFunc(
85850   sqlite3_context *context,
85851   int NotUsed,
85852   sqlite3_value **argv
85853 ){
85854   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
85855   UNUSED_PARAMETER(NotUsed);
85856   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
85857     sqlite3_result_value(context, argv[0]);
85858   }
85859 }
85860
85861 /*
85862 ** Implementation of the sqlite_version() function.  The result is the version
85863 ** of the SQLite library that is running.
85864 */
85865 static void versionFunc(
85866   sqlite3_context *context,
85867   int NotUsed,
85868   sqlite3_value **NotUsed2
85869 ){
85870   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85871   /* IMP: R-48699-48617 This function is an SQL wrapper around the
85872   ** sqlite3_libversion() C-interface. */
85873   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
85874 }
85875
85876 /*
85877 ** Implementation of the sqlite_source_id() function. The result is a string
85878 ** that identifies the particular version of the source code used to build
85879 ** SQLite.
85880 */
85881 static void sourceidFunc(
85882   sqlite3_context *context,
85883   int NotUsed,
85884   sqlite3_value **NotUsed2
85885 ){
85886   UNUSED_PARAMETER2(NotUsed, NotUsed2);
85887   /* IMP: R-24470-31136 This function is an SQL wrapper around the
85888   ** sqlite3_sourceid() C interface. */
85889   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
85890 }
85891
85892 /*
85893 ** Implementation of the sqlite_log() function.  This is a wrapper around
85894 ** sqlite3_log().  The return value is NULL.  The function exists purely for
85895 ** its side-effects.
85896 */
85897 static void errlogFunc(
85898   sqlite3_context *context,
85899   int argc,
85900   sqlite3_value **argv
85901 ){
85902   UNUSED_PARAMETER(argc);
85903   UNUSED_PARAMETER(context);
85904   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
85905 }
85906
85907 /*
85908 ** Implementation of the sqlite_compileoption_used() function.
85909 ** The result is an integer that identifies if the compiler option
85910 ** was used to build SQLite.
85911 */
85912 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85913 static void compileoptionusedFunc(
85914   sqlite3_context *context,
85915   int argc,
85916   sqlite3_value **argv
85917 ){
85918   const char *zOptName;
85919   assert( argc==1 );
85920   UNUSED_PARAMETER(argc);
85921   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
85922   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
85923   ** function.
85924   */
85925   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
85926     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
85927   }
85928 }
85929 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85930
85931 /*
85932 ** Implementation of the sqlite_compileoption_get() function. 
85933 ** The result is a string that identifies the compiler options 
85934 ** used to build SQLite.
85935 */
85936 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85937 static void compileoptiongetFunc(
85938   sqlite3_context *context,
85939   int argc,
85940   sqlite3_value **argv
85941 ){
85942   int n;
85943   assert( argc==1 );
85944   UNUSED_PARAMETER(argc);
85945   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
85946   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
85947   */
85948   n = sqlite3_value_int(argv[0]);
85949   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
85950 }
85951 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85952
85953 /* Array for converting from half-bytes (nybbles) into ASCII hex
85954 ** digits. */
85955 static const char hexdigits[] = {
85956   '0', '1', '2', '3', '4', '5', '6', '7',
85957   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
85958 };
85959
85960 /*
85961 ** EXPERIMENTAL - This is not an official function.  The interface may
85962 ** change.  This function may disappear.  Do not write code that depends
85963 ** on this function.
85964 **
85965 ** Implementation of the QUOTE() function.  This function takes a single
85966 ** argument.  If the argument is numeric, the return value is the same as
85967 ** the argument.  If the argument is NULL, the return value is the string
85968 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
85969 ** single-quote escapes.
85970 */
85971 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85972   assert( argc==1 );
85973   UNUSED_PARAMETER(argc);
85974   switch( sqlite3_value_type(argv[0]) ){
85975     case SQLITE_FLOAT: {
85976       double r1, r2;
85977       char zBuf[50];
85978       r1 = sqlite3_value_double(argv[0]);
85979       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
85980       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
85981       if( r1!=r2 ){
85982         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
85983       }
85984       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
85985       break;
85986     }
85987     case SQLITE_INTEGER: {
85988       sqlite3_result_value(context, argv[0]);
85989       break;
85990     }
85991     case SQLITE_BLOB: {
85992       char *zText = 0;
85993       char const *zBlob = sqlite3_value_blob(argv[0]);
85994       int nBlob = sqlite3_value_bytes(argv[0]);
85995       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
85996       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
85997       if( zText ){
85998         int i;
85999         for(i=0; i<nBlob; i++){
86000           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86001           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86002         }
86003         zText[(nBlob*2)+2] = '\'';
86004         zText[(nBlob*2)+3] = '\0';
86005         zText[0] = 'X';
86006         zText[1] = '\'';
86007         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
86008         sqlite3_free(zText);
86009       }
86010       break;
86011     }
86012     case SQLITE_TEXT: {
86013       int i,j;
86014       u64 n;
86015       const unsigned char *zArg = sqlite3_value_text(argv[0]);
86016       char *z;
86017
86018       if( zArg==0 ) return;
86019       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86020       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86021       if( z ){
86022         z[0] = '\'';
86023         for(i=0, j=1; zArg[i]; i++){
86024           z[j++] = zArg[i];
86025           if( zArg[i]=='\'' ){
86026             z[j++] = '\'';
86027           }
86028         }
86029         z[j++] = '\'';
86030         z[j] = 0;
86031         sqlite3_result_text(context, z, j, sqlite3_free);
86032       }
86033       break;
86034     }
86035     default: {
86036       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
86037       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
86038       break;
86039     }
86040   }
86041 }
86042
86043 /*
86044 ** The hex() function.  Interpret the argument as a blob.  Return
86045 ** a hexadecimal rendering as text.
86046 */
86047 static void hexFunc(
86048   sqlite3_context *context,
86049   int argc,
86050   sqlite3_value **argv
86051 ){
86052   int i, n;
86053   const unsigned char *pBlob;
86054   char *zHex, *z;
86055   assert( argc==1 );
86056   UNUSED_PARAMETER(argc);
86057   pBlob = sqlite3_value_blob(argv[0]);
86058   n = sqlite3_value_bytes(argv[0]);
86059   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
86060   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86061   if( zHex ){
86062     for(i=0; i<n; i++, pBlob++){
86063       unsigned char c = *pBlob;
86064       *(z++) = hexdigits[(c>>4)&0xf];
86065       *(z++) = hexdigits[c&0xf];
86066     }
86067     *z = 0;
86068     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
86069   }
86070 }
86071
86072 /*
86073 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86074 */
86075 static void zeroblobFunc(
86076   sqlite3_context *context,
86077   int argc,
86078   sqlite3_value **argv
86079 ){
86080   i64 n;
86081   sqlite3 *db = sqlite3_context_db_handle(context);
86082   assert( argc==1 );
86083   UNUSED_PARAMETER(argc);
86084   n = sqlite3_value_int64(argv[0]);
86085   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
86086   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86087   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86088     sqlite3_result_error_toobig(context);
86089   }else{
86090     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86091   }
86092 }
86093
86094 /*
86095 ** The replace() function.  Three arguments are all strings: call
86096 ** them A, B, and C. The result is also a string which is derived
86097 ** from A by replacing every occurance of B with C.  The match
86098 ** must be exact.  Collating sequences are not used.
86099 */
86100 static void replaceFunc(
86101   sqlite3_context *context,
86102   int argc,
86103   sqlite3_value **argv
86104 ){
86105   const unsigned char *zStr;        /* The input string A */
86106   const unsigned char *zPattern;    /* The pattern string B */
86107   const unsigned char *zRep;        /* The replacement string C */
86108   unsigned char *zOut;              /* The output */
86109   int nStr;                /* Size of zStr */
86110   int nPattern;            /* Size of zPattern */
86111   int nRep;                /* Size of zRep */
86112   i64 nOut;                /* Maximum size of zOut */
86113   int loopLimit;           /* Last zStr[] that might match zPattern[] */
86114   int i, j;                /* Loop counters */
86115
86116   assert( argc==3 );
86117   UNUSED_PARAMETER(argc);
86118   zStr = sqlite3_value_text(argv[0]);
86119   if( zStr==0 ) return;
86120   nStr = sqlite3_value_bytes(argv[0]);
86121   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
86122   zPattern = sqlite3_value_text(argv[1]);
86123   if( zPattern==0 ){
86124     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
86125             || sqlite3_context_db_handle(context)->mallocFailed );
86126     return;
86127   }
86128   if( zPattern[0]==0 ){
86129     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
86130     sqlite3_result_value(context, argv[0]);
86131     return;
86132   }
86133   nPattern = sqlite3_value_bytes(argv[1]);
86134   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
86135   zRep = sqlite3_value_text(argv[2]);
86136   if( zRep==0 ) return;
86137   nRep = sqlite3_value_bytes(argv[2]);
86138   assert( zRep==sqlite3_value_text(argv[2]) );
86139   nOut = nStr + 1;
86140   assert( nOut<SQLITE_MAX_LENGTH );
86141   zOut = contextMalloc(context, (i64)nOut);
86142   if( zOut==0 ){
86143     return;
86144   }
86145   loopLimit = nStr - nPattern;  
86146   for(i=j=0; i<=loopLimit; i++){
86147     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
86148       zOut[j++] = zStr[i];
86149     }else{
86150       u8 *zOld;
86151       sqlite3 *db = sqlite3_context_db_handle(context);
86152       nOut += nRep - nPattern;
86153       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
86154       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
86155       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86156         sqlite3_result_error_toobig(context);
86157         sqlite3_free(zOut);
86158         return;
86159       }
86160       zOld = zOut;
86161       zOut = sqlite3_realloc(zOut, (int)nOut);
86162       if( zOut==0 ){
86163         sqlite3_result_error_nomem(context);
86164         sqlite3_free(zOld);
86165         return;
86166       }
86167       memcpy(&zOut[j], zRep, nRep);
86168       j += nRep;
86169       i += nPattern-1;
86170     }
86171   }
86172   assert( j+nStr-i+1==nOut );
86173   memcpy(&zOut[j], &zStr[i], nStr-i);
86174   j += nStr - i;
86175   assert( j<=nOut );
86176   zOut[j] = 0;
86177   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
86178 }
86179
86180 /*
86181 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
86182 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
86183 */
86184 static void trimFunc(
86185   sqlite3_context *context,
86186   int argc,
86187   sqlite3_value **argv
86188 ){
86189   const unsigned char *zIn;         /* Input string */
86190   const unsigned char *zCharSet;    /* Set of characters to trim */
86191   int nIn;                          /* Number of bytes in input */
86192   int flags;                        /* 1: trimleft  2: trimright  3: trim */
86193   int i;                            /* Loop counter */
86194   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
86195   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
86196   int nChar;                        /* Number of characters in zCharSet */
86197
86198   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
86199     return;
86200   }
86201   zIn = sqlite3_value_text(argv[0]);
86202   if( zIn==0 ) return;
86203   nIn = sqlite3_value_bytes(argv[0]);
86204   assert( zIn==sqlite3_value_text(argv[0]) );
86205   if( argc==1 ){
86206     static const unsigned char lenOne[] = { 1 };
86207     static unsigned char * const azOne[] = { (u8*)" " };
86208     nChar = 1;
86209     aLen = (u8*)lenOne;
86210     azChar = (unsigned char **)azOne;
86211     zCharSet = 0;
86212   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
86213     return;
86214   }else{
86215     const unsigned char *z;
86216     for(z=zCharSet, nChar=0; *z; nChar++){
86217       SQLITE_SKIP_UTF8(z);
86218     }
86219     if( nChar>0 ){
86220       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
86221       if( azChar==0 ){
86222         return;
86223       }
86224       aLen = (unsigned char*)&azChar[nChar];
86225       for(z=zCharSet, nChar=0; *z; nChar++){
86226         azChar[nChar] = (unsigned char *)z;
86227         SQLITE_SKIP_UTF8(z);
86228         aLen[nChar] = (u8)(z - azChar[nChar]);
86229       }
86230     }
86231   }
86232   if( nChar>0 ){
86233     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
86234     if( flags & 1 ){
86235       while( nIn>0 ){
86236         int len = 0;
86237         for(i=0; i<nChar; i++){
86238           len = aLen[i];
86239           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
86240         }
86241         if( i>=nChar ) break;
86242         zIn += len;
86243         nIn -= len;
86244       }
86245     }
86246     if( flags & 2 ){
86247       while( nIn>0 ){
86248         int len = 0;
86249         for(i=0; i<nChar; i++){
86250           len = aLen[i];
86251           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
86252         }
86253         if( i>=nChar ) break;
86254         nIn -= len;
86255       }
86256     }
86257     if( zCharSet ){
86258       sqlite3_free(azChar);
86259     }
86260   }
86261   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
86262 }
86263
86264
86265 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
86266 ** is only available if the SQLITE_SOUNDEX compile-time option is used
86267 ** when SQLite is built.
86268 */
86269 #ifdef SQLITE_SOUNDEX
86270 /*
86271 ** Compute the soundex encoding of a word.
86272 **
86273 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
86274 ** soundex encoding of the string X. 
86275 */
86276 static void soundexFunc(
86277   sqlite3_context *context,
86278   int argc,
86279   sqlite3_value **argv
86280 ){
86281   char zResult[8];
86282   const u8 *zIn;
86283   int i, j;
86284   static const unsigned char iCode[] = {
86285     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86286     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86287     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86288     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86289     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86290     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86291     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86292     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86293   };
86294   assert( argc==1 );
86295   zIn = (u8*)sqlite3_value_text(argv[0]);
86296   if( zIn==0 ) zIn = (u8*)"";
86297   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
86298   if( zIn[i] ){
86299     u8 prevcode = iCode[zIn[i]&0x7f];
86300     zResult[0] = sqlite3Toupper(zIn[i]);
86301     for(j=1; j<4 && zIn[i]; i++){
86302       int code = iCode[zIn[i]&0x7f];
86303       if( code>0 ){
86304         if( code!=prevcode ){
86305           prevcode = code;
86306           zResult[j++] = code + '0';
86307         }
86308       }else{
86309         prevcode = 0;
86310       }
86311     }
86312     while( j<4 ){
86313       zResult[j++] = '0';
86314     }
86315     zResult[j] = 0;
86316     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
86317   }else{
86318     /* IMP: R-64894-50321 The string "?000" is returned if the argument
86319     ** is NULL or contains no ASCII alphabetic characters. */
86320     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
86321   }
86322 }
86323 #endif /* SQLITE_SOUNDEX */
86324
86325 #ifndef SQLITE_OMIT_LOAD_EXTENSION
86326 /*
86327 ** A function that loads a shared-library extension then returns NULL.
86328 */
86329 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
86330   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
86331   const char *zProc;
86332   sqlite3 *db = sqlite3_context_db_handle(context);
86333   char *zErrMsg = 0;
86334
86335   if( argc==2 ){
86336     zProc = (const char *)sqlite3_value_text(argv[1]);
86337   }else{
86338     zProc = 0;
86339   }
86340   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
86341     sqlite3_result_error(context, zErrMsg, -1);
86342     sqlite3_free(zErrMsg);
86343   }
86344 }
86345 #endif
86346
86347
86348 /*
86349 ** An instance of the following structure holds the context of a
86350 ** sum() or avg() aggregate computation.
86351 */
86352 typedef struct SumCtx SumCtx;
86353 struct SumCtx {
86354   double rSum;      /* Floating point sum */
86355   i64 iSum;         /* Integer sum */   
86356   i64 cnt;          /* Number of elements summed */
86357   u8 overflow;      /* True if integer overflow seen */
86358   u8 approx;        /* True if non-integer value was input to the sum */
86359 };
86360
86361 /*
86362 ** Routines used to compute the sum, average, and total.
86363 **
86364 ** The SUM() function follows the (broken) SQL standard which means
86365 ** that it returns NULL if it sums over no inputs.  TOTAL returns
86366 ** 0.0 in that case.  In addition, TOTAL always returns a float where
86367 ** SUM might return an integer if it never encounters a floating point
86368 ** value.  TOTAL never fails, but SUM might through an exception if
86369 ** it overflows an integer.
86370 */
86371 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
86372   SumCtx *p;
86373   int type;
86374   assert( argc==1 );
86375   UNUSED_PARAMETER(argc);
86376   p = sqlite3_aggregate_context(context, sizeof(*p));
86377   type = sqlite3_value_numeric_type(argv[0]);
86378   if( p && type!=SQLITE_NULL ){
86379     p->cnt++;
86380     if( type==SQLITE_INTEGER ){
86381       i64 v = sqlite3_value_int64(argv[0]);
86382       p->rSum += v;
86383       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
86384         p->overflow = 1;
86385       }
86386     }else{
86387       p->rSum += sqlite3_value_double(argv[0]);
86388       p->approx = 1;
86389     }
86390   }
86391 }
86392 static void sumFinalize(sqlite3_context *context){
86393   SumCtx *p;
86394   p = sqlite3_aggregate_context(context, 0);
86395   if( p && p->cnt>0 ){
86396     if( p->overflow ){
86397       sqlite3_result_error(context,"integer overflow",-1);
86398     }else if( p->approx ){
86399       sqlite3_result_double(context, p->rSum);
86400     }else{
86401       sqlite3_result_int64(context, p->iSum);
86402     }
86403   }
86404 }
86405 static void avgFinalize(sqlite3_context *context){
86406   SumCtx *p;
86407   p = sqlite3_aggregate_context(context, 0);
86408   if( p && p->cnt>0 ){
86409     sqlite3_result_double(context, p->rSum/(double)p->cnt);
86410   }
86411 }
86412 static void totalFinalize(sqlite3_context *context){
86413   SumCtx *p;
86414   p = sqlite3_aggregate_context(context, 0);
86415   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
86416   sqlite3_result_double(context, p ? p->rSum : (double)0);
86417 }
86418
86419 /*
86420 ** The following structure keeps track of state information for the
86421 ** count() aggregate function.
86422 */
86423 typedef struct CountCtx CountCtx;
86424 struct CountCtx {
86425   i64 n;
86426 };
86427
86428 /*
86429 ** Routines to implement the count() aggregate function.
86430 */
86431 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
86432   CountCtx *p;
86433   p = sqlite3_aggregate_context(context, sizeof(*p));
86434   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
86435     p->n++;
86436   }
86437
86438 #ifndef SQLITE_OMIT_DEPRECATED
86439   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
86440   ** sure it still operates correctly, verify that its count agrees with our 
86441   ** internal count when using count(*) and when the total count can be
86442   ** expressed as a 32-bit integer. */
86443   assert( argc==1 || p==0 || p->n>0x7fffffff
86444           || p->n==sqlite3_aggregate_count(context) );
86445 #endif
86446 }   
86447 static void countFinalize(sqlite3_context *context){
86448   CountCtx *p;
86449   p = sqlite3_aggregate_context(context, 0);
86450   sqlite3_result_int64(context, p ? p->n : 0);
86451 }
86452
86453 /*
86454 ** Routines to implement min() and max() aggregate functions.
86455 */
86456 static void minmaxStep(
86457   sqlite3_context *context, 
86458   int NotUsed, 
86459   sqlite3_value **argv
86460 ){
86461   Mem *pArg  = (Mem *)argv[0];
86462   Mem *pBest;
86463   UNUSED_PARAMETER(NotUsed);
86464
86465   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
86466   if( !pBest ) return;
86467
86468   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
86469     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
86470   }else if( pBest->flags ){
86471     int max;
86472     int cmp;
86473     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86474     /* This step function is used for both the min() and max() aggregates,
86475     ** the only difference between the two being that the sense of the
86476     ** comparison is inverted. For the max() aggregate, the
86477     ** sqlite3_user_data() function returns (void *)-1. For min() it
86478     ** returns (void *)db, where db is the sqlite3* database pointer.
86479     ** Therefore the next statement sets variable 'max' to 1 for the max()
86480     ** aggregate, or 0 for min().
86481     */
86482     max = sqlite3_user_data(context)!=0;
86483     cmp = sqlite3MemCompare(pBest, pArg, pColl);
86484     if( (max && cmp<0) || (!max && cmp>0) ){
86485       sqlite3VdbeMemCopy(pBest, pArg);
86486     }else{
86487       sqlite3SkipAccumulatorLoad(context);
86488     }
86489   }else{
86490     sqlite3VdbeMemCopy(pBest, pArg);
86491   }
86492 }
86493 static void minMaxFinalize(sqlite3_context *context){
86494   sqlite3_value *pRes;
86495   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
86496   if( pRes ){
86497     if( pRes->flags ){
86498       sqlite3_result_value(context, pRes);
86499     }
86500     sqlite3VdbeMemRelease(pRes);
86501   }
86502 }
86503
86504 /*
86505 ** group_concat(EXPR, ?SEPARATOR?)
86506 */
86507 static void groupConcatStep(
86508   sqlite3_context *context,
86509   int argc,
86510   sqlite3_value **argv
86511 ){
86512   const char *zVal;
86513   StrAccum *pAccum;
86514   const char *zSep;
86515   int nVal, nSep;
86516   assert( argc==1 || argc==2 );
86517   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86518   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
86519
86520   if( pAccum ){
86521     sqlite3 *db = sqlite3_context_db_handle(context);
86522     int firstTerm = pAccum->useMalloc==0;
86523     pAccum->useMalloc = 2;
86524     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
86525     if( !firstTerm ){
86526       if( argc==2 ){
86527         zSep = (char*)sqlite3_value_text(argv[1]);
86528         nSep = sqlite3_value_bytes(argv[1]);
86529       }else{
86530         zSep = ",";
86531         nSep = 1;
86532       }
86533       sqlite3StrAccumAppend(pAccum, zSep, nSep);
86534     }
86535     zVal = (char*)sqlite3_value_text(argv[0]);
86536     nVal = sqlite3_value_bytes(argv[0]);
86537     sqlite3StrAccumAppend(pAccum, zVal, nVal);
86538   }
86539 }
86540 static void groupConcatFinalize(sqlite3_context *context){
86541   StrAccum *pAccum;
86542   pAccum = sqlite3_aggregate_context(context, 0);
86543   if( pAccum ){
86544     if( pAccum->tooBig ){
86545       sqlite3_result_error_toobig(context);
86546     }else if( pAccum->mallocFailed ){
86547       sqlite3_result_error_nomem(context);
86548     }else{    
86549       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
86550                           sqlite3_free);
86551     }
86552   }
86553 }
86554
86555 /*
86556 ** This routine does per-connection function registration.  Most
86557 ** of the built-in functions above are part of the global function set.
86558 ** This routine only deals with those that are not global.
86559 */
86560 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
86561   int rc = sqlite3_overload_function(db, "MATCH", 2);
86562   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
86563   if( rc==SQLITE_NOMEM ){
86564     db->mallocFailed = 1;
86565   }
86566 }
86567
86568 /*
86569 ** Set the LIKEOPT flag on the 2-argument function with the given name.
86570 */
86571 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
86572   FuncDef *pDef;
86573   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
86574                              2, SQLITE_UTF8, 0);
86575   if( ALWAYS(pDef) ){
86576     pDef->flags = flagVal;
86577   }
86578 }
86579
86580 /*
86581 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
86582 ** parameter determines whether or not the LIKE operator is case
86583 ** sensitive.  GLOB is always case sensitive.
86584 */
86585 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
86586   struct compareInfo *pInfo;
86587   if( caseSensitive ){
86588     pInfo = (struct compareInfo*)&likeInfoAlt;
86589   }else{
86590     pInfo = (struct compareInfo*)&likeInfoNorm;
86591   }
86592   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
86593   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
86594   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
86595       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
86596   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
86597   setLikeOptFlag(db, "like", 
86598       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
86599 }
86600
86601 /*
86602 ** pExpr points to an expression which implements a function.  If
86603 ** it is appropriate to apply the LIKE optimization to that function
86604 ** then set aWc[0] through aWc[2] to the wildcard characters and
86605 ** return TRUE.  If the function is not a LIKE-style function then
86606 ** return FALSE.
86607 */
86608 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
86609   FuncDef *pDef;
86610   if( pExpr->op!=TK_FUNCTION 
86611    || !pExpr->x.pList 
86612    || pExpr->x.pList->nExpr!=2
86613   ){
86614     return 0;
86615   }
86616   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
86617   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
86618                              sqlite3Strlen30(pExpr->u.zToken),
86619                              2, SQLITE_UTF8, 0);
86620   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
86621     return 0;
86622   }
86623
86624   /* The memcpy() statement assumes that the wildcard characters are
86625   ** the first three statements in the compareInfo structure.  The
86626   ** asserts() that follow verify that assumption
86627   */
86628   memcpy(aWc, pDef->pUserData, 3);
86629   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
86630   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
86631   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
86632   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
86633   return 1;
86634 }
86635
86636 /*
86637 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
86638 ** to the global function hash table.  This occurs at start-time (as
86639 ** a consequence of calling sqlite3_initialize()).
86640 **
86641 ** After this routine runs
86642 */
86643 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
86644   /*
86645   ** The following array holds FuncDef structures for all of the functions
86646   ** defined in this file.
86647   **
86648   ** The array cannot be constant since changes are made to the
86649   ** FuncDef.pHash elements at start-time.  The elements of this array
86650   ** are read-only after initialization is complete.
86651   */
86652   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
86653     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
86654     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
86655     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
86656     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
86657     FUNCTION(trim,               1, 3, 0, trimFunc         ),
86658     FUNCTION(trim,               2, 3, 0, trimFunc         ),
86659     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
86660     FUNCTION(min,                0, 0, 1, 0                ),
86661     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
86662     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
86663     FUNCTION(max,                0, 1, 1, 0                ),
86664     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
86665     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
86666     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
86667     FUNCTION(substr,             2, 0, 0, substrFunc       ),
86668     FUNCTION(substr,             3, 0, 0, substrFunc       ),
86669     FUNCTION(abs,                1, 0, 0, absFunc          ),
86670 #ifndef SQLITE_OMIT_FLOATING_POINT
86671     FUNCTION(round,              1, 0, 0, roundFunc        ),
86672     FUNCTION(round,              2, 0, 0, roundFunc        ),
86673 #endif
86674     FUNCTION(upper,              1, 0, 0, upperFunc        ),
86675     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
86676     FUNCTION(coalesce,           1, 0, 0, 0                ),
86677     FUNCTION(coalesce,           0, 0, 0, 0                ),
86678     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
86679     FUNCTION(hex,                1, 0, 0, hexFunc          ),
86680     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
86681     FUNCTION(random,             0, 0, 0, randomFunc       ),
86682     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
86683     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
86684     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
86685     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
86686     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
86687 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86688     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
86689     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
86690 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86691     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
86692     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
86693     FUNCTION(changes,            0, 0, 0, changes          ),
86694     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
86695     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
86696     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
86697   #ifdef SQLITE_SOUNDEX
86698     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
86699   #endif
86700   #ifndef SQLITE_OMIT_LOAD_EXTENSION
86701     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
86702     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
86703   #endif
86704     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
86705     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
86706     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
86707  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
86708     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
86709     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
86710     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
86711     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
86712   
86713     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
86714   #ifdef SQLITE_CASE_SENSITIVE_LIKE
86715     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
86716     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
86717   #else
86718     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
86719     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
86720   #endif
86721   };
86722
86723   int i;
86724   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86725   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
86726
86727   for(i=0; i<ArraySize(aBuiltinFunc); i++){
86728     sqlite3FuncDefInsert(pHash, &aFunc[i]);
86729   }
86730   sqlite3RegisterDateTimeFunctions();
86731 #ifndef SQLITE_OMIT_ALTERTABLE
86732   sqlite3AlterFunctions();
86733 #endif
86734 }
86735
86736 /************** End of func.c ************************************************/
86737 /************** Begin file fkey.c ********************************************/
86738 /*
86739 **
86740 ** The author disclaims copyright to this source code.  In place of
86741 ** a legal notice, here is a blessing:
86742 **
86743 **    May you do good and not evil.
86744 **    May you find forgiveness for yourself and forgive others.
86745 **    May you share freely, never taking more than you give.
86746 **
86747 *************************************************************************
86748 ** This file contains code used by the compiler to add foreign key
86749 ** support to compiled SQL statements.
86750 */
86751
86752 #ifndef SQLITE_OMIT_FOREIGN_KEY
86753 #ifndef SQLITE_OMIT_TRIGGER
86754
86755 /*
86756 ** Deferred and Immediate FKs
86757 ** --------------------------
86758 **
86759 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
86760 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
86761 ** is returned and the current statement transaction rolled back. If a 
86762 ** deferred foreign key constraint is violated, no action is taken 
86763 ** immediately. However if the application attempts to commit the 
86764 ** transaction before fixing the constraint violation, the attempt fails.
86765 **
86766 ** Deferred constraints are implemented using a simple counter associated
86767 ** with the database handle. The counter is set to zero each time a 
86768 ** database transaction is opened. Each time a statement is executed 
86769 ** that causes a foreign key violation, the counter is incremented. Each
86770 ** time a statement is executed that removes an existing violation from
86771 ** the database, the counter is decremented. When the transaction is
86772 ** committed, the commit fails if the current value of the counter is
86773 ** greater than zero. This scheme has two big drawbacks:
86774 **
86775 **   * When a commit fails due to a deferred foreign key constraint, 
86776 **     there is no way to tell which foreign constraint is not satisfied,
86777 **     or which row it is not satisfied for.
86778 **
86779 **   * If the database contains foreign key violations when the 
86780 **     transaction is opened, this may cause the mechanism to malfunction.
86781 **
86782 ** Despite these problems, this approach is adopted as it seems simpler
86783 ** than the alternatives.
86784 **
86785 ** INSERT operations:
86786 **
86787 **   I.1) For each FK for which the table is the child table, search
86788 **        the parent table for a match. If none is found increment the
86789 **        constraint counter.
86790 **
86791 **   I.2) For each FK for which the table is the parent table, 
86792 **        search the child table for rows that correspond to the new
86793 **        row in the parent table. Decrement the counter for each row
86794 **        found (as the constraint is now satisfied).
86795 **
86796 ** DELETE operations:
86797 **
86798 **   D.1) For each FK for which the table is the child table, 
86799 **        search the parent table for a row that corresponds to the 
86800 **        deleted row in the child table. If such a row is not found, 
86801 **        decrement the counter.
86802 **
86803 **   D.2) For each FK for which the table is the parent table, search 
86804 **        the child table for rows that correspond to the deleted row 
86805 **        in the parent table. For each found increment the counter.
86806 **
86807 ** UPDATE operations:
86808 **
86809 **   An UPDATE command requires that all 4 steps above are taken, but only
86810 **   for FK constraints for which the affected columns are actually 
86811 **   modified (values must be compared at runtime).
86812 **
86813 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
86814 ** This simplifies the implementation a bit.
86815 **
86816 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
86817 ** resolution is considered to delete rows before the new row is inserted.
86818 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
86819 ** is thrown, even if the FK constraint would be satisfied after the new 
86820 ** row is inserted.
86821 **
86822 ** Immediate constraints are usually handled similarly. The only difference 
86823 ** is that the counter used is stored as part of each individual statement
86824 ** object (struct Vdbe). If, after the statement has run, its immediate
86825 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
86826 ** and the statement transaction is rolled back. An exception is an INSERT
86827 ** statement that inserts a single row only (no triggers). In this case,
86828 ** instead of using a counter, an exception is thrown immediately if the
86829 ** INSERT violates a foreign key constraint. This is necessary as such
86830 ** an INSERT does not open a statement transaction.
86831 **
86832 ** TODO: How should dropping a table be handled? How should renaming a 
86833 ** table be handled?
86834 **
86835 **
86836 ** Query API Notes
86837 ** ---------------
86838 **
86839 ** Before coding an UPDATE or DELETE row operation, the code-generator
86840 ** for those two operations needs to know whether or not the operation
86841 ** requires any FK processing and, if so, which columns of the original
86842 ** row are required by the FK processing VDBE code (i.e. if FKs were
86843 ** implemented using triggers, which of the old.* columns would be 
86844 ** accessed). No information is required by the code-generator before
86845 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
86846 ** generation code to query for this information are:
86847 **
86848 **   sqlite3FkRequired() - Test to see if FK processing is required.
86849 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
86850 **
86851 **
86852 ** Externally accessible module functions
86853 ** --------------------------------------
86854 **
86855 **   sqlite3FkCheck()    - Check for foreign key violations.
86856 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
86857 **   sqlite3FkDelete()   - Delete an FKey structure.
86858 */
86859
86860 /*
86861 ** VDBE Calling Convention
86862 ** -----------------------
86863 **
86864 ** Example:
86865 **
86866 **   For the following INSERT statement:
86867 **
86868 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
86869 **     INSERT INTO t1 VALUES(1, 2, 3.1);
86870 **
86871 **   Register (x):        2    (type integer)
86872 **   Register (x+1):      1    (type integer)
86873 **   Register (x+2):      NULL (type NULL)
86874 **   Register (x+3):      3.1  (type real)
86875 */
86876
86877 /*
86878 ** A foreign key constraint requires that the key columns in the parent
86879 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
86880 ** Given that pParent is the parent table for foreign key constraint pFKey, 
86881 ** search the schema a unique index on the parent key columns. 
86882 **
86883 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
86884 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
86885 ** is set to point to the unique index. 
86886 ** 
86887 ** If the parent key consists of a single column (the foreign key constraint
86888 ** is not a composite foreign key), output variable *paiCol is set to NULL.
86889 ** Otherwise, it is set to point to an allocated array of size N, where
86890 ** N is the number of columns in the parent key. The first element of the
86891 ** array is the index of the child table column that is mapped by the FK
86892 ** constraint to the parent table column stored in the left-most column
86893 ** of index *ppIdx. The second element of the array is the index of the
86894 ** child table column that corresponds to the second left-most column of
86895 ** *ppIdx, and so on.
86896 **
86897 ** If the required index cannot be found, either because:
86898 **
86899 **   1) The named parent key columns do not exist, or
86900 **
86901 **   2) The named parent key columns do exist, but are not subject to a
86902 **      UNIQUE or PRIMARY KEY constraint, or
86903 **
86904 **   3) No parent key columns were provided explicitly as part of the
86905 **      foreign key definition, and the parent table does not have a
86906 **      PRIMARY KEY, or
86907 **
86908 **   4) No parent key columns were provided explicitly as part of the
86909 **      foreign key definition, and the PRIMARY KEY of the parent table 
86910 **      consists of a a different number of columns to the child key in 
86911 **      the child table.
86912 **
86913 ** then non-zero is returned, and a "foreign key mismatch" error loaded
86914 ** into pParse. If an OOM error occurs, non-zero is returned and the
86915 ** pParse->db->mallocFailed flag is set.
86916 */
86917 static int locateFkeyIndex(
86918   Parse *pParse,                  /* Parse context to store any error in */
86919   Table *pParent,                 /* Parent table of FK constraint pFKey */
86920   FKey *pFKey,                    /* Foreign key to find index for */
86921   Index **ppIdx,                  /* OUT: Unique index on parent table */
86922   int **paiCol                    /* OUT: Map of index columns in pFKey */
86923 ){
86924   Index *pIdx = 0;                    /* Value to return via *ppIdx */
86925   int *aiCol = 0;                     /* Value to return via *paiCol */
86926   int nCol = pFKey->nCol;             /* Number of columns in parent key */
86927   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
86928
86929   /* The caller is responsible for zeroing output parameters. */
86930   assert( ppIdx && *ppIdx==0 );
86931   assert( !paiCol || *paiCol==0 );
86932   assert( pParse );
86933
86934   /* If this is a non-composite (single column) foreign key, check if it 
86935   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
86936   ** and *paiCol set to zero and return early. 
86937   **
86938   ** Otherwise, for a composite foreign key (more than one column), allocate
86939   ** space for the aiCol array (returned via output parameter *paiCol).
86940   ** Non-composite foreign keys do not require the aiCol array.
86941   */
86942   if( nCol==1 ){
86943     /* The FK maps to the IPK if any of the following are true:
86944     **
86945     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
86946     **      mapped to the primary key of table pParent, or
86947     **   2) The FK is explicitly mapped to a column declared as INTEGER
86948     **      PRIMARY KEY.
86949     */
86950     if( pParent->iPKey>=0 ){
86951       if( !zKey ) return 0;
86952       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
86953     }
86954   }else if( paiCol ){
86955     assert( nCol>1 );
86956     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
86957     if( !aiCol ) return 1;
86958     *paiCol = aiCol;
86959   }
86960
86961   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
86962     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
86963       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
86964       ** of columns. If each indexed column corresponds to a foreign key
86965       ** column of pFKey, then this index is a winner.  */
86966
86967       if( zKey==0 ){
86968         /* If zKey is NULL, then this foreign key is implicitly mapped to 
86969         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
86970         ** identified by the test (Index.autoIndex==2).  */
86971         if( pIdx->autoIndex==2 ){
86972           if( aiCol ){
86973             int i;
86974             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
86975           }
86976           break;
86977         }
86978       }else{
86979         /* If zKey is non-NULL, then this foreign key was declared to
86980         ** map to an explicit list of columns in table pParent. Check if this
86981         ** index matches those columns. Also, check that the index uses
86982         ** the default collation sequences for each column. */
86983         int i, j;
86984         for(i=0; i<nCol; i++){
86985           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
86986           char *zDfltColl;                  /* Def. collation for column */
86987           char *zIdxCol;                    /* Name of indexed column */
86988
86989           /* If the index uses a collation sequence that is different from
86990           ** the default collation sequence for the column, this index is
86991           ** unusable. Bail out early in this case.  */
86992           zDfltColl = pParent->aCol[iCol].zColl;
86993           if( !zDfltColl ){
86994             zDfltColl = "BINARY";
86995           }
86996           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
86997
86998           zIdxCol = pParent->aCol[iCol].zName;
86999           for(j=0; j<nCol; j++){
87000             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87001               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87002               break;
87003             }
87004           }
87005           if( j==nCol ) break;
87006         }
87007         if( i==nCol ) break;      /* pIdx is usable */
87008       }
87009     }
87010   }
87011
87012   if( !pIdx ){
87013     if( !pParse->disableTriggers ){
87014       sqlite3ErrorMsg(pParse, "foreign key mismatch");
87015     }
87016     sqlite3DbFree(pParse->db, aiCol);
87017     return 1;
87018   }
87019
87020   *ppIdx = pIdx;
87021   return 0;
87022 }
87023
87024 /*
87025 ** This function is called when a row is inserted into or deleted from the 
87026 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
87027 ** on the child table of pFKey, this function is invoked twice for each row
87028 ** affected - once to "delete" the old row, and then again to "insert" the
87029 ** new row.
87030 **
87031 ** Each time it is called, this function generates VDBE code to locate the
87032 ** row in the parent table that corresponds to the row being inserted into 
87033 ** or deleted from the child table. If the parent row can be found, no 
87034 ** special action is taken. Otherwise, if the parent row can *not* be
87035 ** found in the parent table:
87036 **
87037 **   Operation | FK type   | Action taken
87038 **   --------------------------------------------------------------------------
87039 **   INSERT      immediate   Increment the "immediate constraint counter".
87040 **
87041 **   DELETE      immediate   Decrement the "immediate constraint counter".
87042 **
87043 **   INSERT      deferred    Increment the "deferred constraint counter".
87044 **
87045 **   DELETE      deferred    Decrement the "deferred constraint counter".
87046 **
87047 ** These operations are identified in the comment at the top of this file 
87048 ** (fkey.c) as "I.1" and "D.1".
87049 */
87050 static void fkLookupParent(
87051   Parse *pParse,        /* Parse context */
87052   int iDb,              /* Index of database housing pTab */
87053   Table *pTab,          /* Parent table of FK pFKey */
87054   Index *pIdx,          /* Unique index on parent key columns in pTab */
87055   FKey *pFKey,          /* Foreign key constraint */
87056   int *aiCol,           /* Map from parent key columns to child table columns */
87057   int regData,          /* Address of array containing child table row */
87058   int nIncr,            /* Increment constraint counter by this */
87059   int isIgnore          /* If true, pretend pTab contains all NULL values */
87060 ){
87061   int i;                                    /* Iterator variable */
87062   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
87063   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87064   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
87065
87066   /* If nIncr is less than zero, then check at runtime if there are any
87067   ** outstanding constraints to resolve. If there are not, there is no need
87068   ** to check if deleting this row resolves any outstanding violations.
87069   **
87070   ** Check if any of the key columns in the child table row are NULL. If 
87071   ** any are, then the constraint is considered satisfied. No need to 
87072   ** search for a matching row in the parent table.  */
87073   if( nIncr<0 ){
87074     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87075   }
87076   for(i=0; i<pFKey->nCol; i++){
87077     int iReg = aiCol[i] + regData + 1;
87078     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87079   }
87080
87081   if( isIgnore==0 ){
87082     if( pIdx==0 ){
87083       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87084       ** column of the parent table (table pTab).  */
87085       int iMustBeInt;               /* Address of MustBeInt instruction */
87086       int regTemp = sqlite3GetTempReg(pParse);
87087   
87088       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
87089       ** apply the affinity of the parent key). If this fails, then there
87090       ** is no matching parent key. Before using MustBeInt, make a copy of
87091       ** the value. Otherwise, the value inserted into the child key column
87092       ** will have INTEGER affinity applied to it, which may not be correct.  */
87093       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87094       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87095   
87096       /* If the parent table is the same as the child table, and we are about
87097       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87098       ** then check if the row being inserted matches itself. If so, do not
87099       ** increment the constraint-counter.  */
87100       if( pTab==pFKey->pFrom && nIncr==1 ){
87101         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
87102       }
87103   
87104       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
87105       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
87106       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
87107       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
87108       sqlite3VdbeJumpHere(v, iMustBeInt);
87109       sqlite3ReleaseTempReg(pParse, regTemp);
87110     }else{
87111       int nCol = pFKey->nCol;
87112       int regTemp = sqlite3GetTempRange(pParse, nCol);
87113       int regRec = sqlite3GetTempReg(pParse);
87114       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
87115   
87116       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
87117       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
87118       for(i=0; i<nCol; i++){
87119         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
87120       }
87121   
87122       /* If the parent table is the same as the child table, and we are about
87123       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87124       ** then check if the row being inserted matches itself. If so, do not
87125       ** increment the constraint-counter. 
87126       **
87127       ** If any of the parent-key values are NULL, then the row cannot match 
87128       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
87129       ** of the parent-key values are NULL (at this point it is known that
87130       ** none of the child key values are).
87131       */
87132       if( pTab==pFKey->pFrom && nIncr==1 ){
87133         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
87134         for(i=0; i<nCol; i++){
87135           int iChild = aiCol[i]+1+regData;
87136           int iParent = pIdx->aiColumn[i]+1+regData;
87137           assert( aiCol[i]!=pTab->iPKey );
87138           if( pIdx->aiColumn[i]==pTab->iPKey ){
87139             /* The parent key is a composite key that includes the IPK column */
87140             iParent = regData;
87141           }
87142           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
87143           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
87144         }
87145         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
87146       }
87147   
87148       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
87149       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
87150       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
87151   
87152       sqlite3ReleaseTempReg(pParse, regRec);
87153       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
87154     }
87155   }
87156
87157   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
87158     /* Special case: If this is an INSERT statement that will insert exactly
87159     ** one row into the table, raise a constraint immediately instead of
87160     ** incrementing a counter. This is necessary as the VM code is being
87161     ** generated for will not open a statement transaction.  */
87162     assert( nIncr==1 );
87163     sqlite3HaltConstraint(
87164         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
87165     );
87166   }else{
87167     if( nIncr>0 && pFKey->isDeferred==0 ){
87168       sqlite3ParseToplevel(pParse)->mayAbort = 1;
87169     }
87170     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87171   }
87172
87173   sqlite3VdbeResolveLabel(v, iOk);
87174   sqlite3VdbeAddOp1(v, OP_Close, iCur);
87175 }
87176
87177 /*
87178 ** This function is called to generate code executed when a row is deleted
87179 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
87180 ** deferred, when a row is inserted into the same table. When generating
87181 ** code for an SQL UPDATE operation, this function may be called twice -
87182 ** once to "delete" the old row and once to "insert" the new row.
87183 **
87184 ** The code generated by this function scans through the rows in the child
87185 ** table that correspond to the parent table row being deleted or inserted.
87186 ** For each child row found, one of the following actions is taken:
87187 **
87188 **   Operation | FK type   | Action taken
87189 **   --------------------------------------------------------------------------
87190 **   DELETE      immediate   Increment the "immediate constraint counter".
87191 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87192 **                           throw a "foreign key constraint failed" exception.
87193 **
87194 **   INSERT      immediate   Decrement the "immediate constraint counter".
87195 **
87196 **   DELETE      deferred    Increment the "deferred constraint counter".
87197 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87198 **                           throw a "foreign key constraint failed" exception.
87199 **
87200 **   INSERT      deferred    Decrement the "deferred constraint counter".
87201 **
87202 ** These operations are identified in the comment at the top of this file 
87203 ** (fkey.c) as "I.2" and "D.2".
87204 */
87205 static void fkScanChildren(
87206   Parse *pParse,                  /* Parse context */
87207   SrcList *pSrc,                  /* SrcList containing the table to scan */
87208   Table *pTab,
87209   Index *pIdx,                    /* Foreign key index */
87210   FKey *pFKey,                    /* Foreign key relationship */
87211   int *aiCol,                     /* Map from pIdx cols to child table cols */
87212   int regData,                    /* Referenced table data starts here */
87213   int nIncr                       /* Amount to increment deferred counter by */
87214 ){
87215   sqlite3 *db = pParse->db;       /* Database handle */
87216   int i;                          /* Iterator variable */
87217   Expr *pWhere = 0;               /* WHERE clause to scan with */
87218   NameContext sNameContext;       /* Context used to resolve WHERE clause */
87219   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
87220   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
87221   Vdbe *v = sqlite3GetVdbe(pParse);
87222
87223   assert( !pIdx || pIdx->pTable==pTab );
87224
87225   if( nIncr<0 ){
87226     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
87227   }
87228
87229   /* Create an Expr object representing an SQL expression like:
87230   **
87231   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
87232   **
87233   ** The collation sequence used for the comparison should be that of
87234   ** the parent key columns. The affinity of the parent key column should
87235   ** be applied to each child key value before the comparison takes place.
87236   */
87237   for(i=0; i<pFKey->nCol; i++){
87238     Expr *pLeft;                  /* Value from parent table row */
87239     Expr *pRight;                 /* Column ref to child table */
87240     Expr *pEq;                    /* Expression (pLeft = pRight) */
87241     int iCol;                     /* Index of column in child table */ 
87242     const char *zCol;             /* Name of column in child table */
87243
87244     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
87245     if( pLeft ){
87246       /* Set the collation sequence and affinity of the LHS of each TK_EQ
87247       ** expression to the parent key column defaults.  */
87248       if( pIdx ){
87249         Column *pCol;
87250         iCol = pIdx->aiColumn[i];
87251         pCol = &pTab->aCol[iCol];
87252         if( pTab->iPKey==iCol ) iCol = -1;
87253         pLeft->iTable = regData+iCol+1;
87254         pLeft->affinity = pCol->affinity;
87255         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
87256       }else{
87257         pLeft->iTable = regData;
87258         pLeft->affinity = SQLITE_AFF_INTEGER;
87259       }
87260     }
87261     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
87262     assert( iCol>=0 );
87263     zCol = pFKey->pFrom->aCol[iCol].zName;
87264     pRight = sqlite3Expr(db, TK_ID, zCol);
87265     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
87266     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87267   }
87268
87269   /* If the child table is the same as the parent table, and this scan
87270   ** is taking place as part of a DELETE operation (operation D.2), omit the
87271   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
87272   ** clause, where $rowid is the rowid of the row being deleted.  */
87273   if( pTab==pFKey->pFrom && nIncr>0 ){
87274     Expr *pEq;                    /* Expression (pLeft = pRight) */
87275     Expr *pLeft;                  /* Value from parent table row */
87276     Expr *pRight;                 /* Column ref to child table */
87277     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
87278     pRight = sqlite3Expr(db, TK_COLUMN, 0);
87279     if( pLeft && pRight ){
87280       pLeft->iTable = regData;
87281       pLeft->affinity = SQLITE_AFF_INTEGER;
87282       pRight->iTable = pSrc->a[0].iCursor;
87283       pRight->iColumn = -1;
87284     }
87285     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
87286     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87287   }
87288
87289   /* Resolve the references in the WHERE clause. */
87290   memset(&sNameContext, 0, sizeof(NameContext));
87291   sNameContext.pSrcList = pSrc;
87292   sNameContext.pParse = pParse;
87293   sqlite3ResolveExprNames(&sNameContext, pWhere);
87294
87295   /* Create VDBE to loop through the entries in pSrc that match the WHERE
87296   ** clause. If the constraint is not deferred, throw an exception for
87297   ** each row found. Otherwise, for deferred constraints, increment the
87298   ** deferred constraint counter by nIncr for each row selected.  */
87299   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
87300   if( nIncr>0 && pFKey->isDeferred==0 ){
87301     sqlite3ParseToplevel(pParse)->mayAbort = 1;
87302   }
87303   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87304   if( pWInfo ){
87305     sqlite3WhereEnd(pWInfo);
87306   }
87307
87308   /* Clean up the WHERE clause constructed above. */
87309   sqlite3ExprDelete(db, pWhere);
87310   if( iFkIfZero ){
87311     sqlite3VdbeJumpHere(v, iFkIfZero);
87312   }
87313 }
87314
87315 /*
87316 ** This function returns a pointer to the head of a linked list of FK
87317 ** constraints for which table pTab is the parent table. For example,
87318 ** given the following schema:
87319 **
87320 **   CREATE TABLE t1(a PRIMARY KEY);
87321 **   CREATE TABLE t2(b REFERENCES t1(a);
87322 **
87323 ** Calling this function with table "t1" as an argument returns a pointer
87324 ** to the FKey structure representing the foreign key constraint on table
87325 ** "t2". Calling this function with "t2" as the argument would return a
87326 ** NULL pointer (as there are no FK constraints for which t2 is the parent
87327 ** table).
87328 */
87329 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
87330   int nName = sqlite3Strlen30(pTab->zName);
87331   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
87332 }
87333
87334 /*
87335 ** The second argument is a Trigger structure allocated by the 
87336 ** fkActionTrigger() routine. This function deletes the Trigger structure
87337 ** and all of its sub-components.
87338 **
87339 ** The Trigger structure or any of its sub-components may be allocated from
87340 ** the lookaside buffer belonging to database handle dbMem.
87341 */
87342 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
87343   if( p ){
87344     TriggerStep *pStep = p->step_list;
87345     sqlite3ExprDelete(dbMem, pStep->pWhere);
87346     sqlite3ExprListDelete(dbMem, pStep->pExprList);
87347     sqlite3SelectDelete(dbMem, pStep->pSelect);
87348     sqlite3ExprDelete(dbMem, p->pWhen);
87349     sqlite3DbFree(dbMem, p);
87350   }
87351 }
87352
87353 /*
87354 ** This function is called to generate code that runs when table pTab is
87355 ** being dropped from the database. The SrcList passed as the second argument
87356 ** to this function contains a single entry guaranteed to resolve to
87357 ** table pTab.
87358 **
87359 ** Normally, no code is required. However, if either
87360 **
87361 **   (a) The table is the parent table of a FK constraint, or
87362 **   (b) The table is the child table of a deferred FK constraint and it is
87363 **       determined at runtime that there are outstanding deferred FK 
87364 **       constraint violations in the database,
87365 **
87366 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
87367 ** the table from the database. Triggers are disabled while running this
87368 ** DELETE, but foreign key actions are not.
87369 */
87370 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
87371   sqlite3 *db = pParse->db;
87372   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
87373     int iSkip = 0;
87374     Vdbe *v = sqlite3GetVdbe(pParse);
87375
87376     assert( v );                  /* VDBE has already been allocated */
87377     if( sqlite3FkReferences(pTab)==0 ){
87378       /* Search for a deferred foreign key constraint for which this table
87379       ** is the child table. If one cannot be found, return without 
87380       ** generating any VDBE code. If one can be found, then jump over
87381       ** the entire DELETE if there are no outstanding deferred constraints
87382       ** when this statement is run.  */
87383       FKey *p;
87384       for(p=pTab->pFKey; p; p=p->pNextFrom){
87385         if( p->isDeferred ) break;
87386       }
87387       if( !p ) return;
87388       iSkip = sqlite3VdbeMakeLabel(v);
87389       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
87390     }
87391
87392     pParse->disableTriggers = 1;
87393     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
87394     pParse->disableTriggers = 0;
87395
87396     /* If the DELETE has generated immediate foreign key constraint 
87397     ** violations, halt the VDBE and return an error at this point, before
87398     ** any modifications to the schema are made. This is because statement
87399     ** transactions are not able to rollback schema changes.  */
87400     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
87401     sqlite3HaltConstraint(
87402         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
87403     );
87404
87405     if( iSkip ){
87406       sqlite3VdbeResolveLabel(v, iSkip);
87407     }
87408   }
87409 }
87410
87411 /*
87412 ** This function is called when inserting, deleting or updating a row of
87413 ** table pTab to generate VDBE code to perform foreign key constraint 
87414 ** processing for the operation.
87415 **
87416 ** For a DELETE operation, parameter regOld is passed the index of the
87417 ** first register in an array of (pTab->nCol+1) registers containing the
87418 ** rowid of the row being deleted, followed by each of the column values
87419 ** of the row being deleted, from left to right. Parameter regNew is passed
87420 ** zero in this case.
87421 **
87422 ** For an INSERT operation, regOld is passed zero and regNew is passed the
87423 ** first register of an array of (pTab->nCol+1) registers containing the new
87424 ** row data.
87425 **
87426 ** For an UPDATE operation, this function is called twice. Once before
87427 ** the original record is deleted from the table using the calling convention
87428 ** described for DELETE. Then again after the original record is deleted
87429 ** but before the new record is inserted using the INSERT convention. 
87430 */
87431 SQLITE_PRIVATE void sqlite3FkCheck(
87432   Parse *pParse,                  /* Parse context */
87433   Table *pTab,                    /* Row is being deleted from this table */ 
87434   int regOld,                     /* Previous row data is stored here */
87435   int regNew                      /* New row data is stored here */
87436 ){
87437   sqlite3 *db = pParse->db;       /* Database handle */
87438   FKey *pFKey;                    /* Used to iterate through FKs */
87439   int iDb;                        /* Index of database containing pTab */
87440   const char *zDb;                /* Name of database containing pTab */
87441   int isIgnoreErrors = pParse->disableTriggers;
87442
87443   /* Exactly one of regOld and regNew should be non-zero. */
87444   assert( (regOld==0)!=(regNew==0) );
87445
87446   /* If foreign-keys are disabled, this function is a no-op. */
87447   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
87448
87449   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87450   zDb = db->aDb[iDb].zName;
87451
87452   /* Loop through all the foreign key constraints for which pTab is the
87453   ** child table (the table that the foreign key definition is part of).  */
87454   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
87455     Table *pTo;                   /* Parent table of foreign key pFKey */
87456     Index *pIdx = 0;              /* Index on key columns in pTo */
87457     int *aiFree = 0;
87458     int *aiCol;
87459     int iCol;
87460     int i;
87461     int isIgnore = 0;
87462
87463     /* Find the parent table of this foreign key. Also find a unique index 
87464     ** on the parent key columns in the parent table. If either of these 
87465     ** schema items cannot be located, set an error in pParse and return 
87466     ** early.  */
87467     if( pParse->disableTriggers ){
87468       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
87469     }else{
87470       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
87471     }
87472     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
87473       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
87474       if( !isIgnoreErrors || db->mallocFailed ) return;
87475       if( pTo==0 ){
87476         /* If isIgnoreErrors is true, then a table is being dropped. In this
87477         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
87478         ** before actually dropping it in order to check FK constraints.
87479         ** If the parent table of an FK constraint on the current table is
87480         ** missing, behave as if it is empty. i.e. decrement the relevant
87481         ** FK counter for each row of the current table with non-NULL keys.
87482         */
87483         Vdbe *v = sqlite3GetVdbe(pParse);
87484         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
87485         for(i=0; i<pFKey->nCol; i++){
87486           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
87487           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
87488         }
87489         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
87490       }
87491       continue;
87492     }
87493     assert( pFKey->nCol==1 || (aiFree && pIdx) );
87494
87495     if( aiFree ){
87496       aiCol = aiFree;
87497     }else{
87498       iCol = pFKey->aCol[0].iFrom;
87499       aiCol = &iCol;
87500     }
87501     for(i=0; i<pFKey->nCol; i++){
87502       if( aiCol[i]==pTab->iPKey ){
87503         aiCol[i] = -1;
87504       }
87505 #ifndef SQLITE_OMIT_AUTHORIZATION
87506       /* Request permission to read the parent key columns. If the 
87507       ** authorization callback returns SQLITE_IGNORE, behave as if any
87508       ** values read from the parent table are NULL. */
87509       if( db->xAuth ){
87510         int rcauth;
87511         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
87512         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
87513         isIgnore = (rcauth==SQLITE_IGNORE);
87514       }
87515 #endif
87516     }
87517
87518     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
87519     ** a cursor to use to search the unique index on the parent key columns 
87520     ** in the parent table.  */
87521     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
87522     pParse->nTab++;
87523
87524     if( regOld!=0 ){
87525       /* A row is being removed from the child table. Search for the parent.
87526       ** If the parent does not exist, removing the child row resolves an 
87527       ** outstanding foreign key constraint violation. */
87528       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
87529     }
87530     if( regNew!=0 ){
87531       /* A row is being added to the child table. If a parent row cannot
87532       ** be found, adding the child row has violated the FK constraint. */ 
87533       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
87534     }
87535
87536     sqlite3DbFree(db, aiFree);
87537   }
87538
87539   /* Loop through all the foreign key constraints that refer to this table */
87540   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
87541     Index *pIdx = 0;              /* Foreign key index for pFKey */
87542     SrcList *pSrc;
87543     int *aiCol = 0;
87544
87545     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
87546       assert( regOld==0 && regNew!=0 );
87547       /* Inserting a single row into a parent table cannot cause an immediate
87548       ** foreign key violation. So do nothing in this case.  */
87549       continue;
87550     }
87551
87552     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
87553       if( !isIgnoreErrors || db->mallocFailed ) return;
87554       continue;
87555     }
87556     assert( aiCol || pFKey->nCol==1 );
87557
87558     /* Create a SrcList structure containing a single table (the table 
87559     ** the foreign key that refers to this table is attached to). This
87560     ** is required for the sqlite3WhereXXX() interface.  */
87561     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
87562     if( pSrc ){
87563       struct SrcList_item *pItem = pSrc->a;
87564       pItem->pTab = pFKey->pFrom;
87565       pItem->zName = pFKey->pFrom->zName;
87566       pItem->pTab->nRef++;
87567       pItem->iCursor = pParse->nTab++;
87568   
87569       if( regNew!=0 ){
87570         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
87571       }
87572       if( regOld!=0 ){
87573         /* If there is a RESTRICT action configured for the current operation
87574         ** on the parent table of this FK, then throw an exception 
87575         ** immediately if the FK constraint is violated, even if this is a
87576         ** deferred trigger. That's what RESTRICT means. To defer checking
87577         ** the constraint, the FK should specify NO ACTION (represented
87578         ** using OE_None). NO ACTION is the default.  */
87579         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
87580       }
87581       pItem->zName = 0;
87582       sqlite3SrcListDelete(db, pSrc);
87583     }
87584     sqlite3DbFree(db, aiCol);
87585   }
87586 }
87587
87588 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
87589
87590 /*
87591 ** This function is called before generating code to update or delete a 
87592 ** row contained in table pTab.
87593 */
87594 SQLITE_PRIVATE u32 sqlite3FkOldmask(
87595   Parse *pParse,                  /* Parse context */
87596   Table *pTab                     /* Table being modified */
87597 ){
87598   u32 mask = 0;
87599   if( pParse->db->flags&SQLITE_ForeignKeys ){
87600     FKey *p;
87601     int i;
87602     for(p=pTab->pFKey; p; p=p->pNextFrom){
87603       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
87604     }
87605     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87606       Index *pIdx = 0;
87607       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
87608       if( pIdx ){
87609         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
87610       }
87611     }
87612   }
87613   return mask;
87614 }
87615
87616 /*
87617 ** This function is called before generating code to update or delete a 
87618 ** row contained in table pTab. If the operation is a DELETE, then
87619 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
87620 ** to an array of size N, where N is the number of columns in table pTab.
87621 ** If the i'th column is not modified by the UPDATE, then the corresponding 
87622 ** entry in the aChange[] array is set to -1. If the column is modified,
87623 ** the value is 0 or greater. Parameter chngRowid is set to true if the
87624 ** UPDATE statement modifies the rowid fields of the table.
87625 **
87626 ** If any foreign key processing will be required, this function returns
87627 ** true. If there is no foreign key related processing, this function 
87628 ** returns false.
87629 */
87630 SQLITE_PRIVATE int sqlite3FkRequired(
87631   Parse *pParse,                  /* Parse context */
87632   Table *pTab,                    /* Table being modified */
87633   int *aChange,                   /* Non-NULL for UPDATE operations */
87634   int chngRowid                   /* True for UPDATE that affects rowid */
87635 ){
87636   if( pParse->db->flags&SQLITE_ForeignKeys ){
87637     if( !aChange ){
87638       /* A DELETE operation. Foreign key processing is required if the 
87639       ** table in question is either the child or parent table for any 
87640       ** foreign key constraint.  */
87641       return (sqlite3FkReferences(pTab) || pTab->pFKey);
87642     }else{
87643       /* This is an UPDATE. Foreign key processing is only required if the
87644       ** operation modifies one or more child or parent key columns. */
87645       int i;
87646       FKey *p;
87647
87648       /* Check if any child key columns are being modified. */
87649       for(p=pTab->pFKey; p; p=p->pNextFrom){
87650         for(i=0; i<p->nCol; i++){
87651           int iChildKey = p->aCol[i].iFrom;
87652           if( aChange[iChildKey]>=0 ) return 1;
87653           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
87654         }
87655       }
87656
87657       /* Check if any parent key columns are being modified. */
87658       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87659         for(i=0; i<p->nCol; i++){
87660           char *zKey = p->aCol[i].zCol;
87661           int iKey;
87662           for(iKey=0; iKey<pTab->nCol; iKey++){
87663             Column *pCol = &pTab->aCol[iKey];
87664             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
87665               if( aChange[iKey]>=0 ) return 1;
87666               if( iKey==pTab->iPKey && chngRowid ) return 1;
87667             }
87668           }
87669         }
87670       }
87671     }
87672   }
87673   return 0;
87674 }
87675
87676 /*
87677 ** This function is called when an UPDATE or DELETE operation is being 
87678 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
87679 ** If the current operation is an UPDATE, then the pChanges parameter is
87680 ** passed a pointer to the list of columns being modified. If it is a
87681 ** DELETE, pChanges is passed a NULL pointer.
87682 **
87683 ** It returns a pointer to a Trigger structure containing a trigger
87684 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
87685 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
87686 ** returned (these actions require no special handling by the triggers
87687 ** sub-system, code for them is created by fkScanChildren()).
87688 **
87689 ** For example, if pFKey is the foreign key and pTab is table "p" in 
87690 ** the following schema:
87691 **
87692 **   CREATE TABLE p(pk PRIMARY KEY);
87693 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
87694 **
87695 ** then the returned trigger structure is equivalent to:
87696 **
87697 **   CREATE TRIGGER ... DELETE ON p BEGIN
87698 **     DELETE FROM c WHERE ck = old.pk;
87699 **   END;
87700 **
87701 ** The returned pointer is cached as part of the foreign key object. It
87702 ** is eventually freed along with the rest of the foreign key object by 
87703 ** sqlite3FkDelete().
87704 */
87705 static Trigger *fkActionTrigger(
87706   Parse *pParse,                  /* Parse context */
87707   Table *pTab,                    /* Table being updated or deleted from */
87708   FKey *pFKey,                    /* Foreign key to get action for */
87709   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
87710 ){
87711   sqlite3 *db = pParse->db;       /* Database handle */
87712   int action;                     /* One of OE_None, OE_Cascade etc. */
87713   Trigger *pTrigger;              /* Trigger definition to return */
87714   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
87715
87716   action = pFKey->aAction[iAction];
87717   pTrigger = pFKey->apTrigger[iAction];
87718
87719   if( action!=OE_None && !pTrigger ){
87720     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
87721     char const *zFrom;            /* Name of child table */
87722     int nFrom;                    /* Length in bytes of zFrom */
87723     Index *pIdx = 0;              /* Parent key index for this FK */
87724     int *aiCol = 0;               /* child table cols -> parent key cols */
87725     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
87726     Expr *pWhere = 0;             /* WHERE clause of trigger step */
87727     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
87728     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
87729     int i;                        /* Iterator variable */
87730     Expr *pWhen = 0;              /* WHEN clause for the trigger */
87731
87732     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
87733     assert( aiCol || pFKey->nCol==1 );
87734
87735     for(i=0; i<pFKey->nCol; i++){
87736       Token tOld = { "old", 3 };  /* Literal "old" token */
87737       Token tNew = { "new", 3 };  /* Literal "new" token */
87738       Token tFromCol;             /* Name of column in child table */
87739       Token tToCol;               /* Name of column in parent table */
87740       int iFromCol;               /* Idx of column in child table */
87741       Expr *pEq;                  /* tFromCol = OLD.tToCol */
87742
87743       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
87744       assert( iFromCol>=0 );
87745       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
87746       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
87747
87748       tToCol.n = sqlite3Strlen30(tToCol.z);
87749       tFromCol.n = sqlite3Strlen30(tFromCol.z);
87750
87751       /* Create the expression "OLD.zToCol = zFromCol". It is important
87752       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
87753       ** that the affinity and collation sequence associated with the
87754       ** parent table are used for the comparison. */
87755       pEq = sqlite3PExpr(pParse, TK_EQ,
87756           sqlite3PExpr(pParse, TK_DOT, 
87757             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
87758             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
87759           , 0),
87760           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
87761       , 0);
87762       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87763
87764       /* For ON UPDATE, construct the next term of the WHEN clause.
87765       ** The final WHEN clause will be like this:
87766       **
87767       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
87768       */
87769       if( pChanges ){
87770         pEq = sqlite3PExpr(pParse, TK_IS,
87771             sqlite3PExpr(pParse, TK_DOT, 
87772               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
87773               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
87774               0),
87775             sqlite3PExpr(pParse, TK_DOT, 
87776               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
87777               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
87778               0),
87779             0);
87780         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
87781       }
87782   
87783       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
87784         Expr *pNew;
87785         if( action==OE_Cascade ){
87786           pNew = sqlite3PExpr(pParse, TK_DOT, 
87787             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
87788             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
87789           , 0);
87790         }else if( action==OE_SetDflt ){
87791           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
87792           if( pDflt ){
87793             pNew = sqlite3ExprDup(db, pDflt, 0);
87794           }else{
87795             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
87796           }
87797         }else{
87798           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
87799         }
87800         pList = sqlite3ExprListAppend(pParse, pList, pNew);
87801         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
87802       }
87803     }
87804     sqlite3DbFree(db, aiCol);
87805
87806     zFrom = pFKey->pFrom->zName;
87807     nFrom = sqlite3Strlen30(zFrom);
87808
87809     if( action==OE_Restrict ){
87810       Token tFrom;
87811       Expr *pRaise; 
87812
87813       tFrom.z = zFrom;
87814       tFrom.n = nFrom;
87815       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
87816       if( pRaise ){
87817         pRaise->affinity = OE_Abort;
87818       }
87819       pSelect = sqlite3SelectNew(pParse, 
87820           sqlite3ExprListAppend(pParse, 0, pRaise),
87821           sqlite3SrcListAppend(db, 0, &tFrom, 0),
87822           pWhere,
87823           0, 0, 0, 0, 0, 0
87824       );
87825       pWhere = 0;
87826     }
87827
87828     /* Disable lookaside memory allocation */
87829     enableLookaside = db->lookaside.bEnabled;
87830     db->lookaside.bEnabled = 0;
87831
87832     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
87833         sizeof(Trigger) +         /* struct Trigger */
87834         sizeof(TriggerStep) +     /* Single step in trigger program */
87835         nFrom + 1                 /* Space for pStep->target.z */
87836     );
87837     if( pTrigger ){
87838       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
87839       pStep->target.z = (char *)&pStep[1];
87840       pStep->target.n = nFrom;
87841       memcpy((char *)pStep->target.z, zFrom, nFrom);
87842   
87843       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
87844       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
87845       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
87846       if( pWhen ){
87847         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
87848         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
87849       }
87850     }
87851
87852     /* Re-enable the lookaside buffer, if it was disabled earlier. */
87853     db->lookaside.bEnabled = enableLookaside;
87854
87855     sqlite3ExprDelete(db, pWhere);
87856     sqlite3ExprDelete(db, pWhen);
87857     sqlite3ExprListDelete(db, pList);
87858     sqlite3SelectDelete(db, pSelect);
87859     if( db->mallocFailed==1 ){
87860       fkTriggerDelete(db, pTrigger);
87861       return 0;
87862     }
87863     assert( pStep!=0 );
87864
87865     switch( action ){
87866       case OE_Restrict:
87867         pStep->op = TK_SELECT; 
87868         break;
87869       case OE_Cascade: 
87870         if( !pChanges ){ 
87871           pStep->op = TK_DELETE; 
87872           break; 
87873         }
87874       default:
87875         pStep->op = TK_UPDATE;
87876     }
87877     pStep->pTrig = pTrigger;
87878     pTrigger->pSchema = pTab->pSchema;
87879     pTrigger->pTabSchema = pTab->pSchema;
87880     pFKey->apTrigger[iAction] = pTrigger;
87881     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
87882   }
87883
87884   return pTrigger;
87885 }
87886
87887 /*
87888 ** This function is called when deleting or updating a row to implement
87889 ** any required CASCADE, SET NULL or SET DEFAULT actions.
87890 */
87891 SQLITE_PRIVATE void sqlite3FkActions(
87892   Parse *pParse,                  /* Parse context */
87893   Table *pTab,                    /* Table being updated or deleted from */
87894   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
87895   int regOld                      /* Address of array containing old row */
87896 ){
87897   /* If foreign-key support is enabled, iterate through all FKs that 
87898   ** refer to table pTab. If there is an action associated with the FK 
87899   ** for this operation (either update or delete), invoke the associated 
87900   ** trigger sub-program.  */
87901   if( pParse->db->flags&SQLITE_ForeignKeys ){
87902     FKey *pFKey;                  /* Iterator variable */
87903     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
87904       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
87905       if( pAction ){
87906         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
87907       }
87908     }
87909   }
87910 }
87911
87912 #endif /* ifndef SQLITE_OMIT_TRIGGER */
87913
87914 /*
87915 ** Free all memory associated with foreign key definitions attached to
87916 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
87917 ** hash table.
87918 */
87919 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
87920   FKey *pFKey;                    /* Iterator variable */
87921   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
87922
87923   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
87924   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
87925
87926     /* Remove the FK from the fkeyHash hash table. */
87927     if( !db || db->pnBytesFreed==0 ){
87928       if( pFKey->pPrevTo ){
87929         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
87930       }else{
87931         void *p = (void *)pFKey->pNextTo;
87932         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
87933         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
87934       }
87935       if( pFKey->pNextTo ){
87936         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
87937       }
87938     }
87939
87940     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
87941     ** classified as either immediate or deferred.
87942     */
87943     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
87944
87945     /* Delete any triggers created to implement actions for this FK. */
87946 #ifndef SQLITE_OMIT_TRIGGER
87947     fkTriggerDelete(db, pFKey->apTrigger[0]);
87948     fkTriggerDelete(db, pFKey->apTrigger[1]);
87949 #endif
87950
87951     pNext = pFKey->pNextFrom;
87952     sqlite3DbFree(db, pFKey);
87953   }
87954 }
87955 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
87956
87957 /************** End of fkey.c ************************************************/
87958 /************** Begin file insert.c ******************************************/
87959 /*
87960 ** 2001 September 15
87961 **
87962 ** The author disclaims copyright to this source code.  In place of
87963 ** a legal notice, here is a blessing:
87964 **
87965 **    May you do good and not evil.
87966 **    May you find forgiveness for yourself and forgive others.
87967 **    May you share freely, never taking more than you give.
87968 **
87969 *************************************************************************
87970 ** This file contains C code routines that are called by the parser
87971 ** to handle INSERT statements in SQLite.
87972 */
87973
87974 /*
87975 ** Generate code that will open a table for reading.
87976 */
87977 SQLITE_PRIVATE void sqlite3OpenTable(
87978   Parse *p,       /* Generate code into this VDBE */
87979   int iCur,       /* The cursor number of the table */
87980   int iDb,        /* The database index in sqlite3.aDb[] */
87981   Table *pTab,    /* The table to be opened */
87982   int opcode      /* OP_OpenRead or OP_OpenWrite */
87983 ){
87984   Vdbe *v;
87985   if( IsVirtual(pTab) ) return;
87986   v = sqlite3GetVdbe(p);
87987   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
87988   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
87989   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
87990   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
87991   VdbeComment((v, "%s", pTab->zName));
87992 }
87993
87994 /*
87995 ** Return a pointer to the column affinity string associated with index
87996 ** pIdx. A column affinity string has one character for each column in 
87997 ** the table, according to the affinity of the column:
87998 **
87999 **  Character      Column affinity
88000 **  ------------------------------
88001 **  'a'            TEXT
88002 **  'b'            NONE
88003 **  'c'            NUMERIC
88004 **  'd'            INTEGER
88005 **  'e'            REAL
88006 **
88007 ** An extra 'd' is appended to the end of the string to cover the
88008 ** rowid that appears as the last column in every index.
88009 **
88010 ** Memory for the buffer containing the column index affinity string
88011 ** is managed along with the rest of the Index structure. It will be
88012 ** released when sqlite3DeleteIndex() is called.
88013 */
88014 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
88015   if( !pIdx->zColAff ){
88016     /* The first time a column affinity string for a particular index is
88017     ** required, it is allocated and populated here. It is then stored as
88018     ** a member of the Index structure for subsequent use.
88019     **
88020     ** The column affinity string will eventually be deleted by
88021     ** sqliteDeleteIndex() when the Index structure itself is cleaned
88022     ** up.
88023     */
88024     int n;
88025     Table *pTab = pIdx->pTable;
88026     sqlite3 *db = sqlite3VdbeDb(v);
88027     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
88028     if( !pIdx->zColAff ){
88029       db->mallocFailed = 1;
88030       return 0;
88031     }
88032     for(n=0; n<pIdx->nColumn; n++){
88033       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88034     }
88035     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
88036     pIdx->zColAff[n] = 0;
88037   }
88038  
88039   return pIdx->zColAff;
88040 }
88041
88042 /*
88043 ** Set P4 of the most recently inserted opcode to a column affinity
88044 ** string for table pTab. A column affinity string has one character
88045 ** for each column indexed by the index, according to the affinity of the
88046 ** column:
88047 **
88048 **  Character      Column affinity
88049 **  ------------------------------
88050 **  'a'            TEXT
88051 **  'b'            NONE
88052 **  'c'            NUMERIC
88053 **  'd'            INTEGER
88054 **  'e'            REAL
88055 */
88056 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
88057   /* The first time a column affinity string for a particular table
88058   ** is required, it is allocated and populated here. It is then 
88059   ** stored as a member of the Table structure for subsequent use.
88060   **
88061   ** The column affinity string will eventually be deleted by
88062   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
88063   */
88064   if( !pTab->zColAff ){
88065     char *zColAff;
88066     int i;
88067     sqlite3 *db = sqlite3VdbeDb(v);
88068
88069     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
88070     if( !zColAff ){
88071       db->mallocFailed = 1;
88072       return;
88073     }
88074
88075     for(i=0; i<pTab->nCol; i++){
88076       zColAff[i] = pTab->aCol[i].affinity;
88077     }
88078     zColAff[pTab->nCol] = '\0';
88079
88080     pTab->zColAff = zColAff;
88081   }
88082
88083   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88084 }
88085
88086 /*
88087 ** Return non-zero if the table pTab in database iDb or any of its indices
88088 ** have been opened at any point in the VDBE program beginning at location
88089 ** iStartAddr throught the end of the program.  This is used to see if 
88090 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
88091 ** run without using temporary table for the results of the SELECT. 
88092 */
88093 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
88094   Vdbe *v = sqlite3GetVdbe(p);
88095   int i;
88096   int iEnd = sqlite3VdbeCurrentAddr(v);
88097 #ifndef SQLITE_OMIT_VIRTUALTABLE
88098   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
88099 #endif
88100
88101   for(i=iStartAddr; i<iEnd; i++){
88102     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
88103     assert( pOp!=0 );
88104     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
88105       Index *pIndex;
88106       int tnum = pOp->p2;
88107       if( tnum==pTab->tnum ){
88108         return 1;
88109       }
88110       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
88111         if( tnum==pIndex->tnum ){
88112           return 1;
88113         }
88114       }
88115     }
88116 #ifndef SQLITE_OMIT_VIRTUALTABLE
88117     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
88118       assert( pOp->p4.pVtab!=0 );
88119       assert( pOp->p4type==P4_VTAB );
88120       return 1;
88121     }
88122 #endif
88123   }
88124   return 0;
88125 }
88126
88127 #ifndef SQLITE_OMIT_AUTOINCREMENT
88128 /*
88129 ** Locate or create an AutoincInfo structure associated with table pTab
88130 ** which is in database iDb.  Return the register number for the register
88131 ** that holds the maximum rowid.
88132 **
88133 ** There is at most one AutoincInfo structure per table even if the
88134 ** same table is autoincremented multiple times due to inserts within
88135 ** triggers.  A new AutoincInfo structure is created if this is the
88136 ** first use of table pTab.  On 2nd and subsequent uses, the original
88137 ** AutoincInfo structure is used.
88138 **
88139 ** Three memory locations are allocated:
88140 **
88141 **   (1)  Register to hold the name of the pTab table.
88142 **   (2)  Register to hold the maximum ROWID of pTab.
88143 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
88144 **
88145 ** The 2nd register is the one that is returned.  That is all the
88146 ** insert routine needs to know about.
88147 */
88148 static int autoIncBegin(
88149   Parse *pParse,      /* Parsing context */
88150   int iDb,            /* Index of the database holding pTab */
88151   Table *pTab         /* The table we are writing to */
88152 ){
88153   int memId = 0;      /* Register holding maximum rowid */
88154   if( pTab->tabFlags & TF_Autoincrement ){
88155     Parse *pToplevel = sqlite3ParseToplevel(pParse);
88156     AutoincInfo *pInfo;
88157
88158     pInfo = pToplevel->pAinc;
88159     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
88160     if( pInfo==0 ){
88161       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
88162       if( pInfo==0 ) return 0;
88163       pInfo->pNext = pToplevel->pAinc;
88164       pToplevel->pAinc = pInfo;
88165       pInfo->pTab = pTab;
88166       pInfo->iDb = iDb;
88167       pToplevel->nMem++;                  /* Register to hold name of table */
88168       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
88169       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
88170     }
88171     memId = pInfo->regCtr;
88172   }
88173   return memId;
88174 }
88175
88176 /*
88177 ** This routine generates code that will initialize all of the
88178 ** register used by the autoincrement tracker.  
88179 */
88180 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
88181   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
88182   sqlite3 *db = pParse->db;  /* The database connection */
88183   Db *pDb;                   /* Database only autoinc table */
88184   int memId;                 /* Register holding max rowid */
88185   int addr;                  /* A VDBE address */
88186   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
88187
88188   /* This routine is never called during trigger-generation.  It is
88189   ** only called from the top-level */
88190   assert( pParse->pTriggerTab==0 );
88191   assert( pParse==sqlite3ParseToplevel(pParse) );
88192
88193   assert( v );   /* We failed long ago if this is not so */
88194   for(p = pParse->pAinc; p; p = p->pNext){
88195     pDb = &db->aDb[p->iDb];
88196     memId = p->regCtr;
88197     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
88198     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
88199     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
88200     addr = sqlite3VdbeCurrentAddr(v);
88201     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
88202     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
88203     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
88204     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
88205     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88206     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88207     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
88208     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
88209     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
88210     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
88211     sqlite3VdbeAddOp0(v, OP_Close);
88212   }
88213 }
88214
88215 /*
88216 ** Update the maximum rowid for an autoincrement calculation.
88217 **
88218 ** This routine should be called when the top of the stack holds a
88219 ** new rowid that is about to be inserted.  If that new rowid is
88220 ** larger than the maximum rowid in the memId memory cell, then the
88221 ** memory cell is updated.  The stack is unchanged.
88222 */
88223 static void autoIncStep(Parse *pParse, int memId, int regRowid){
88224   if( memId>0 ){
88225     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
88226   }
88227 }
88228
88229 /*
88230 ** This routine generates the code needed to write autoincrement
88231 ** maximum rowid values back into the sqlite_sequence register.
88232 ** Every statement that might do an INSERT into an autoincrement
88233 ** table (either directly or through triggers) needs to call this
88234 ** routine just before the "exit" code.
88235 */
88236 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
88237   AutoincInfo *p;
88238   Vdbe *v = pParse->pVdbe;
88239   sqlite3 *db = pParse->db;
88240
88241   assert( v );
88242   for(p = pParse->pAinc; p; p = p->pNext){
88243     Db *pDb = &db->aDb[p->iDb];
88244     int j1, j2, j3, j4, j5;
88245     int iRec;
88246     int memId = p->regCtr;
88247
88248     iRec = sqlite3GetTempReg(pParse);
88249     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
88250     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
88251     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
88252     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
88253     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
88254     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
88255     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
88256     sqlite3VdbeJumpHere(v, j2);
88257     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
88258     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
88259     sqlite3VdbeJumpHere(v, j4);
88260     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88261     sqlite3VdbeJumpHere(v, j1);
88262     sqlite3VdbeJumpHere(v, j5);
88263     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
88264     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
88265     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88266     sqlite3VdbeAddOp0(v, OP_Close);
88267     sqlite3ReleaseTempReg(pParse, iRec);
88268   }
88269 }
88270 #else
88271 /*
88272 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
88273 ** above are all no-ops
88274 */
88275 # define autoIncBegin(A,B,C) (0)
88276 # define autoIncStep(A,B,C)
88277 #endif /* SQLITE_OMIT_AUTOINCREMENT */
88278
88279
88280 /* Forward declaration */
88281 static int xferOptimization(
88282   Parse *pParse,        /* Parser context */
88283   Table *pDest,         /* The table we are inserting into */
88284   Select *pSelect,      /* A SELECT statement to use as the data source */
88285   int onError,          /* How to handle constraint errors */
88286   int iDbDest           /* The database of pDest */
88287 );
88288
88289 /*
88290 ** This routine is call to handle SQL of the following forms:
88291 **
88292 **    insert into TABLE (IDLIST) values(EXPRLIST)
88293 **    insert into TABLE (IDLIST) select
88294 **
88295 ** The IDLIST following the table name is always optional.  If omitted,
88296 ** then a list of all columns for the table is substituted.  The IDLIST
88297 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
88298 **
88299 ** The pList parameter holds EXPRLIST in the first form of the INSERT
88300 ** statement above, and pSelect is NULL.  For the second form, pList is
88301 ** NULL and pSelect is a pointer to the select statement used to generate
88302 ** data for the insert.
88303 **
88304 ** The code generated follows one of four templates.  For a simple
88305 ** select with data coming from a VALUES clause, the code executes
88306 ** once straight down through.  Pseudo-code follows (we call this
88307 ** the "1st template"):
88308 **
88309 **         open write cursor to <table> and its indices
88310 **         puts VALUES clause expressions onto the stack
88311 **         write the resulting record into <table>
88312 **         cleanup
88313 **
88314 ** The three remaining templates assume the statement is of the form
88315 **
88316 **   INSERT INTO <table> SELECT ...
88317 **
88318 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
88319 ** in other words if the SELECT pulls all columns from a single table
88320 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
88321 ** if <table2> and <table1> are distinct tables but have identical
88322 ** schemas, including all the same indices, then a special optimization
88323 ** is invoked that copies raw records from <table2> over to <table1>.
88324 ** See the xferOptimization() function for the implementation of this
88325 ** template.  This is the 2nd template.
88326 **
88327 **         open a write cursor to <table>
88328 **         open read cursor on <table2>
88329 **         transfer all records in <table2> over to <table>
88330 **         close cursors
88331 **         foreach index on <table>
88332 **           open a write cursor on the <table> index
88333 **           open a read cursor on the corresponding <table2> index
88334 **           transfer all records from the read to the write cursors
88335 **           close cursors
88336 **         end foreach
88337 **
88338 ** The 3rd template is for when the second template does not apply
88339 ** and the SELECT clause does not read from <table> at any time.
88340 ** The generated code follows this template:
88341 **
88342 **         EOF <- 0
88343 **         X <- A
88344 **         goto B
88345 **      A: setup for the SELECT
88346 **         loop over the rows in the SELECT
88347 **           load values into registers R..R+n
88348 **           yield X
88349 **         end loop
88350 **         cleanup after the SELECT
88351 **         EOF <- 1
88352 **         yield X
88353 **         goto A
88354 **      B: open write cursor to <table> and its indices
88355 **      C: yield X
88356 **         if EOF goto D
88357 **         insert the select result into <table> from R..R+n
88358 **         goto C
88359 **      D: cleanup
88360 **
88361 ** The 4th template is used if the insert statement takes its
88362 ** values from a SELECT but the data is being inserted into a table
88363 ** that is also read as part of the SELECT.  In the third form,
88364 ** we have to use a intermediate table to store the results of
88365 ** the select.  The template is like this:
88366 **
88367 **         EOF <- 0
88368 **         X <- A
88369 **         goto B
88370 **      A: setup for the SELECT
88371 **         loop over the tables in the SELECT
88372 **           load value into register R..R+n
88373 **           yield X
88374 **         end loop
88375 **         cleanup after the SELECT
88376 **         EOF <- 1
88377 **         yield X
88378 **         halt-error
88379 **      B: open temp table
88380 **      L: yield X
88381 **         if EOF goto M
88382 **         insert row from R..R+n into temp table
88383 **         goto L
88384 **      M: open write cursor to <table> and its indices
88385 **         rewind temp table
88386 **      C: loop over rows of intermediate table
88387 **           transfer values form intermediate table into <table>
88388 **         end loop
88389 **      D: cleanup
88390 */
88391 SQLITE_PRIVATE void sqlite3Insert(
88392   Parse *pParse,        /* Parser context */
88393   SrcList *pTabList,    /* Name of table into which we are inserting */
88394   ExprList *pList,      /* List of values to be inserted */
88395   Select *pSelect,      /* A SELECT statement to use as the data source */
88396   IdList *pColumn,      /* Column names corresponding to IDLIST. */
88397   int onError           /* How to handle constraint errors */
88398 ){
88399   sqlite3 *db;          /* The main database structure */
88400   Table *pTab;          /* The table to insert into.  aka TABLE */
88401   char *zTab;           /* Name of the table into which we are inserting */
88402   const char *zDb;      /* Name of the database holding this table */
88403   int i, j, idx;        /* Loop counters */
88404   Vdbe *v;              /* Generate code into this virtual machine */
88405   Index *pIdx;          /* For looping over indices of the table */
88406   int nColumn;          /* Number of columns in the data */
88407   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
88408   int baseCur = 0;      /* VDBE Cursor number for pTab */
88409   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
88410   int endOfLoop;        /* Label for the end of the insertion loop */
88411   int useTempTable = 0; /* Store SELECT results in intermediate table */
88412   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
88413   int addrInsTop = 0;   /* Jump to label "D" */
88414   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
88415   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
88416   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
88417   int iDb;              /* Index of database holding TABLE */
88418   Db *pDb;              /* The database containing table being inserted into */
88419   int appendFlag = 0;   /* True if the insert is likely to be an append */
88420
88421   /* Register allocations */
88422   int regFromSelect = 0;/* Base register for data coming from SELECT */
88423   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
88424   int regRowCount = 0;  /* Memory cell used for the row counter */
88425   int regIns;           /* Block of regs holding rowid+data being inserted */
88426   int regRowid;         /* registers holding insert rowid */
88427   int regData;          /* register holding first column to insert */
88428   int regEof = 0;       /* Register recording end of SELECT data */
88429   int *aRegIdx = 0;     /* One register allocated to each index */
88430
88431 #ifndef SQLITE_OMIT_TRIGGER
88432   int isView;                 /* True if attempting to insert into a view */
88433   Trigger *pTrigger;          /* List of triggers on pTab, if required */
88434   int tmask;                  /* Mask of trigger times */
88435 #endif
88436
88437   db = pParse->db;
88438   memset(&dest, 0, sizeof(dest));
88439   if( pParse->nErr || db->mallocFailed ){
88440     goto insert_cleanup;
88441   }
88442
88443   /* Locate the table into which we will be inserting new information.
88444   */
88445   assert( pTabList->nSrc==1 );
88446   zTab = pTabList->a[0].zName;
88447   if( NEVER(zTab==0) ) goto insert_cleanup;
88448   pTab = sqlite3SrcListLookup(pParse, pTabList);
88449   if( pTab==0 ){
88450     goto insert_cleanup;
88451   }
88452   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88453   assert( iDb<db->nDb );
88454   pDb = &db->aDb[iDb];
88455   zDb = pDb->zName;
88456   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
88457     goto insert_cleanup;
88458   }
88459
88460   /* Figure out if we have any triggers and if the table being
88461   ** inserted into is a view
88462   */
88463 #ifndef SQLITE_OMIT_TRIGGER
88464   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
88465   isView = pTab->pSelect!=0;
88466 #else
88467 # define pTrigger 0
88468 # define tmask 0
88469 # define isView 0
88470 #endif
88471 #ifdef SQLITE_OMIT_VIEW
88472 # undef isView
88473 # define isView 0
88474 #endif
88475   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
88476
88477   /* If pTab is really a view, make sure it has been initialized.
88478   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
88479   ** module table).
88480   */
88481   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
88482     goto insert_cleanup;
88483   }
88484
88485   /* Ensure that:
88486   *  (a) the table is not read-only, 
88487   *  (b) that if it is a view then ON INSERT triggers exist
88488   */
88489   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
88490     goto insert_cleanup;
88491   }
88492
88493   /* Allocate a VDBE
88494   */
88495   v = sqlite3GetVdbe(pParse);
88496   if( v==0 ) goto insert_cleanup;
88497   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
88498   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
88499
88500 #ifndef SQLITE_OMIT_XFER_OPT
88501   /* If the statement is of the form
88502   **
88503   **       INSERT INTO <table1> SELECT * FROM <table2>;
88504   **
88505   ** Then special optimizations can be applied that make the transfer
88506   ** very fast and which reduce fragmentation of indices.
88507   **
88508   ** This is the 2nd template.
88509   */
88510   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
88511     assert( !pTrigger );
88512     assert( pList==0 );
88513     goto insert_end;
88514   }
88515 #endif /* SQLITE_OMIT_XFER_OPT */
88516
88517   /* If this is an AUTOINCREMENT table, look up the sequence number in the
88518   ** sqlite_sequence table and store it in memory cell regAutoinc.
88519   */
88520   regAutoinc = autoIncBegin(pParse, iDb, pTab);
88521
88522   /* Figure out how many columns of data are supplied.  If the data
88523   ** is coming from a SELECT statement, then generate a co-routine that
88524   ** produces a single row of the SELECT on each invocation.  The
88525   ** co-routine is the common header to the 3rd and 4th templates.
88526   */
88527   if( pSelect ){
88528     /* Data is coming from a SELECT.  Generate code to implement that SELECT
88529     ** as a co-routine.  The code is common to both the 3rd and 4th
88530     ** templates:
88531     **
88532     **         EOF <- 0
88533     **         X <- A
88534     **         goto B
88535     **      A: setup for the SELECT
88536     **         loop over the tables in the SELECT
88537     **           load value into register R..R+n
88538     **           yield X
88539     **         end loop
88540     **         cleanup after the SELECT
88541     **         EOF <- 1
88542     **         yield X
88543     **         halt-error
88544     **
88545     ** On each invocation of the co-routine, it puts a single row of the
88546     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
88547     ** (These output registers are allocated by sqlite3Select().)  When
88548     ** the SELECT completes, it sets the EOF flag stored in regEof.
88549     */
88550     int rc, j1;
88551
88552     regEof = ++pParse->nMem;
88553     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
88554     VdbeComment((v, "SELECT eof flag"));
88555     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
88556     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
88557     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iSDParm);
88558     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
88559     VdbeComment((v, "Jump over SELECT coroutine"));
88560
88561     /* Resolve the expressions in the SELECT statement and execute it. */
88562     rc = sqlite3Select(pParse, pSelect, &dest);
88563     assert( pParse->nErr==0 || rc );
88564     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
88565       goto insert_cleanup;
88566     }
88567     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
88568     sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);   /* yield X */
88569     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
88570     VdbeComment((v, "End of SELECT coroutine"));
88571     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
88572
88573     regFromSelect = dest.iSdst;
88574     assert( pSelect->pEList );
88575     nColumn = pSelect->pEList->nExpr;
88576     assert( dest.nSdst==nColumn );
88577
88578     /* Set useTempTable to TRUE if the result of the SELECT statement
88579     ** should be written into a temporary table (template 4).  Set to
88580     ** FALSE if each* row of the SELECT can be written directly into
88581     ** the destination table (template 3).
88582     **
88583     ** A temp table must be used if the table being updated is also one
88584     ** of the tables being read by the SELECT statement.  Also use a 
88585     ** temp table in the case of row triggers.
88586     */
88587     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
88588       useTempTable = 1;
88589     }
88590
88591     if( useTempTable ){
88592       /* Invoke the coroutine to extract information from the SELECT
88593       ** and add it to a transient table srcTab.  The code generated
88594       ** here is from the 4th template:
88595       **
88596       **      B: open temp table
88597       **      L: yield X
88598       **         if EOF goto M
88599       **         insert row from R..R+n into temp table
88600       **         goto L
88601       **      M: ...
88602       */
88603       int regRec;          /* Register to hold packed record */
88604       int regTempRowid;    /* Register to hold temp table ROWID */
88605       int addrTop;         /* Label "L" */
88606       int addrIf;          /* Address of jump to M */
88607
88608       srcTab = pParse->nTab++;
88609       regRec = sqlite3GetTempReg(pParse);
88610       regTempRowid = sqlite3GetTempReg(pParse);
88611       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
88612       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
88613       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
88614       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
88615       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
88616       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
88617       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
88618       sqlite3VdbeJumpHere(v, addrIf);
88619       sqlite3ReleaseTempReg(pParse, regRec);
88620       sqlite3ReleaseTempReg(pParse, regTempRowid);
88621     }
88622   }else{
88623     /* This is the case if the data for the INSERT is coming from a VALUES
88624     ** clause
88625     */
88626     NameContext sNC;
88627     memset(&sNC, 0, sizeof(sNC));
88628     sNC.pParse = pParse;
88629     srcTab = -1;
88630     assert( useTempTable==0 );
88631     nColumn = pList ? pList->nExpr : 0;
88632     for(i=0; i<nColumn; i++){
88633       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
88634         goto insert_cleanup;
88635       }
88636     }
88637   }
88638
88639   /* Make sure the number of columns in the source data matches the number
88640   ** of columns to be inserted into the table.
88641   */
88642   if( IsVirtual(pTab) ){
88643     for(i=0; i<pTab->nCol; i++){
88644       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
88645     }
88646   }
88647   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
88648     sqlite3ErrorMsg(pParse, 
88649        "table %S has %d columns but %d values were supplied",
88650        pTabList, 0, pTab->nCol-nHidden, nColumn);
88651     goto insert_cleanup;
88652   }
88653   if( pColumn!=0 && nColumn!=pColumn->nId ){
88654     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
88655     goto insert_cleanup;
88656   }
88657
88658   /* If the INSERT statement included an IDLIST term, then make sure
88659   ** all elements of the IDLIST really are columns of the table and 
88660   ** remember the column indices.
88661   **
88662   ** If the table has an INTEGER PRIMARY KEY column and that column
88663   ** is named in the IDLIST, then record in the keyColumn variable
88664   ** the index into IDLIST of the primary key column.  keyColumn is
88665   ** the index of the primary key as it appears in IDLIST, not as
88666   ** is appears in the original table.  (The index of the primary
88667   ** key in the original table is pTab->iPKey.)
88668   */
88669   if( pColumn ){
88670     for(i=0; i<pColumn->nId; i++){
88671       pColumn->a[i].idx = -1;
88672     }
88673     for(i=0; i<pColumn->nId; i++){
88674       for(j=0; j<pTab->nCol; j++){
88675         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
88676           pColumn->a[i].idx = j;
88677           if( j==pTab->iPKey ){
88678             keyColumn = i;
88679           }
88680           break;
88681         }
88682       }
88683       if( j>=pTab->nCol ){
88684         if( sqlite3IsRowid(pColumn->a[i].zName) ){
88685           keyColumn = i;
88686         }else{
88687           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
88688               pTabList, 0, pColumn->a[i].zName);
88689           pParse->checkSchema = 1;
88690           goto insert_cleanup;
88691         }
88692       }
88693     }
88694   }
88695
88696   /* If there is no IDLIST term but the table has an integer primary
88697   ** key, the set the keyColumn variable to the primary key column index
88698   ** in the original table definition.
88699   */
88700   if( pColumn==0 && nColumn>0 ){
88701     keyColumn = pTab->iPKey;
88702   }
88703     
88704   /* Initialize the count of rows to be inserted
88705   */
88706   if( db->flags & SQLITE_CountRows ){
88707     regRowCount = ++pParse->nMem;
88708     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
88709   }
88710
88711   /* If this is not a view, open the table and and all indices */
88712   if( !isView ){
88713     int nIdx;
88714
88715     baseCur = pParse->nTab;
88716     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
88717     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
88718     if( aRegIdx==0 ){
88719       goto insert_cleanup;
88720     }
88721     for(i=0; i<nIdx; i++){
88722       aRegIdx[i] = ++pParse->nMem;
88723     }
88724   }
88725
88726   /* This is the top of the main insertion loop */
88727   if( useTempTable ){
88728     /* This block codes the top of loop only.  The complete loop is the
88729     ** following pseudocode (template 4):
88730     **
88731     **         rewind temp table
88732     **      C: loop over rows of intermediate table
88733     **           transfer values form intermediate table into <table>
88734     **         end loop
88735     **      D: ...
88736     */
88737     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
88738     addrCont = sqlite3VdbeCurrentAddr(v);
88739   }else if( pSelect ){
88740     /* This block codes the top of loop only.  The complete loop is the
88741     ** following pseudocode (template 3):
88742     **
88743     **      C: yield X
88744     **         if EOF goto D
88745     **         insert the select result into <table> from R..R+n
88746     **         goto C
88747     **      D: ...
88748     */
88749     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
88750     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
88751   }
88752
88753   /* Allocate registers for holding the rowid of the new row,
88754   ** the content of the new row, and the assemblied row record.
88755   */
88756   regRowid = regIns = pParse->nMem+1;
88757   pParse->nMem += pTab->nCol + 1;
88758   if( IsVirtual(pTab) ){
88759     regRowid++;
88760     pParse->nMem++;
88761   }
88762   regData = regRowid+1;
88763
88764   /* Run the BEFORE and INSTEAD OF triggers, if there are any
88765   */
88766   endOfLoop = sqlite3VdbeMakeLabel(v);
88767   if( tmask & TRIGGER_BEFORE ){
88768     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
88769
88770     /* build the NEW.* reference row.  Note that if there is an INTEGER
88771     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
88772     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88773     ** we do not know what the unique ID will be (because the insert has
88774     ** not happened yet) so we substitute a rowid of -1
88775     */
88776     if( keyColumn<0 ){
88777       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88778     }else{
88779       int j1;
88780       if( useTempTable ){
88781         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
88782       }else{
88783         assert( pSelect==0 );  /* Otherwise useTempTable is true */
88784         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
88785       }
88786       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
88787       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88788       sqlite3VdbeJumpHere(v, j1);
88789       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
88790     }
88791
88792     /* Cannot have triggers on a virtual table. If it were possible,
88793     ** this block would have to account for hidden column.
88794     */
88795     assert( !IsVirtual(pTab) );
88796
88797     /* Create the new column data
88798     */
88799     for(i=0; i<pTab->nCol; i++){
88800       if( pColumn==0 ){
88801         j = i;
88802       }else{
88803         for(j=0; j<pColumn->nId; j++){
88804           if( pColumn->a[j].idx==i ) break;
88805         }
88806       }
88807       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
88808         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
88809       }else if( useTempTable ){
88810         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
88811       }else{
88812         assert( pSelect==0 ); /* Otherwise useTempTable is true */
88813         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
88814       }
88815     }
88816
88817     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
88818     ** do not attempt any conversions before assembling the record.
88819     ** If this is a real table, attempt conversions as required by the
88820     ** table column affinities.
88821     */
88822     if( !isView ){
88823       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
88824       sqlite3TableAffinityStr(v, pTab);
88825     }
88826
88827     /* Fire BEFORE or INSTEAD OF triggers */
88828     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
88829         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
88830
88831     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
88832   }
88833
88834   /* Push the record number for the new entry onto the stack.  The
88835   ** record number is a randomly generate integer created by NewRowid
88836   ** except when the table has an INTEGER PRIMARY KEY column, in which
88837   ** case the record number is the same as that column. 
88838   */
88839   if( !isView ){
88840     if( IsVirtual(pTab) ){
88841       /* The row that the VUpdate opcode will delete: none */
88842       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
88843     }
88844     if( keyColumn>=0 ){
88845       if( useTempTable ){
88846         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
88847       }else if( pSelect ){
88848         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
88849       }else{
88850         VdbeOp *pOp;
88851         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
88852         pOp = sqlite3VdbeGetOp(v, -1);
88853         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
88854           appendFlag = 1;
88855           pOp->opcode = OP_NewRowid;
88856           pOp->p1 = baseCur;
88857           pOp->p2 = regRowid;
88858           pOp->p3 = regAutoinc;
88859         }
88860       }
88861       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
88862       ** to generate a unique primary key value.
88863       */
88864       if( !appendFlag ){
88865         int j1;
88866         if( !IsVirtual(pTab) ){
88867           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
88868           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
88869           sqlite3VdbeJumpHere(v, j1);
88870         }else{
88871           j1 = sqlite3VdbeCurrentAddr(v);
88872           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
88873         }
88874         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
88875       }
88876     }else if( IsVirtual(pTab) ){
88877       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
88878     }else{
88879       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
88880       appendFlag = 1;
88881     }
88882     autoIncStep(pParse, regAutoinc, regRowid);
88883
88884     /* Push onto the stack, data for all columns of the new entry, beginning
88885     ** with the first column.
88886     */
88887     nHidden = 0;
88888     for(i=0; i<pTab->nCol; i++){
88889       int iRegStore = regRowid+1+i;
88890       if( i==pTab->iPKey ){
88891         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
88892         ** Whenever this column is read, the record number will be substituted
88893         ** in its place.  So will fill this column with a NULL to avoid
88894         ** taking up data space with information that will never be used. */
88895         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
88896         continue;
88897       }
88898       if( pColumn==0 ){
88899         if( IsHiddenColumn(&pTab->aCol[i]) ){
88900           assert( IsVirtual(pTab) );
88901           j = -1;
88902           nHidden++;
88903         }else{
88904           j = i - nHidden;
88905         }
88906       }else{
88907         for(j=0; j<pColumn->nId; j++){
88908           if( pColumn->a[j].idx==i ) break;
88909         }
88910       }
88911       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
88912         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
88913       }else if( useTempTable ){
88914         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
88915       }else if( pSelect ){
88916         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
88917       }else{
88918         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
88919       }
88920     }
88921
88922     /* Generate code to check constraints and generate index keys and
88923     ** do the insertion.
88924     */
88925 #ifndef SQLITE_OMIT_VIRTUALTABLE
88926     if( IsVirtual(pTab) ){
88927       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
88928       sqlite3VtabMakeWritable(pParse, pTab);
88929       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
88930       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
88931       sqlite3MayAbort(pParse);
88932     }else
88933 #endif
88934     {
88935       int isReplace;    /* Set to true if constraints may cause a replace */
88936       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
88937           keyColumn>=0, 0, onError, endOfLoop, &isReplace
88938       );
88939       sqlite3FkCheck(pParse, pTab, 0, regIns);
88940       sqlite3CompleteInsertion(
88941           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
88942       );
88943     }
88944   }
88945
88946   /* Update the count of rows that are inserted
88947   */
88948   if( (db->flags & SQLITE_CountRows)!=0 ){
88949     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
88950   }
88951
88952   if( pTrigger ){
88953     /* Code AFTER triggers */
88954     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
88955         pTab, regData-2-pTab->nCol, onError, endOfLoop);
88956   }
88957
88958   /* The bottom of the main insertion loop, if the data source
88959   ** is a SELECT statement.
88960   */
88961   sqlite3VdbeResolveLabel(v, endOfLoop);
88962   if( useTempTable ){
88963     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
88964     sqlite3VdbeJumpHere(v, addrInsTop);
88965     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
88966   }else if( pSelect ){
88967     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
88968     sqlite3VdbeJumpHere(v, addrInsTop);
88969   }
88970
88971   if( !IsVirtual(pTab) && !isView ){
88972     /* Close all tables opened */
88973     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
88974     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
88975       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
88976     }
88977   }
88978
88979 insert_end:
88980   /* Update the sqlite_sequence table by storing the content of the
88981   ** maximum rowid counter values recorded while inserting into
88982   ** autoincrement tables.
88983   */
88984   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
88985     sqlite3AutoincrementEnd(pParse);
88986   }
88987
88988   /*
88989   ** Return the number of rows inserted. If this routine is 
88990   ** generating code because of a call to sqlite3NestedParse(), do not
88991   ** invoke the callback function.
88992   */
88993   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
88994     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
88995     sqlite3VdbeSetNumCols(v, 1);
88996     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
88997   }
88998
88999 insert_cleanup:
89000   sqlite3SrcListDelete(db, pTabList);
89001   sqlite3ExprListDelete(db, pList);
89002   sqlite3SelectDelete(db, pSelect);
89003   sqlite3IdListDelete(db, pColumn);
89004   sqlite3DbFree(db, aRegIdx);
89005 }
89006
89007 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89008 ** thely may interfere with compilation of other functions in this file
89009 ** (or in another file, if this file becomes part of the amalgamation).  */
89010 #ifdef isView
89011  #undef isView
89012 #endif
89013 #ifdef pTrigger
89014  #undef pTrigger
89015 #endif
89016 #ifdef tmask
89017  #undef tmask
89018 #endif
89019
89020
89021 /*
89022 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89023 **
89024 ** The input is a range of consecutive registers as follows:
89025 **
89026 **    1.  The rowid of the row after the update.
89027 **
89028 **    2.  The data in the first column of the entry after the update.
89029 **
89030 **    i.  Data from middle columns...
89031 **
89032 **    N.  The data in the last column of the entry after the update.
89033 **
89034 ** The regRowid parameter is the index of the register containing (1).
89035 **
89036 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89037 ** the address of a register containing the rowid before the update takes
89038 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89039 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
89040 ** indicates that the rowid was explicitly specified as part of the
89041 ** INSERT statement. If rowidChng is false, it means that  the rowid is
89042 ** computed automatically in an insert or that the rowid value is not 
89043 ** modified by an update.
89044 **
89045 ** The code generated by this routine store new index entries into
89046 ** registers identified by aRegIdx[].  No index entry is created for
89047 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
89048 ** the same as the order of indices on the linked list of indices
89049 ** attached to the table.
89050 **
89051 ** This routine also generates code to check constraints.  NOT NULL,
89052 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
89053 ** then the appropriate action is performed.  There are five possible
89054 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
89055 **
89056 **  Constraint type  Action       What Happens
89057 **  ---------------  ----------   ----------------------------------------
89058 **  any              ROLLBACK     The current transaction is rolled back and
89059 **                                sqlite3_exec() returns immediately with a
89060 **                                return code of SQLITE_CONSTRAINT.
89061 **
89062 **  any              ABORT        Back out changes from the current command
89063 **                                only (do not do a complete rollback) then
89064 **                                cause sqlite3_exec() to return immediately
89065 **                                with SQLITE_CONSTRAINT.
89066 **
89067 **  any              FAIL         Sqlite3_exec() returns immediately with a
89068 **                                return code of SQLITE_CONSTRAINT.  The
89069 **                                transaction is not rolled back and any
89070 **                                prior changes are retained.
89071 **
89072 **  any              IGNORE       The record number and data is popped from
89073 **                                the stack and there is an immediate jump
89074 **                                to label ignoreDest.
89075 **
89076 **  NOT NULL         REPLACE      The NULL value is replace by the default
89077 **                                value for that column.  If the default value
89078 **                                is NULL, the action is the same as ABORT.
89079 **
89080 **  UNIQUE           REPLACE      The other row that conflicts with the row
89081 **                                being inserted is removed.
89082 **
89083 **  CHECK            REPLACE      Illegal.  The results in an exception.
89084 **
89085 ** Which action to take is determined by the overrideError parameter.
89086 ** Or if overrideError==OE_Default, then the pParse->onError parameter
89087 ** is used.  Or if pParse->onError==OE_Default then the onError value
89088 ** for the constraint is used.
89089 **
89090 ** The calling routine must open a read/write cursor for pTab with
89091 ** cursor number "baseCur".  All indices of pTab must also have open
89092 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
89093 ** Except, if there is no possibility of a REPLACE action then
89094 ** cursors do not need to be open for indices where aRegIdx[i]==0.
89095 */
89096 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
89097   Parse *pParse,      /* The parser context */
89098   Table *pTab,        /* the table into which we are inserting */
89099   int baseCur,        /* Index of a read/write cursor pointing at pTab */
89100   int regRowid,       /* Index of the range of input registers */
89101   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
89102   int rowidChng,      /* True if the rowid might collide with existing entry */
89103   int isUpdate,       /* True for UPDATE, False for INSERT */
89104   int overrideError,  /* Override onError to this if not OE_Default */
89105   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
89106   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
89107 ){
89108   int i;              /* loop counter */
89109   Vdbe *v;            /* VDBE under constrution */
89110   int nCol;           /* Number of columns */
89111   int onError;        /* Conflict resolution strategy */
89112   int j1;             /* Addresss of jump instruction */
89113   int j2 = 0, j3;     /* Addresses of jump instructions */
89114   int regData;        /* Register containing first data column */
89115   int iCur;           /* Table cursor number */
89116   Index *pIdx;         /* Pointer to one of the indices */
89117   sqlite3 *db;         /* Database connection */
89118   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
89119   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
89120
89121   db = pParse->db;
89122   v = sqlite3GetVdbe(pParse);
89123   assert( v!=0 );
89124   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
89125   nCol = pTab->nCol;
89126   regData = regRowid + 1;
89127
89128   /* Test all NOT NULL constraints.
89129   */
89130   for(i=0; i<nCol; i++){
89131     if( i==pTab->iPKey ){
89132       continue;
89133     }
89134     onError = pTab->aCol[i].notNull;
89135     if( onError==OE_None ) continue;
89136     if( overrideError!=OE_Default ){
89137       onError = overrideError;
89138     }else if( onError==OE_Default ){
89139       onError = OE_Abort;
89140     }
89141     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
89142       onError = OE_Abort;
89143     }
89144     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89145         || onError==OE_Ignore || onError==OE_Replace );
89146     switch( onError ){
89147       case OE_Abort:
89148         sqlite3MayAbort(pParse);
89149       case OE_Rollback:
89150       case OE_Fail: {
89151         char *zMsg;
89152         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
89153                                   SQLITE_CONSTRAINT, onError, regData+i);
89154         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
89155                               pTab->zName, pTab->aCol[i].zName);
89156         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
89157         break;
89158       }
89159       case OE_Ignore: {
89160         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
89161         break;
89162       }
89163       default: {
89164         assert( onError==OE_Replace );
89165         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
89166         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
89167         sqlite3VdbeJumpHere(v, j1);
89168         break;
89169       }
89170     }
89171   }
89172
89173   /* Test all CHECK constraints
89174   */
89175 #ifndef SQLITE_OMIT_CHECK
89176   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
89177     ExprList *pCheck = pTab->pCheck;
89178     pParse->ckBase = regData;
89179     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
89180     for(i=0; i<pCheck->nExpr; i++){
89181       int allOk = sqlite3VdbeMakeLabel(v);
89182       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
89183       if( onError==OE_Ignore ){
89184         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89185       }else{
89186         char *zConsName = pCheck->a[i].zName;
89187         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
89188         if( zConsName ){
89189           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
89190         }else{
89191           zConsName = 0;
89192         }
89193         sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);
89194       }
89195       sqlite3VdbeResolveLabel(v, allOk);
89196     }
89197   }
89198 #endif /* !defined(SQLITE_OMIT_CHECK) */
89199
89200   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
89201   ** of the new record does not previously exist.  Except, if this
89202   ** is an UPDATE and the primary key is not changing, that is OK.
89203   */
89204   if( rowidChng ){
89205     onError = pTab->keyConf;
89206     if( overrideError!=OE_Default ){
89207       onError = overrideError;
89208     }else if( onError==OE_Default ){
89209       onError = OE_Abort;
89210     }
89211     
89212     if( isUpdate ){
89213       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
89214     }
89215     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
89216     switch( onError ){
89217       default: {
89218         onError = OE_Abort;
89219         /* Fall thru into the next case */
89220       }
89221       case OE_Rollback:
89222       case OE_Abort:
89223       case OE_Fail: {
89224         sqlite3HaltConstraint(
89225           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
89226         break;
89227       }
89228       case OE_Replace: {
89229         /* If there are DELETE triggers on this table and the
89230         ** recursive-triggers flag is set, call GenerateRowDelete() to
89231         ** remove the conflicting row from the table. This will fire
89232         ** the triggers and remove both the table and index b-tree entries.
89233         **
89234         ** Otherwise, if there are no triggers or the recursive-triggers
89235         ** flag is not set, but the table has one or more indexes, call 
89236         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
89237         ** only. The table b-tree entry will be replaced by the new entry 
89238         ** when it is inserted.  
89239         **
89240         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
89241         ** also invoke MultiWrite() to indicate that this VDBE may require
89242         ** statement rollback (if the statement is aborted after the delete
89243         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
89244         ** but being more selective here allows statements like:
89245         **
89246         **   REPLACE INTO t(rowid) VALUES($newrowid)
89247         **
89248         ** to run without a statement journal if there are no indexes on the
89249         ** table.
89250         */
89251         Trigger *pTrigger = 0;
89252         if( db->flags&SQLITE_RecTriggers ){
89253           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89254         }
89255         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
89256           sqlite3MultiWrite(pParse);
89257           sqlite3GenerateRowDelete(
89258               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
89259           );
89260         }else if( pTab->pIndex ){
89261           sqlite3MultiWrite(pParse);
89262           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
89263         }
89264         seenReplace = 1;
89265         break;
89266       }
89267       case OE_Ignore: {
89268         assert( seenReplace==0 );
89269         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89270         break;
89271       }
89272     }
89273     sqlite3VdbeJumpHere(v, j3);
89274     if( isUpdate ){
89275       sqlite3VdbeJumpHere(v, j2);
89276     }
89277   }
89278
89279   /* Test all UNIQUE constraints by creating entries for each UNIQUE
89280   ** index and making sure that duplicate entries do not already exist.
89281   ** Add the new records to the indices as we go.
89282   */
89283   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
89284     int regIdx;
89285     int regR;
89286
89287     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
89288
89289     /* Create a key for accessing the index entry */
89290     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
89291     for(i=0; i<pIdx->nColumn; i++){
89292       int idx = pIdx->aiColumn[i];
89293       if( idx==pTab->iPKey ){
89294         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89295       }else{
89296         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
89297       }
89298     }
89299     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89300     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
89301     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
89302     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
89303
89304     /* Find out what action to take in case there is an indexing conflict */
89305     onError = pIdx->onError;
89306     if( onError==OE_None ){ 
89307       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
89308       continue;  /* pIdx is not a UNIQUE index */
89309     }
89310     if( overrideError!=OE_Default ){
89311       onError = overrideError;
89312     }else if( onError==OE_Default ){
89313       onError = OE_Abort;
89314     }
89315     if( seenReplace ){
89316       if( onError==OE_Ignore ) onError = OE_Replace;
89317       else if( onError==OE_Fail ) onError = OE_Abort;
89318     }
89319     
89320     /* Check to see if the new index entry will be unique */
89321     regR = sqlite3GetTempReg(pParse);
89322     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
89323     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
89324                            regR, SQLITE_INT_TO_PTR(regIdx),
89325                            P4_INT32);
89326     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
89327
89328     /* Generate code that executes if the new index entry is not unique */
89329     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89330         || onError==OE_Ignore || onError==OE_Replace );
89331     switch( onError ){
89332       case OE_Rollback:
89333       case OE_Abort:
89334       case OE_Fail: {
89335         int j;
89336         StrAccum errMsg;
89337         const char *zSep;
89338         char *zErr;
89339
89340         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
89341         errMsg.db = db;
89342         zSep = pIdx->nColumn>1 ? "columns " : "column ";
89343         for(j=0; j<pIdx->nColumn; j++){
89344           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
89345           sqlite3StrAccumAppend(&errMsg, zSep, -1);
89346           zSep = ", ";
89347           sqlite3StrAccumAppend(&errMsg, zCol, -1);
89348         }
89349         sqlite3StrAccumAppend(&errMsg,
89350             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
89351         zErr = sqlite3StrAccumFinish(&errMsg);
89352         sqlite3HaltConstraint(pParse, onError, zErr, 0);
89353         sqlite3DbFree(errMsg.db, zErr);
89354         break;
89355       }
89356       case OE_Ignore: {
89357         assert( seenReplace==0 );
89358         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89359         break;
89360       }
89361       default: {
89362         Trigger *pTrigger = 0;
89363         assert( onError==OE_Replace );
89364         sqlite3MultiWrite(pParse);
89365         if( db->flags&SQLITE_RecTriggers ){
89366           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89367         }
89368         sqlite3GenerateRowDelete(
89369             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
89370         );
89371         seenReplace = 1;
89372         break;
89373       }
89374     }
89375     sqlite3VdbeJumpHere(v, j3);
89376     sqlite3ReleaseTempReg(pParse, regR);
89377   }
89378   
89379   if( pbMayReplace ){
89380     *pbMayReplace = seenReplace;
89381   }
89382 }
89383
89384 /*
89385 ** This routine generates code to finish the INSERT or UPDATE operation
89386 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
89387 ** A consecutive range of registers starting at regRowid contains the
89388 ** rowid and the content to be inserted.
89389 **
89390 ** The arguments to this routine should be the same as the first six
89391 ** arguments to sqlite3GenerateConstraintChecks.
89392 */
89393 SQLITE_PRIVATE void sqlite3CompleteInsertion(
89394   Parse *pParse,      /* The parser context */
89395   Table *pTab,        /* the table into which we are inserting */
89396   int baseCur,        /* Index of a read/write cursor pointing at pTab */
89397   int regRowid,       /* Range of content */
89398   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
89399   int isUpdate,       /* True for UPDATE, False for INSERT */
89400   int appendBias,     /* True if this is likely to be an append */
89401   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
89402 ){
89403   int i;
89404   Vdbe *v;
89405   int nIdx;
89406   Index *pIdx;
89407   u8 pik_flags;
89408   int regData;
89409   int regRec;
89410
89411   v = sqlite3GetVdbe(pParse);
89412   assert( v!=0 );
89413   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
89414   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
89415   for(i=nIdx-1; i>=0; i--){
89416     if( aRegIdx[i]==0 ) continue;
89417     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
89418     if( useSeekResult ){
89419       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
89420     }
89421   }
89422   regData = regRowid + 1;
89423   regRec = sqlite3GetTempReg(pParse);
89424   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
89425   sqlite3TableAffinityStr(v, pTab);
89426   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
89427   if( pParse->nested ){
89428     pik_flags = 0;
89429   }else{
89430     pik_flags = OPFLAG_NCHANGE;
89431     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
89432   }
89433   if( appendBias ){
89434     pik_flags |= OPFLAG_APPEND;
89435   }
89436   if( useSeekResult ){
89437     pik_flags |= OPFLAG_USESEEKRESULT;
89438   }
89439   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
89440   if( !pParse->nested ){
89441     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
89442   }
89443   sqlite3VdbeChangeP5(v, pik_flags);
89444 }
89445
89446 /*
89447 ** Generate code that will open cursors for a table and for all
89448 ** indices of that table.  The "baseCur" parameter is the cursor number used
89449 ** for the table.  Indices are opened on subsequent cursors.
89450 **
89451 ** Return the number of indices on the table.
89452 */
89453 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
89454   Parse *pParse,   /* Parsing context */
89455   Table *pTab,     /* Table to be opened */
89456   int baseCur,     /* Cursor number assigned to the table */
89457   int op           /* OP_OpenRead or OP_OpenWrite */
89458 ){
89459   int i;
89460   int iDb;
89461   Index *pIdx;
89462   Vdbe *v;
89463
89464   if( IsVirtual(pTab) ) return 0;
89465   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89466   v = sqlite3GetVdbe(pParse);
89467   assert( v!=0 );
89468   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
89469   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
89470     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89471     assert( pIdx->pSchema==pTab->pSchema );
89472     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
89473                       (char*)pKey, P4_KEYINFO_HANDOFF);
89474     VdbeComment((v, "%s", pIdx->zName));
89475   }
89476   if( pParse->nTab<baseCur+i ){
89477     pParse->nTab = baseCur+i;
89478   }
89479   return i-1;
89480 }
89481
89482
89483 #ifdef SQLITE_TEST
89484 /*
89485 ** The following global variable is incremented whenever the
89486 ** transfer optimization is used.  This is used for testing
89487 ** purposes only - to make sure the transfer optimization really
89488 ** is happening when it is suppose to.
89489 */
89490 SQLITE_API int sqlite3_xferopt_count;
89491 #endif /* SQLITE_TEST */
89492
89493
89494 #ifndef SQLITE_OMIT_XFER_OPT
89495 /*
89496 ** Check to collation names to see if they are compatible.
89497 */
89498 static int xferCompatibleCollation(const char *z1, const char *z2){
89499   if( z1==0 ){
89500     return z2==0;
89501   }
89502   if( z2==0 ){
89503     return 0;
89504   }
89505   return sqlite3StrICmp(z1, z2)==0;
89506 }
89507
89508
89509 /*
89510 ** Check to see if index pSrc is compatible as a source of data
89511 ** for index pDest in an insert transfer optimization.  The rules
89512 ** for a compatible index:
89513 **
89514 **    *   The index is over the same set of columns
89515 **    *   The same DESC and ASC markings occurs on all columns
89516 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
89517 **    *   The same collating sequence on each column
89518 */
89519 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
89520   int i;
89521   assert( pDest && pSrc );
89522   assert( pDest->pTable!=pSrc->pTable );
89523   if( pDest->nColumn!=pSrc->nColumn ){
89524     return 0;   /* Different number of columns */
89525   }
89526   if( pDest->onError!=pSrc->onError ){
89527     return 0;   /* Different conflict resolution strategies */
89528   }
89529   for(i=0; i<pSrc->nColumn; i++){
89530     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
89531       return 0;   /* Different columns indexed */
89532     }
89533     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
89534       return 0;   /* Different sort orders */
89535     }
89536     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
89537       return 0;   /* Different collating sequences */
89538     }
89539   }
89540
89541   /* If no test above fails then the indices must be compatible */
89542   return 1;
89543 }
89544
89545 /*
89546 ** Attempt the transfer optimization on INSERTs of the form
89547 **
89548 **     INSERT INTO tab1 SELECT * FROM tab2;
89549 **
89550 ** The xfer optimization transfers raw records from tab2 over to tab1.  
89551 ** Columns are not decoded and reassemblied, which greatly improves
89552 ** performance.  Raw index records are transferred in the same way.
89553 **
89554 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
89555 ** There are lots of rules for determining compatibility - see comments
89556 ** embedded in the code for details.
89557 **
89558 ** This routine returns TRUE if the optimization is guaranteed to be used.
89559 ** Sometimes the xfer optimization will only work if the destination table
89560 ** is empty - a factor that can only be determined at run-time.  In that
89561 ** case, this routine generates code for the xfer optimization but also
89562 ** does a test to see if the destination table is empty and jumps over the
89563 ** xfer optimization code if the test fails.  In that case, this routine
89564 ** returns FALSE so that the caller will know to go ahead and generate
89565 ** an unoptimized transfer.  This routine also returns FALSE if there
89566 ** is no chance that the xfer optimization can be applied.
89567 **
89568 ** This optimization is particularly useful at making VACUUM run faster.
89569 */
89570 static int xferOptimization(
89571   Parse *pParse,        /* Parser context */
89572   Table *pDest,         /* The table we are inserting into */
89573   Select *pSelect,      /* A SELECT statement to use as the data source */
89574   int onError,          /* How to handle constraint errors */
89575   int iDbDest           /* The database of pDest */
89576 ){
89577   ExprList *pEList;                /* The result set of the SELECT */
89578   Table *pSrc;                     /* The table in the FROM clause of SELECT */
89579   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
89580   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
89581   int i;                           /* Loop counter */
89582   int iDbSrc;                      /* The database of pSrc */
89583   int iSrc, iDest;                 /* Cursors from source and destination */
89584   int addr1, addr2;                /* Loop addresses */
89585   int emptyDestTest;               /* Address of test for empty pDest */
89586   int emptySrcTest;                /* Address of test for empty pSrc */
89587   Vdbe *v;                         /* The VDBE we are building */
89588   KeyInfo *pKey;                   /* Key information for an index */
89589   int regAutoinc;                  /* Memory register used by AUTOINC */
89590   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
89591   int regData, regRowid;           /* Registers holding data and rowid */
89592
89593   if( pSelect==0 ){
89594     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
89595   }
89596   if( sqlite3TriggerList(pParse, pDest) ){
89597     return 0;   /* tab1 must not have triggers */
89598   }
89599 #ifndef SQLITE_OMIT_VIRTUALTABLE
89600   if( pDest->tabFlags & TF_Virtual ){
89601     return 0;   /* tab1 must not be a virtual table */
89602   }
89603 #endif
89604   if( onError==OE_Default ){
89605     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
89606     if( onError==OE_Default ) onError = OE_Abort;
89607   }
89608   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
89609   if( pSelect->pSrc->nSrc!=1 ){
89610     return 0;   /* FROM clause must have exactly one term */
89611   }
89612   if( pSelect->pSrc->a[0].pSelect ){
89613     return 0;   /* FROM clause cannot contain a subquery */
89614   }
89615   if( pSelect->pWhere ){
89616     return 0;   /* SELECT may not have a WHERE clause */
89617   }
89618   if( pSelect->pOrderBy ){
89619     return 0;   /* SELECT may not have an ORDER BY clause */
89620   }
89621   /* Do not need to test for a HAVING clause.  If HAVING is present but
89622   ** there is no ORDER BY, we will get an error. */
89623   if( pSelect->pGroupBy ){
89624     return 0;   /* SELECT may not have a GROUP BY clause */
89625   }
89626   if( pSelect->pLimit ){
89627     return 0;   /* SELECT may not have a LIMIT clause */
89628   }
89629   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
89630   if( pSelect->pPrior ){
89631     return 0;   /* SELECT may not be a compound query */
89632   }
89633   if( pSelect->selFlags & SF_Distinct ){
89634     return 0;   /* SELECT may not be DISTINCT */
89635   }
89636   pEList = pSelect->pEList;
89637   assert( pEList!=0 );
89638   if( pEList->nExpr!=1 ){
89639     return 0;   /* The result set must have exactly one column */
89640   }
89641   assert( pEList->a[0].pExpr );
89642   if( pEList->a[0].pExpr->op!=TK_ALL ){
89643     return 0;   /* The result set must be the special operator "*" */
89644   }
89645
89646   /* At this point we have established that the statement is of the
89647   ** correct syntactic form to participate in this optimization.  Now
89648   ** we have to check the semantics.
89649   */
89650   pItem = pSelect->pSrc->a;
89651   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
89652   if( pSrc==0 ){
89653     return 0;   /* FROM clause does not contain a real table */
89654   }
89655   if( pSrc==pDest ){
89656     return 0;   /* tab1 and tab2 may not be the same table */
89657   }
89658 #ifndef SQLITE_OMIT_VIRTUALTABLE
89659   if( pSrc->tabFlags & TF_Virtual ){
89660     return 0;   /* tab2 must not be a virtual table */
89661   }
89662 #endif
89663   if( pSrc->pSelect ){
89664     return 0;   /* tab2 may not be a view */
89665   }
89666   if( pDest->nCol!=pSrc->nCol ){
89667     return 0;   /* Number of columns must be the same in tab1 and tab2 */
89668   }
89669   if( pDest->iPKey!=pSrc->iPKey ){
89670     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
89671   }
89672   for(i=0; i<pDest->nCol; i++){
89673     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
89674       return 0;    /* Affinity must be the same on all columns */
89675     }
89676     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
89677       return 0;    /* Collating sequence must be the same on all columns */
89678     }
89679     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
89680       return 0;    /* tab2 must be NOT NULL if tab1 is */
89681     }
89682   }
89683   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
89684     if( pDestIdx->onError!=OE_None ){
89685       destHasUniqueIdx = 1;
89686     }
89687     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
89688       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
89689     }
89690     if( pSrcIdx==0 ){
89691       return 0;    /* pDestIdx has no corresponding index in pSrc */
89692     }
89693   }
89694 #ifndef SQLITE_OMIT_CHECK
89695   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
89696     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
89697   }
89698 #endif
89699 #ifndef SQLITE_OMIT_FOREIGN_KEY
89700   /* Disallow the transfer optimization if the destination table constains
89701   ** any foreign key constraints.  This is more restrictive than necessary.
89702   ** But the main beneficiary of the transfer optimization is the VACUUM 
89703   ** command, and the VACUUM command disables foreign key constraints.  So
89704   ** the extra complication to make this rule less restrictive is probably
89705   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
89706   */
89707   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
89708     return 0;
89709   }
89710 #endif
89711   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
89712     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
89713   }
89714
89715   /* If we get this far, it means that the xfer optimization is at
89716   ** least a possibility, though it might only work if the destination
89717   ** table (tab1) is initially empty.
89718   */
89719 #ifdef SQLITE_TEST
89720   sqlite3_xferopt_count++;
89721 #endif
89722   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
89723   v = sqlite3GetVdbe(pParse);
89724   sqlite3CodeVerifySchema(pParse, iDbSrc);
89725   iSrc = pParse->nTab++;
89726   iDest = pParse->nTab++;
89727   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
89728   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
89729   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
89730    || destHasUniqueIdx                              /* (2) */
89731    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
89732   ){
89733     /* In some circumstances, we are able to run the xfer optimization
89734     ** only if the destination table is initially empty.  This code makes
89735     ** that determination.  Conditions under which the destination must
89736     ** be empty:
89737     **
89738     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
89739     **     (If the destination is not initially empty, the rowid fields
89740     **     of index entries might need to change.)
89741     **
89742     ** (2) The destination has a unique index.  (The xfer optimization 
89743     **     is unable to test uniqueness.)
89744     **
89745     ** (3) onError is something other than OE_Abort and OE_Rollback.
89746     */
89747     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
89748     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89749     sqlite3VdbeJumpHere(v, addr1);
89750   }else{
89751     emptyDestTest = 0;
89752   }
89753   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
89754   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
89755   regData = sqlite3GetTempReg(pParse);
89756   regRowid = sqlite3GetTempReg(pParse);
89757   if( pDest->iPKey>=0 ){
89758     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
89759     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
89760     sqlite3HaltConstraint(
89761         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
89762     sqlite3VdbeJumpHere(v, addr2);
89763     autoIncStep(pParse, regAutoinc, regRowid);
89764   }else if( pDest->pIndex==0 ){
89765     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
89766   }else{
89767     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
89768     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
89769   }
89770   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
89771   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
89772   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
89773   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
89774   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
89775   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
89776     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
89777       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
89778     }
89779     assert( pSrcIdx );
89780     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
89781     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89782     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
89783     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
89784                       (char*)pKey, P4_KEYINFO_HANDOFF);
89785     VdbeComment((v, "%s", pSrcIdx->zName));
89786     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
89787     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
89788                       (char*)pKey, P4_KEYINFO_HANDOFF);
89789     VdbeComment((v, "%s", pDestIdx->zName));
89790     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
89791     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
89792     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
89793     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
89794     sqlite3VdbeJumpHere(v, addr1);
89795   }
89796   sqlite3VdbeJumpHere(v, emptySrcTest);
89797   sqlite3ReleaseTempReg(pParse, regRowid);
89798   sqlite3ReleaseTempReg(pParse, regData);
89799   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
89800   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89801   if( emptyDestTest ){
89802     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
89803     sqlite3VdbeJumpHere(v, emptyDestTest);
89804     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89805     return 0;
89806   }else{
89807     return 1;
89808   }
89809 }
89810 #endif /* SQLITE_OMIT_XFER_OPT */
89811
89812 /************** End of insert.c **********************************************/
89813 /************** Begin file legacy.c ******************************************/
89814 /*
89815 ** 2001 September 15
89816 **
89817 ** The author disclaims copyright to this source code.  In place of
89818 ** a legal notice, here is a blessing:
89819 **
89820 **    May you do good and not evil.
89821 **    May you find forgiveness for yourself and forgive others.
89822 **    May you share freely, never taking more than you give.
89823 **
89824 *************************************************************************
89825 ** Main file for the SQLite library.  The routines in this file
89826 ** implement the programmer interface to the library.  Routines in
89827 ** other files are for internal use by SQLite and should not be
89828 ** accessed by users of the library.
89829 */
89830
89831
89832 /*
89833 ** Execute SQL code.  Return one of the SQLITE_ success/failure
89834 ** codes.  Also write an error message into memory obtained from
89835 ** malloc() and make *pzErrMsg point to that message.
89836 **
89837 ** If the SQL is a query, then for each row in the query result
89838 ** the xCallback() function is called.  pArg becomes the first
89839 ** argument to xCallback().  If xCallback=NULL then no callback
89840 ** is invoked, even for queries.
89841 */
89842 SQLITE_API int sqlite3_exec(
89843   sqlite3 *db,                /* The database on which the SQL executes */
89844   const char *zSql,           /* The SQL to be executed */
89845   sqlite3_callback xCallback, /* Invoke this callback routine */
89846   void *pArg,                 /* First argument to xCallback() */
89847   char **pzErrMsg             /* Write error messages here */
89848 ){
89849   int rc = SQLITE_OK;         /* Return code */
89850   const char *zLeftover;      /* Tail of unprocessed SQL */
89851   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
89852   char **azCols = 0;          /* Names of result columns */
89853   int nRetry = 0;             /* Number of retry attempts */
89854   int callbackIsInit;         /* True if callback data is initialized */
89855
89856   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
89857   if( zSql==0 ) zSql = "";
89858
89859   sqlite3_mutex_enter(db->mutex);
89860   sqlite3Error(db, SQLITE_OK, 0);
89861   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
89862     int nCol;
89863     char **azVals = 0;
89864
89865     pStmt = 0;
89866     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
89867     assert( rc==SQLITE_OK || pStmt==0 );
89868     if( rc!=SQLITE_OK ){
89869       continue;
89870     }
89871     if( !pStmt ){
89872       /* this happens for a comment or white-space */
89873       zSql = zLeftover;
89874       continue;
89875     }
89876
89877     callbackIsInit = 0;
89878     nCol = sqlite3_column_count(pStmt);
89879
89880     while( 1 ){
89881       int i;
89882       rc = sqlite3_step(pStmt);
89883
89884       /* Invoke the callback function if required */
89885       if( xCallback && (SQLITE_ROW==rc || 
89886           (SQLITE_DONE==rc && !callbackIsInit
89887                            && db->flags&SQLITE_NullCallback)) ){
89888         if( !callbackIsInit ){
89889           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
89890           if( azCols==0 ){
89891             goto exec_out;
89892           }
89893           for(i=0; i<nCol; i++){
89894             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
89895             /* sqlite3VdbeSetColName() installs column names as UTF8
89896             ** strings so there is no way for sqlite3_column_name() to fail. */
89897             assert( azCols[i]!=0 );
89898           }
89899           callbackIsInit = 1;
89900         }
89901         if( rc==SQLITE_ROW ){
89902           azVals = &azCols[nCol];
89903           for(i=0; i<nCol; i++){
89904             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
89905             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
89906               db->mallocFailed = 1;
89907               goto exec_out;
89908             }
89909           }
89910         }
89911         if( xCallback(pArg, nCol, azVals, azCols) ){
89912           rc = SQLITE_ABORT;
89913           sqlite3VdbeFinalize((Vdbe *)pStmt);
89914           pStmt = 0;
89915           sqlite3Error(db, SQLITE_ABORT, 0);
89916           goto exec_out;
89917         }
89918       }
89919
89920       if( rc!=SQLITE_ROW ){
89921         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
89922         pStmt = 0;
89923         if( rc!=SQLITE_SCHEMA ){
89924           nRetry = 0;
89925           zSql = zLeftover;
89926           while( sqlite3Isspace(zSql[0]) ) zSql++;
89927         }
89928         break;
89929       }
89930     }
89931
89932     sqlite3DbFree(db, azCols);
89933     azCols = 0;
89934   }
89935
89936 exec_out:
89937   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
89938   sqlite3DbFree(db, azCols);
89939
89940   rc = sqlite3ApiExit(db, rc);
89941   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
89942     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
89943     *pzErrMsg = sqlite3Malloc(nErrMsg);
89944     if( *pzErrMsg ){
89945       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
89946     }else{
89947       rc = SQLITE_NOMEM;
89948       sqlite3Error(db, SQLITE_NOMEM, 0);
89949     }
89950   }else if( pzErrMsg ){
89951     *pzErrMsg = 0;
89952   }
89953
89954   assert( (rc&db->errMask)==rc );
89955   sqlite3_mutex_leave(db->mutex);
89956   return rc;
89957 }
89958
89959 /************** End of legacy.c **********************************************/
89960 /************** Begin file loadext.c *****************************************/
89961 /*
89962 ** 2006 June 7
89963 **
89964 ** The author disclaims copyright to this source code.  In place of
89965 ** a legal notice, here is a blessing:
89966 **
89967 **    May you do good and not evil.
89968 **    May you find forgiveness for yourself and forgive others.
89969 **    May you share freely, never taking more than you give.
89970 **
89971 *************************************************************************
89972 ** This file contains code used to dynamically load extensions into
89973 ** the SQLite library.
89974 */
89975
89976 #ifndef SQLITE_CORE
89977   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
89978 #endif
89979 /************** Include sqlite3ext.h in the middle of loadext.c **************/
89980 /************** Begin file sqlite3ext.h **************************************/
89981 /*
89982 ** 2006 June 7
89983 **
89984 ** The author disclaims copyright to this source code.  In place of
89985 ** a legal notice, here is a blessing:
89986 **
89987 **    May you do good and not evil.
89988 **    May you find forgiveness for yourself and forgive others.
89989 **    May you share freely, never taking more than you give.
89990 **
89991 *************************************************************************
89992 ** This header file defines the SQLite interface for use by
89993 ** shared libraries that want to be imported as extensions into
89994 ** an SQLite instance.  Shared libraries that intend to be loaded
89995 ** as extensions by SQLite should #include this file instead of 
89996 ** sqlite3.h.
89997 */
89998 #ifndef _SQLITE3EXT_H_
89999 #define _SQLITE3EXT_H_
90000
90001 typedef struct sqlite3_api_routines sqlite3_api_routines;
90002
90003 /*
90004 ** The following structure holds pointers to all of the SQLite API
90005 ** routines.
90006 **
90007 ** WARNING:  In order to maintain backwards compatibility, add new
90008 ** interfaces to the end of this structure only.  If you insert new
90009 ** interfaces in the middle of this structure, then older different
90010 ** versions of SQLite will not be able to load each others' shared
90011 ** libraries!
90012 */
90013 struct sqlite3_api_routines {
90014   void * (*aggregate_context)(sqlite3_context*,int nBytes);
90015   int  (*aggregate_count)(sqlite3_context*);
90016   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
90017   int  (*bind_double)(sqlite3_stmt*,int,double);
90018   int  (*bind_int)(sqlite3_stmt*,int,int);
90019   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
90020   int  (*bind_null)(sqlite3_stmt*,int);
90021   int  (*bind_parameter_count)(sqlite3_stmt*);
90022   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
90023   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
90024   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
90025   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
90026   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
90027   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
90028   int  (*busy_timeout)(sqlite3*,int ms);
90029   int  (*changes)(sqlite3*);
90030   int  (*close)(sqlite3*);
90031   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
90032                            int eTextRep,const char*));
90033   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
90034                              int eTextRep,const void*));
90035   const void * (*column_blob)(sqlite3_stmt*,int iCol);
90036   int  (*column_bytes)(sqlite3_stmt*,int iCol);
90037   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
90038   int  (*column_count)(sqlite3_stmt*pStmt);
90039   const char * (*column_database_name)(sqlite3_stmt*,int);
90040   const void * (*column_database_name16)(sqlite3_stmt*,int);
90041   const char * (*column_decltype)(sqlite3_stmt*,int i);
90042   const void * (*column_decltype16)(sqlite3_stmt*,int);
90043   double  (*column_double)(sqlite3_stmt*,int iCol);
90044   int  (*column_int)(sqlite3_stmt*,int iCol);
90045   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
90046   const char * (*column_name)(sqlite3_stmt*,int);
90047   const void * (*column_name16)(sqlite3_stmt*,int);
90048   const char * (*column_origin_name)(sqlite3_stmt*,int);
90049   const void * (*column_origin_name16)(sqlite3_stmt*,int);
90050   const char * (*column_table_name)(sqlite3_stmt*,int);
90051   const void * (*column_table_name16)(sqlite3_stmt*,int);
90052   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
90053   const void * (*column_text16)(sqlite3_stmt*,int iCol);
90054   int  (*column_type)(sqlite3_stmt*,int iCol);
90055   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
90056   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
90057   int  (*complete)(const char*sql);
90058   int  (*complete16)(const void*sql);
90059   int  (*create_collation)(sqlite3*,const char*,int,void*,
90060                            int(*)(void*,int,const void*,int,const void*));
90061   int  (*create_collation16)(sqlite3*,const void*,int,void*,
90062                              int(*)(void*,int,const void*,int,const void*));
90063   int  (*create_function)(sqlite3*,const char*,int,int,void*,
90064                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90065                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90066                           void (*xFinal)(sqlite3_context*));
90067   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
90068                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90069                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90070                             void (*xFinal)(sqlite3_context*));
90071   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
90072   int  (*data_count)(sqlite3_stmt*pStmt);
90073   sqlite3 * (*db_handle)(sqlite3_stmt*);
90074   int (*declare_vtab)(sqlite3*,const char*);
90075   int  (*enable_shared_cache)(int);
90076   int  (*errcode)(sqlite3*db);
90077   const char * (*errmsg)(sqlite3*);
90078   const void * (*errmsg16)(sqlite3*);
90079   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
90080   int  (*expired)(sqlite3_stmt*);
90081   int  (*finalize)(sqlite3_stmt*pStmt);
90082   void  (*free)(void*);
90083   void  (*free_table)(char**result);
90084   int  (*get_autocommit)(sqlite3*);
90085   void * (*get_auxdata)(sqlite3_context*,int);
90086   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
90087   int  (*global_recover)(void);
90088   void  (*interruptx)(sqlite3*);
90089   sqlite_int64  (*last_insert_rowid)(sqlite3*);
90090   const char * (*libversion)(void);
90091   int  (*libversion_number)(void);
90092   void *(*malloc)(int);
90093   char * (*mprintf)(const char*,...);
90094   int  (*open)(const char*,sqlite3**);
90095   int  (*open16)(const void*,sqlite3**);
90096   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
90097   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
90098   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
90099   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
90100   void *(*realloc)(void*,int);
90101   int  (*reset)(sqlite3_stmt*pStmt);
90102   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
90103   void  (*result_double)(sqlite3_context*,double);
90104   void  (*result_error)(sqlite3_context*,const char*,int);
90105   void  (*result_error16)(sqlite3_context*,const void*,int);
90106   void  (*result_int)(sqlite3_context*,int);
90107   void  (*result_int64)(sqlite3_context*,sqlite_int64);
90108   void  (*result_null)(sqlite3_context*);
90109   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
90110   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
90111   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
90112   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
90113   void  (*result_value)(sqlite3_context*,sqlite3_value*);
90114   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
90115   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
90116                          const char*,const char*),void*);
90117   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
90118   char * (*snprintf)(int,char*,const char*,...);
90119   int  (*step)(sqlite3_stmt*);
90120   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
90121                                 char const**,char const**,int*,int*,int*);
90122   void  (*thread_cleanup)(void);
90123   int  (*total_changes)(sqlite3*);
90124   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
90125   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
90126   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
90127                                          sqlite_int64),void*);
90128   void * (*user_data)(sqlite3_context*);
90129   const void * (*value_blob)(sqlite3_value*);
90130   int  (*value_bytes)(sqlite3_value*);
90131   int  (*value_bytes16)(sqlite3_value*);
90132   double  (*value_double)(sqlite3_value*);
90133   int  (*value_int)(sqlite3_value*);
90134   sqlite_int64  (*value_int64)(sqlite3_value*);
90135   int  (*value_numeric_type)(sqlite3_value*);
90136   const unsigned char * (*value_text)(sqlite3_value*);
90137   const void * (*value_text16)(sqlite3_value*);
90138   const void * (*value_text16be)(sqlite3_value*);
90139   const void * (*value_text16le)(sqlite3_value*);
90140   int  (*value_type)(sqlite3_value*);
90141   char *(*vmprintf)(const char*,va_list);
90142   /* Added ??? */
90143   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
90144   /* Added by 3.3.13 */
90145   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
90146   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
90147   int (*clear_bindings)(sqlite3_stmt*);
90148   /* Added by 3.4.1 */
90149   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
90150                           void (*xDestroy)(void *));
90151   /* Added by 3.5.0 */
90152   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
90153   int (*blob_bytes)(sqlite3_blob*);
90154   int (*blob_close)(sqlite3_blob*);
90155   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
90156                    int,sqlite3_blob**);
90157   int (*blob_read)(sqlite3_blob*,void*,int,int);
90158   int (*blob_write)(sqlite3_blob*,const void*,int,int);
90159   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
90160                              int(*)(void*,int,const void*,int,const void*),
90161                              void(*)(void*));
90162   int (*file_control)(sqlite3*,const char*,int,void*);
90163   sqlite3_int64 (*memory_highwater)(int);
90164   sqlite3_int64 (*memory_used)(void);
90165   sqlite3_mutex *(*mutex_alloc)(int);
90166   void (*mutex_enter)(sqlite3_mutex*);
90167   void (*mutex_free)(sqlite3_mutex*);
90168   void (*mutex_leave)(sqlite3_mutex*);
90169   int (*mutex_try)(sqlite3_mutex*);
90170   int (*open_v2)(const char*,sqlite3**,int,const char*);
90171   int (*release_memory)(int);
90172   void (*result_error_nomem)(sqlite3_context*);
90173   void (*result_error_toobig)(sqlite3_context*);
90174   int (*sleep)(int);
90175   void (*soft_heap_limit)(int);
90176   sqlite3_vfs *(*vfs_find)(const char*);
90177   int (*vfs_register)(sqlite3_vfs*,int);
90178   int (*vfs_unregister)(sqlite3_vfs*);
90179   int (*xthreadsafe)(void);
90180   void (*result_zeroblob)(sqlite3_context*,int);
90181   void (*result_error_code)(sqlite3_context*,int);
90182   int (*test_control)(int, ...);
90183   void (*randomness)(int,void*);
90184   sqlite3 *(*context_db_handle)(sqlite3_context*);
90185   int (*extended_result_codes)(sqlite3*,int);
90186   int (*limit)(sqlite3*,int,int);
90187   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
90188   const char *(*sql)(sqlite3_stmt*);
90189   int (*status)(int,int*,int*,int);
90190   int (*backup_finish)(sqlite3_backup*);
90191   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
90192   int (*backup_pagecount)(sqlite3_backup*);
90193   int (*backup_remaining)(sqlite3_backup*);
90194   int (*backup_step)(sqlite3_backup*,int);
90195   const char *(*compileoption_get)(int);
90196   int (*compileoption_used)(const char*);
90197   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
90198                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90199                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90200                             void (*xFinal)(sqlite3_context*),
90201                             void(*xDestroy)(void*));
90202   int (*db_config)(sqlite3*,int,...);
90203   sqlite3_mutex *(*db_mutex)(sqlite3*);
90204   int (*db_status)(sqlite3*,int,int*,int*,int);
90205   int (*extended_errcode)(sqlite3*);
90206   void (*log)(int,const char*,...);
90207   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
90208   const char *(*sourceid)(void);
90209   int (*stmt_status)(sqlite3_stmt*,int,int);
90210   int (*strnicmp)(const char*,const char*,int);
90211   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
90212   int (*wal_autocheckpoint)(sqlite3*,int);
90213   int (*wal_checkpoint)(sqlite3*,const char*);
90214   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
90215   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
90216   int (*vtab_config)(sqlite3*,int op,...);
90217   int (*vtab_on_conflict)(sqlite3*);
90218 };
90219
90220 /*
90221 ** The following macros redefine the API routines so that they are
90222 ** redirected throught the global sqlite3_api structure.
90223 **
90224 ** This header file is also used by the loadext.c source file
90225 ** (part of the main SQLite library - not an extension) so that
90226 ** it can get access to the sqlite3_api_routines structure
90227 ** definition.  But the main library does not want to redefine
90228 ** the API.  So the redefinition macros are only valid if the
90229 ** SQLITE_CORE macros is undefined.
90230 */
90231 #ifndef SQLITE_CORE
90232 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
90233 #ifndef SQLITE_OMIT_DEPRECATED
90234 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
90235 #endif
90236 #define sqlite3_bind_blob              sqlite3_api->bind_blob
90237 #define sqlite3_bind_double            sqlite3_api->bind_double
90238 #define sqlite3_bind_int               sqlite3_api->bind_int
90239 #define sqlite3_bind_int64             sqlite3_api->bind_int64
90240 #define sqlite3_bind_null              sqlite3_api->bind_null
90241 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
90242 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
90243 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
90244 #define sqlite3_bind_text              sqlite3_api->bind_text
90245 #define sqlite3_bind_text16            sqlite3_api->bind_text16
90246 #define sqlite3_bind_value             sqlite3_api->bind_value
90247 #define sqlite3_busy_handler           sqlite3_api->busy_handler
90248 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
90249 #define sqlite3_changes                sqlite3_api->changes
90250 #define sqlite3_close                  sqlite3_api->close
90251 #define sqlite3_collation_needed       sqlite3_api->collation_needed
90252 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
90253 #define sqlite3_column_blob            sqlite3_api->column_blob
90254 #define sqlite3_column_bytes           sqlite3_api->column_bytes
90255 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
90256 #define sqlite3_column_count           sqlite3_api->column_count
90257 #define sqlite3_column_database_name   sqlite3_api->column_database_name
90258 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
90259 #define sqlite3_column_decltype        sqlite3_api->column_decltype
90260 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
90261 #define sqlite3_column_double          sqlite3_api->column_double
90262 #define sqlite3_column_int             sqlite3_api->column_int
90263 #define sqlite3_column_int64           sqlite3_api->column_int64
90264 #define sqlite3_column_name            sqlite3_api->column_name
90265 #define sqlite3_column_name16          sqlite3_api->column_name16
90266 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
90267 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
90268 #define sqlite3_column_table_name      sqlite3_api->column_table_name
90269 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
90270 #define sqlite3_column_text            sqlite3_api->column_text
90271 #define sqlite3_column_text16          sqlite3_api->column_text16
90272 #define sqlite3_column_type            sqlite3_api->column_type
90273 #define sqlite3_column_value           sqlite3_api->column_value
90274 #define sqlite3_commit_hook            sqlite3_api->commit_hook
90275 #define sqlite3_complete               sqlite3_api->complete
90276 #define sqlite3_complete16             sqlite3_api->complete16
90277 #define sqlite3_create_collation       sqlite3_api->create_collation
90278 #define sqlite3_create_collation16     sqlite3_api->create_collation16
90279 #define sqlite3_create_function        sqlite3_api->create_function
90280 #define sqlite3_create_function16      sqlite3_api->create_function16
90281 #define sqlite3_create_module          sqlite3_api->create_module
90282 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
90283 #define sqlite3_data_count             sqlite3_api->data_count
90284 #define sqlite3_db_handle              sqlite3_api->db_handle
90285 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
90286 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
90287 #define sqlite3_errcode                sqlite3_api->errcode
90288 #define sqlite3_errmsg                 sqlite3_api->errmsg
90289 #define sqlite3_errmsg16               sqlite3_api->errmsg16
90290 #define sqlite3_exec                   sqlite3_api->exec
90291 #ifndef SQLITE_OMIT_DEPRECATED
90292 #define sqlite3_expired                sqlite3_api->expired
90293 #endif
90294 #define sqlite3_finalize               sqlite3_api->finalize
90295 #define sqlite3_free                   sqlite3_api->free
90296 #define sqlite3_free_table             sqlite3_api->free_table
90297 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
90298 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
90299 #define sqlite3_get_table              sqlite3_api->get_table
90300 #ifndef SQLITE_OMIT_DEPRECATED
90301 #define sqlite3_global_recover         sqlite3_api->global_recover
90302 #endif
90303 #define sqlite3_interrupt              sqlite3_api->interruptx
90304 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
90305 #define sqlite3_libversion             sqlite3_api->libversion
90306 #define sqlite3_libversion_number      sqlite3_api->libversion_number
90307 #define sqlite3_malloc                 sqlite3_api->malloc
90308 #define sqlite3_mprintf                sqlite3_api->mprintf
90309 #define sqlite3_open                   sqlite3_api->open
90310 #define sqlite3_open16                 sqlite3_api->open16
90311 #define sqlite3_prepare                sqlite3_api->prepare
90312 #define sqlite3_prepare16              sqlite3_api->prepare16
90313 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
90314 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
90315 #define sqlite3_profile                sqlite3_api->profile
90316 #define sqlite3_progress_handler       sqlite3_api->progress_handler
90317 #define sqlite3_realloc                sqlite3_api->realloc
90318 #define sqlite3_reset                  sqlite3_api->reset
90319 #define sqlite3_result_blob            sqlite3_api->result_blob
90320 #define sqlite3_result_double          sqlite3_api->result_double
90321 #define sqlite3_result_error           sqlite3_api->result_error
90322 #define sqlite3_result_error16         sqlite3_api->result_error16
90323 #define sqlite3_result_int             sqlite3_api->result_int
90324 #define sqlite3_result_int64           sqlite3_api->result_int64
90325 #define sqlite3_result_null            sqlite3_api->result_null
90326 #define sqlite3_result_text            sqlite3_api->result_text
90327 #define sqlite3_result_text16          sqlite3_api->result_text16
90328 #define sqlite3_result_text16be        sqlite3_api->result_text16be
90329 #define sqlite3_result_text16le        sqlite3_api->result_text16le
90330 #define sqlite3_result_value           sqlite3_api->result_value
90331 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
90332 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
90333 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
90334 #define sqlite3_snprintf               sqlite3_api->snprintf
90335 #define sqlite3_step                   sqlite3_api->step
90336 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
90337 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
90338 #define sqlite3_total_changes          sqlite3_api->total_changes
90339 #define sqlite3_trace                  sqlite3_api->trace
90340 #ifndef SQLITE_OMIT_DEPRECATED
90341 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
90342 #endif
90343 #define sqlite3_update_hook            sqlite3_api->update_hook
90344 #define sqlite3_user_data              sqlite3_api->user_data
90345 #define sqlite3_value_blob             sqlite3_api->value_blob
90346 #define sqlite3_value_bytes            sqlite3_api->value_bytes
90347 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
90348 #define sqlite3_value_double           sqlite3_api->value_double
90349 #define sqlite3_value_int              sqlite3_api->value_int
90350 #define sqlite3_value_int64            sqlite3_api->value_int64
90351 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
90352 #define sqlite3_value_text             sqlite3_api->value_text
90353 #define sqlite3_value_text16           sqlite3_api->value_text16
90354 #define sqlite3_value_text16be         sqlite3_api->value_text16be
90355 #define sqlite3_value_text16le         sqlite3_api->value_text16le
90356 #define sqlite3_value_type             sqlite3_api->value_type
90357 #define sqlite3_vmprintf               sqlite3_api->vmprintf
90358 #define sqlite3_overload_function      sqlite3_api->overload_function
90359 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
90360 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
90361 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
90362 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
90363 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
90364 #define sqlite3_blob_close             sqlite3_api->blob_close
90365 #define sqlite3_blob_open              sqlite3_api->blob_open
90366 #define sqlite3_blob_read              sqlite3_api->blob_read
90367 #define sqlite3_blob_write             sqlite3_api->blob_write
90368 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
90369 #define sqlite3_file_control           sqlite3_api->file_control
90370 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
90371 #define sqlite3_memory_used            sqlite3_api->memory_used
90372 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
90373 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
90374 #define sqlite3_mutex_free             sqlite3_api->mutex_free
90375 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
90376 #define sqlite3_mutex_try              sqlite3_api->mutex_try
90377 #define sqlite3_open_v2                sqlite3_api->open_v2
90378 #define sqlite3_release_memory         sqlite3_api->release_memory
90379 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
90380 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
90381 #define sqlite3_sleep                  sqlite3_api->sleep
90382 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
90383 #define sqlite3_vfs_find               sqlite3_api->vfs_find
90384 #define sqlite3_vfs_register           sqlite3_api->vfs_register
90385 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
90386 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
90387 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
90388 #define sqlite3_result_error_code      sqlite3_api->result_error_code
90389 #define sqlite3_test_control           sqlite3_api->test_control
90390 #define sqlite3_randomness             sqlite3_api->randomness
90391 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
90392 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
90393 #define sqlite3_limit                  sqlite3_api->limit
90394 #define sqlite3_next_stmt              sqlite3_api->next_stmt
90395 #define sqlite3_sql                    sqlite3_api->sql
90396 #define sqlite3_status                 sqlite3_api->status
90397 #define sqlite3_backup_finish          sqlite3_api->backup_finish
90398 #define sqlite3_backup_init            sqlite3_api->backup_init
90399 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
90400 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
90401 #define sqlite3_backup_step            sqlite3_api->backup_step
90402 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
90403 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
90404 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
90405 #define sqlite3_db_config              sqlite3_api->db_config
90406 #define sqlite3_db_mutex               sqlite3_api->db_mutex
90407 #define sqlite3_db_status              sqlite3_api->db_status
90408 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
90409 #define sqlite3_log                    sqlite3_api->log
90410 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
90411 #define sqlite3_sourceid               sqlite3_api->sourceid
90412 #define sqlite3_stmt_status            sqlite3_api->stmt_status
90413 #define sqlite3_strnicmp               sqlite3_api->strnicmp
90414 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
90415 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
90416 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
90417 #define sqlite3_wal_hook               sqlite3_api->wal_hook
90418 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
90419 #define sqlite3_vtab_config            sqlite3_api->vtab_config
90420 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
90421 #endif /* SQLITE_CORE */
90422
90423 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
90424 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
90425
90426 #endif /* _SQLITE3EXT_H_ */
90427
90428 /************** End of sqlite3ext.h ******************************************/
90429 /************** Continuing where we left off in loadext.c ********************/
90430 /* #include <string.h> */
90431
90432 #ifndef SQLITE_OMIT_LOAD_EXTENSION
90433
90434 /*
90435 ** Some API routines are omitted when various features are
90436 ** excluded from a build of SQLite.  Substitute a NULL pointer
90437 ** for any missing APIs.
90438 */
90439 #ifndef SQLITE_ENABLE_COLUMN_METADATA
90440 # define sqlite3_column_database_name   0
90441 # define sqlite3_column_database_name16 0
90442 # define sqlite3_column_table_name      0
90443 # define sqlite3_column_table_name16    0
90444 # define sqlite3_column_origin_name     0
90445 # define sqlite3_column_origin_name16   0
90446 # define sqlite3_table_column_metadata  0
90447 #endif
90448
90449 #ifdef SQLITE_OMIT_AUTHORIZATION
90450 # define sqlite3_set_authorizer         0
90451 #endif
90452
90453 #ifdef SQLITE_OMIT_UTF16
90454 # define sqlite3_bind_text16            0
90455 # define sqlite3_collation_needed16     0
90456 # define sqlite3_column_decltype16      0
90457 # define sqlite3_column_name16          0
90458 # define sqlite3_column_text16          0
90459 # define sqlite3_complete16             0
90460 # define sqlite3_create_collation16     0
90461 # define sqlite3_create_function16      0
90462 # define sqlite3_errmsg16               0
90463 # define sqlite3_open16                 0
90464 # define sqlite3_prepare16              0
90465 # define sqlite3_prepare16_v2           0
90466 # define sqlite3_result_error16         0
90467 # define sqlite3_result_text16          0
90468 # define sqlite3_result_text16be        0
90469 # define sqlite3_result_text16le        0
90470 # define sqlite3_value_text16           0
90471 # define sqlite3_value_text16be         0
90472 # define sqlite3_value_text16le         0
90473 # define sqlite3_column_database_name16 0
90474 # define sqlite3_column_table_name16    0
90475 # define sqlite3_column_origin_name16   0
90476 #endif
90477
90478 #ifdef SQLITE_OMIT_COMPLETE
90479 # define sqlite3_complete 0
90480 # define sqlite3_complete16 0
90481 #endif
90482
90483 #ifdef SQLITE_OMIT_DECLTYPE
90484 # define sqlite3_column_decltype16      0
90485 # define sqlite3_column_decltype        0
90486 #endif
90487
90488 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
90489 # define sqlite3_progress_handler 0
90490 #endif
90491
90492 #ifdef SQLITE_OMIT_VIRTUALTABLE
90493 # define sqlite3_create_module 0
90494 # define sqlite3_create_module_v2 0
90495 # define sqlite3_declare_vtab 0
90496 # define sqlite3_vtab_config 0
90497 # define sqlite3_vtab_on_conflict 0
90498 #endif
90499
90500 #ifdef SQLITE_OMIT_SHARED_CACHE
90501 # define sqlite3_enable_shared_cache 0
90502 #endif
90503
90504 #ifdef SQLITE_OMIT_TRACE
90505 # define sqlite3_profile       0
90506 # define sqlite3_trace         0
90507 #endif
90508
90509 #ifdef SQLITE_OMIT_GET_TABLE
90510 # define sqlite3_free_table    0
90511 # define sqlite3_get_table     0
90512 #endif
90513
90514 #ifdef SQLITE_OMIT_INCRBLOB
90515 #define sqlite3_bind_zeroblob  0
90516 #define sqlite3_blob_bytes     0
90517 #define sqlite3_blob_close     0
90518 #define sqlite3_blob_open      0
90519 #define sqlite3_blob_read      0
90520 #define sqlite3_blob_write     0
90521 #define sqlite3_blob_reopen    0
90522 #endif
90523
90524 /*
90525 ** The following structure contains pointers to all SQLite API routines.
90526 ** A pointer to this structure is passed into extensions when they are
90527 ** loaded so that the extension can make calls back into the SQLite
90528 ** library.
90529 **
90530 ** When adding new APIs, add them to the bottom of this structure
90531 ** in order to preserve backwards compatibility.
90532 **
90533 ** Extensions that use newer APIs should first call the
90534 ** sqlite3_libversion_number() to make sure that the API they
90535 ** intend to use is supported by the library.  Extensions should
90536 ** also check to make sure that the pointer to the function is
90537 ** not NULL before calling it.
90538 */
90539 static const sqlite3_api_routines sqlite3Apis = {
90540   sqlite3_aggregate_context,
90541 #ifndef SQLITE_OMIT_DEPRECATED
90542   sqlite3_aggregate_count,
90543 #else
90544   0,
90545 #endif
90546   sqlite3_bind_blob,
90547   sqlite3_bind_double,
90548   sqlite3_bind_int,
90549   sqlite3_bind_int64,
90550   sqlite3_bind_null,
90551   sqlite3_bind_parameter_count,
90552   sqlite3_bind_parameter_index,
90553   sqlite3_bind_parameter_name,
90554   sqlite3_bind_text,
90555   sqlite3_bind_text16,
90556   sqlite3_bind_value,
90557   sqlite3_busy_handler,
90558   sqlite3_busy_timeout,
90559   sqlite3_changes,
90560   sqlite3_close,
90561   sqlite3_collation_needed,
90562   sqlite3_collation_needed16,
90563   sqlite3_column_blob,
90564   sqlite3_column_bytes,
90565   sqlite3_column_bytes16,
90566   sqlite3_column_count,
90567   sqlite3_column_database_name,
90568   sqlite3_column_database_name16,
90569   sqlite3_column_decltype,
90570   sqlite3_column_decltype16,
90571   sqlite3_column_double,
90572   sqlite3_column_int,
90573   sqlite3_column_int64,
90574   sqlite3_column_name,
90575   sqlite3_column_name16,
90576   sqlite3_column_origin_name,
90577   sqlite3_column_origin_name16,
90578   sqlite3_column_table_name,
90579   sqlite3_column_table_name16,
90580   sqlite3_column_text,
90581   sqlite3_column_text16,
90582   sqlite3_column_type,
90583   sqlite3_column_value,
90584   sqlite3_commit_hook,
90585   sqlite3_complete,
90586   sqlite3_complete16,
90587   sqlite3_create_collation,
90588   sqlite3_create_collation16,
90589   sqlite3_create_function,
90590   sqlite3_create_function16,
90591   sqlite3_create_module,
90592   sqlite3_data_count,
90593   sqlite3_db_handle,
90594   sqlite3_declare_vtab,
90595   sqlite3_enable_shared_cache,
90596   sqlite3_errcode,
90597   sqlite3_errmsg,
90598   sqlite3_errmsg16,
90599   sqlite3_exec,
90600 #ifndef SQLITE_OMIT_DEPRECATED
90601   sqlite3_expired,
90602 #else
90603   0,
90604 #endif
90605   sqlite3_finalize,
90606   sqlite3_free,
90607   sqlite3_free_table,
90608   sqlite3_get_autocommit,
90609   sqlite3_get_auxdata,
90610   sqlite3_get_table,
90611   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
90612   sqlite3_interrupt,
90613   sqlite3_last_insert_rowid,
90614   sqlite3_libversion,
90615   sqlite3_libversion_number,
90616   sqlite3_malloc,
90617   sqlite3_mprintf,
90618   sqlite3_open,
90619   sqlite3_open16,
90620   sqlite3_prepare,
90621   sqlite3_prepare16,
90622   sqlite3_profile,
90623   sqlite3_progress_handler,
90624   sqlite3_realloc,
90625   sqlite3_reset,
90626   sqlite3_result_blob,
90627   sqlite3_result_double,
90628   sqlite3_result_error,
90629   sqlite3_result_error16,
90630   sqlite3_result_int,
90631   sqlite3_result_int64,
90632   sqlite3_result_null,
90633   sqlite3_result_text,
90634   sqlite3_result_text16,
90635   sqlite3_result_text16be,
90636   sqlite3_result_text16le,
90637   sqlite3_result_value,
90638   sqlite3_rollback_hook,
90639   sqlite3_set_authorizer,
90640   sqlite3_set_auxdata,
90641   sqlite3_snprintf,
90642   sqlite3_step,
90643   sqlite3_table_column_metadata,
90644 #ifndef SQLITE_OMIT_DEPRECATED
90645   sqlite3_thread_cleanup,
90646 #else
90647   0,
90648 #endif
90649   sqlite3_total_changes,
90650   sqlite3_trace,
90651 #ifndef SQLITE_OMIT_DEPRECATED
90652   sqlite3_transfer_bindings,
90653 #else
90654   0,
90655 #endif
90656   sqlite3_update_hook,
90657   sqlite3_user_data,
90658   sqlite3_value_blob,
90659   sqlite3_value_bytes,
90660   sqlite3_value_bytes16,
90661   sqlite3_value_double,
90662   sqlite3_value_int,
90663   sqlite3_value_int64,
90664   sqlite3_value_numeric_type,
90665   sqlite3_value_text,
90666   sqlite3_value_text16,
90667   sqlite3_value_text16be,
90668   sqlite3_value_text16le,
90669   sqlite3_value_type,
90670   sqlite3_vmprintf,
90671   /*
90672   ** The original API set ends here.  All extensions can call any
90673   ** of the APIs above provided that the pointer is not NULL.  But
90674   ** before calling APIs that follow, extension should check the
90675   ** sqlite3_libversion_number() to make sure they are dealing with
90676   ** a library that is new enough to support that API.
90677   *************************************************************************
90678   */
90679   sqlite3_overload_function,
90680
90681   /*
90682   ** Added after 3.3.13
90683   */
90684   sqlite3_prepare_v2,
90685   sqlite3_prepare16_v2,
90686   sqlite3_clear_bindings,
90687
90688   /*
90689   ** Added for 3.4.1
90690   */
90691   sqlite3_create_module_v2,
90692
90693   /*
90694   ** Added for 3.5.0
90695   */
90696   sqlite3_bind_zeroblob,
90697   sqlite3_blob_bytes,
90698   sqlite3_blob_close,
90699   sqlite3_blob_open,
90700   sqlite3_blob_read,
90701   sqlite3_blob_write,
90702   sqlite3_create_collation_v2,
90703   sqlite3_file_control,
90704   sqlite3_memory_highwater,
90705   sqlite3_memory_used,
90706 #ifdef SQLITE_MUTEX_OMIT
90707   0, 
90708   0, 
90709   0,
90710   0,
90711   0,
90712 #else
90713   sqlite3_mutex_alloc,
90714   sqlite3_mutex_enter,
90715   sqlite3_mutex_free,
90716   sqlite3_mutex_leave,
90717   sqlite3_mutex_try,
90718 #endif
90719   sqlite3_open_v2,
90720   sqlite3_release_memory,
90721   sqlite3_result_error_nomem,
90722   sqlite3_result_error_toobig,
90723   sqlite3_sleep,
90724   sqlite3_soft_heap_limit,
90725   sqlite3_vfs_find,
90726   sqlite3_vfs_register,
90727   sqlite3_vfs_unregister,
90728
90729   /*
90730   ** Added for 3.5.8
90731   */
90732   sqlite3_threadsafe,
90733   sqlite3_result_zeroblob,
90734   sqlite3_result_error_code,
90735   sqlite3_test_control,
90736   sqlite3_randomness,
90737   sqlite3_context_db_handle,
90738
90739   /*
90740   ** Added for 3.6.0
90741   */
90742   sqlite3_extended_result_codes,
90743   sqlite3_limit,
90744   sqlite3_next_stmt,
90745   sqlite3_sql,
90746   sqlite3_status,
90747
90748   /*
90749   ** Added for 3.7.4
90750   */
90751   sqlite3_backup_finish,
90752   sqlite3_backup_init,
90753   sqlite3_backup_pagecount,
90754   sqlite3_backup_remaining,
90755   sqlite3_backup_step,
90756 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
90757   sqlite3_compileoption_get,
90758   sqlite3_compileoption_used,
90759 #else
90760   0,
90761   0,
90762 #endif
90763   sqlite3_create_function_v2,
90764   sqlite3_db_config,
90765   sqlite3_db_mutex,
90766   sqlite3_db_status,
90767   sqlite3_extended_errcode,
90768   sqlite3_log,
90769   sqlite3_soft_heap_limit64,
90770   sqlite3_sourceid,
90771   sqlite3_stmt_status,
90772   sqlite3_strnicmp,
90773 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
90774   sqlite3_unlock_notify,
90775 #else
90776   0,
90777 #endif
90778 #ifndef SQLITE_OMIT_WAL
90779   sqlite3_wal_autocheckpoint,
90780   sqlite3_wal_checkpoint,
90781   sqlite3_wal_hook,
90782 #else
90783   0,
90784   0,
90785   0,
90786 #endif
90787   sqlite3_blob_reopen,
90788   sqlite3_vtab_config,
90789   sqlite3_vtab_on_conflict,
90790 };
90791
90792 /*
90793 ** Attempt to load an SQLite extension library contained in the file
90794 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
90795 ** default entry point name (sqlite3_extension_init) is used.  Use
90796 ** of the default name is recommended.
90797 **
90798 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
90799 **
90800 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
90801 ** error message text.  The calling function should free this memory
90802 ** by calling sqlite3DbFree(db, ).
90803 */
90804 static int sqlite3LoadExtension(
90805   sqlite3 *db,          /* Load the extension into this database connection */
90806   const char *zFile,    /* Name of the shared library containing extension */
90807   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
90808   char **pzErrMsg       /* Put error message here if not 0 */
90809 ){
90810   sqlite3_vfs *pVfs = db->pVfs;
90811   void *handle;
90812   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
90813   char *zErrmsg = 0;
90814   void **aHandle;
90815   int nMsg = 300 + sqlite3Strlen30(zFile);
90816
90817   if( pzErrMsg ) *pzErrMsg = 0;
90818
90819   /* Ticket #1863.  To avoid a creating security problems for older
90820   ** applications that relink against newer versions of SQLite, the
90821   ** ability to run load_extension is turned off by default.  One
90822   ** must call sqlite3_enable_load_extension() to turn on extension
90823   ** loading.  Otherwise you get the following error.
90824   */
90825   if( (db->flags & SQLITE_LoadExtension)==0 ){
90826     if( pzErrMsg ){
90827       *pzErrMsg = sqlite3_mprintf("not authorized");
90828     }
90829     return SQLITE_ERROR;
90830   }
90831
90832   if( zProc==0 ){
90833     zProc = "sqlite3_extension_init";
90834   }
90835
90836   handle = sqlite3OsDlOpen(pVfs, zFile);
90837   if( handle==0 ){
90838     if( pzErrMsg ){
90839       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
90840       if( zErrmsg ){
90841         sqlite3_snprintf(nMsg, zErrmsg, 
90842             "unable to open shared library [%s]", zFile);
90843         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
90844       }
90845     }
90846     return SQLITE_ERROR;
90847   }
90848   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
90849                    sqlite3OsDlSym(pVfs, handle, zProc);
90850   if( xInit==0 ){
90851     if( pzErrMsg ){
90852       nMsg += sqlite3Strlen30(zProc);
90853       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
90854       if( zErrmsg ){
90855         sqlite3_snprintf(nMsg, zErrmsg,
90856             "no entry point [%s] in shared library [%s]", zProc,zFile);
90857         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
90858       }
90859       sqlite3OsDlClose(pVfs, handle);
90860     }
90861     return SQLITE_ERROR;
90862   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
90863     if( pzErrMsg ){
90864       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
90865     }
90866     sqlite3_free(zErrmsg);
90867     sqlite3OsDlClose(pVfs, handle);
90868     return SQLITE_ERROR;
90869   }
90870
90871   /* Append the new shared library handle to the db->aExtension array. */
90872   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
90873   if( aHandle==0 ){
90874     return SQLITE_NOMEM;
90875   }
90876   if( db->nExtension>0 ){
90877     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
90878   }
90879   sqlite3DbFree(db, db->aExtension);
90880   db->aExtension = aHandle;
90881
90882   db->aExtension[db->nExtension++] = handle;
90883   return SQLITE_OK;
90884 }
90885 SQLITE_API int sqlite3_load_extension(
90886   sqlite3 *db,          /* Load the extension into this database connection */
90887   const char *zFile,    /* Name of the shared library containing extension */
90888   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
90889   char **pzErrMsg       /* Put error message here if not 0 */
90890 ){
90891   int rc;
90892   sqlite3_mutex_enter(db->mutex);
90893   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
90894   rc = sqlite3ApiExit(db, rc);
90895   sqlite3_mutex_leave(db->mutex);
90896   return rc;
90897 }
90898
90899 /*
90900 ** Call this routine when the database connection is closing in order
90901 ** to clean up loaded extensions
90902 */
90903 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
90904   int i;
90905   assert( sqlite3_mutex_held(db->mutex) );
90906   for(i=0; i<db->nExtension; i++){
90907     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
90908   }
90909   sqlite3DbFree(db, db->aExtension);
90910 }
90911
90912 /*
90913 ** Enable or disable extension loading.  Extension loading is disabled by
90914 ** default so as not to open security holes in older applications.
90915 */
90916 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
90917   sqlite3_mutex_enter(db->mutex);
90918   if( onoff ){
90919     db->flags |= SQLITE_LoadExtension;
90920   }else{
90921     db->flags &= ~SQLITE_LoadExtension;
90922   }
90923   sqlite3_mutex_leave(db->mutex);
90924   return SQLITE_OK;
90925 }
90926
90927 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
90928
90929 /*
90930 ** The auto-extension code added regardless of whether or not extension
90931 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
90932 ** code if regular extension loading is not available.  This is that
90933 ** dummy pointer.
90934 */
90935 #ifdef SQLITE_OMIT_LOAD_EXTENSION
90936 static const sqlite3_api_routines sqlite3Apis = { 0 };
90937 #endif
90938
90939
90940 /*
90941 ** The following object holds the list of automatically loaded
90942 ** extensions.
90943 **
90944 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
90945 ** mutex must be held while accessing this list.
90946 */
90947 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
90948 static SQLITE_WSD struct sqlite3AutoExtList {
90949   int nExt;              /* Number of entries in aExt[] */          
90950   void (**aExt)(void);   /* Pointers to the extension init functions */
90951 } sqlite3Autoext = { 0, 0 };
90952
90953 /* The "wsdAutoext" macro will resolve to the autoextension
90954 ** state vector.  If writable static data is unsupported on the target,
90955 ** we have to locate the state vector at run-time.  In the more common
90956 ** case where writable static data is supported, wsdStat can refer directly
90957 ** to the "sqlite3Autoext" state vector declared above.
90958 */
90959 #ifdef SQLITE_OMIT_WSD
90960 # define wsdAutoextInit \
90961   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
90962 # define wsdAutoext x[0]
90963 #else
90964 # define wsdAutoextInit
90965 # define wsdAutoext sqlite3Autoext
90966 #endif
90967
90968
90969 /*
90970 ** Register a statically linked extension that is automatically
90971 ** loaded by every new database connection.
90972 */
90973 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
90974   int rc = SQLITE_OK;
90975 #ifndef SQLITE_OMIT_AUTOINIT
90976   rc = sqlite3_initialize();
90977   if( rc ){
90978     return rc;
90979   }else
90980 #endif
90981   {
90982     int i;
90983 #if SQLITE_THREADSAFE
90984     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
90985 #endif
90986     wsdAutoextInit;
90987     sqlite3_mutex_enter(mutex);
90988     for(i=0; i<wsdAutoext.nExt; i++){
90989       if( wsdAutoext.aExt[i]==xInit ) break;
90990     }
90991     if( i==wsdAutoext.nExt ){
90992       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
90993       void (**aNew)(void);
90994       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
90995       if( aNew==0 ){
90996         rc = SQLITE_NOMEM;
90997       }else{
90998         wsdAutoext.aExt = aNew;
90999         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91000         wsdAutoext.nExt++;
91001       }
91002     }
91003     sqlite3_mutex_leave(mutex);
91004     assert( (rc&0xff)==rc );
91005     return rc;
91006   }
91007 }
91008
91009 /*
91010 ** Reset the automatic extension loading mechanism.
91011 */
91012 SQLITE_API void sqlite3_reset_auto_extension(void){
91013 #ifndef SQLITE_OMIT_AUTOINIT
91014   if( sqlite3_initialize()==SQLITE_OK )
91015 #endif
91016   {
91017 #if SQLITE_THREADSAFE
91018     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91019 #endif
91020     wsdAutoextInit;
91021     sqlite3_mutex_enter(mutex);
91022     sqlite3_free(wsdAutoext.aExt);
91023     wsdAutoext.aExt = 0;
91024     wsdAutoext.nExt = 0;
91025     sqlite3_mutex_leave(mutex);
91026   }
91027 }
91028
91029 /*
91030 ** Load all automatic extensions.
91031 **
91032 ** If anything goes wrong, set an error in the database connection.
91033 */
91034 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
91035   int i;
91036   int go = 1;
91037   int rc;
91038   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91039
91040   wsdAutoextInit;
91041   if( wsdAutoext.nExt==0 ){
91042     /* Common case: early out without every having to acquire a mutex */
91043     return;
91044   }
91045   for(i=0; go; i++){
91046     char *zErrmsg;
91047 #if SQLITE_THREADSAFE
91048     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91049 #endif
91050     sqlite3_mutex_enter(mutex);
91051     if( i>=wsdAutoext.nExt ){
91052       xInit = 0;
91053       go = 0;
91054     }else{
91055       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91056               wsdAutoext.aExt[i];
91057     }
91058     sqlite3_mutex_leave(mutex);
91059     zErrmsg = 0;
91060     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
91061       sqlite3Error(db, rc,
91062             "automatic extension loading failed: %s", zErrmsg);
91063       go = 0;
91064     }
91065     sqlite3_free(zErrmsg);
91066   }
91067 }
91068
91069 /************** End of loadext.c *********************************************/
91070 /************** Begin file pragma.c ******************************************/
91071 /*
91072 ** 2003 April 6
91073 **
91074 ** The author disclaims copyright to this source code.  In place of
91075 ** a legal notice, here is a blessing:
91076 **
91077 **    May you do good and not evil.
91078 **    May you find forgiveness for yourself and forgive others.
91079 **    May you share freely, never taking more than you give.
91080 **
91081 *************************************************************************
91082 ** This file contains code used to implement the PRAGMA command.
91083 */
91084
91085 /*
91086 ** Interpret the given string as a safety level.  Return 0 for OFF,
91087 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
91088 ** unrecognized string argument.  The FULL option is disallowed
91089 ** if the omitFull parameter it 1.
91090 **
91091 ** Note that the values returned are one less that the values that
91092 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
91093 ** to support legacy SQL code.  The safety level used to be boolean
91094 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
91095 */
91096 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
91097                              /* 123456789 123456789 */
91098   static const char zText[] = "onoffalseyestruefull";
91099   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
91100   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
91101   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
91102   int i, n;
91103   if( sqlite3Isdigit(*z) ){
91104     return (u8)sqlite3Atoi(z);
91105   }
91106   n = sqlite3Strlen30(z);
91107   for(i=0; i<ArraySize(iLength)-omitFull; i++){
91108     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
91109       return iValue[i];
91110     }
91111   }
91112   return dflt;
91113 }
91114
91115 /*
91116 ** Interpret the given string as a boolean value.
91117 */
91118 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
91119   return getSafetyLevel(z,1,dflt)!=0;
91120 }
91121
91122 /* The sqlite3GetBoolean() function is used by other modules but the
91123 ** remainder of this file is specific to PRAGMA processing.  So omit
91124 ** the rest of the file if PRAGMAs are omitted from the build.
91125 */
91126 #if !defined(SQLITE_OMIT_PRAGMA)
91127
91128 /*
91129 ** Interpret the given string as a locking mode value.
91130 */
91131 static int getLockingMode(const char *z){
91132   if( z ){
91133     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
91134     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
91135   }
91136   return PAGER_LOCKINGMODE_QUERY;
91137 }
91138
91139 #ifndef SQLITE_OMIT_AUTOVACUUM
91140 /*
91141 ** Interpret the given string as an auto-vacuum mode value.
91142 **
91143 ** The following strings, "none", "full" and "incremental" are 
91144 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
91145 */
91146 static int getAutoVacuum(const char *z){
91147   int i;
91148   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
91149   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
91150   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
91151   i = sqlite3Atoi(z);
91152   return (u8)((i>=0&&i<=2)?i:0);
91153 }
91154 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
91155
91156 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91157 /*
91158 ** Interpret the given string as a temp db location. Return 1 for file
91159 ** backed temporary databases, 2 for the Red-Black tree in memory database
91160 ** and 0 to use the compile-time default.
91161 */
91162 static int getTempStore(const char *z){
91163   if( z[0]>='0' && z[0]<='2' ){
91164     return z[0] - '0';
91165   }else if( sqlite3StrICmp(z, "file")==0 ){
91166     return 1;
91167   }else if( sqlite3StrICmp(z, "memory")==0 ){
91168     return 2;
91169   }else{
91170     return 0;
91171   }
91172 }
91173 #endif /* SQLITE_PAGER_PRAGMAS */
91174
91175 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91176 /*
91177 ** Invalidate temp storage, either when the temp storage is changed
91178 ** from default, or when 'file' and the temp_store_directory has changed
91179 */
91180 static int invalidateTempStorage(Parse *pParse){
91181   sqlite3 *db = pParse->db;
91182   if( db->aDb[1].pBt!=0 ){
91183     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
91184       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
91185         "from within a transaction");
91186       return SQLITE_ERROR;
91187     }
91188     sqlite3BtreeClose(db->aDb[1].pBt);
91189     db->aDb[1].pBt = 0;
91190     sqlite3ResetAllSchemasOfConnection(db);
91191   }
91192   return SQLITE_OK;
91193 }
91194 #endif /* SQLITE_PAGER_PRAGMAS */
91195
91196 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91197 /*
91198 ** If the TEMP database is open, close it and mark the database schema
91199 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
91200 ** or DEFAULT_TEMP_STORE pragmas.
91201 */
91202 static int changeTempStorage(Parse *pParse, const char *zStorageType){
91203   int ts = getTempStore(zStorageType);
91204   sqlite3 *db = pParse->db;
91205   if( db->temp_store==ts ) return SQLITE_OK;
91206   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
91207     return SQLITE_ERROR;
91208   }
91209   db->temp_store = (u8)ts;
91210   return SQLITE_OK;
91211 }
91212 #endif /* SQLITE_PAGER_PRAGMAS */
91213
91214 /*
91215 ** Generate code to return a single integer value.
91216 */
91217 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
91218   Vdbe *v = sqlite3GetVdbe(pParse);
91219   int mem = ++pParse->nMem;
91220   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
91221   if( pI64 ){
91222     memcpy(pI64, &value, sizeof(value));
91223   }
91224   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
91225   sqlite3VdbeSetNumCols(v, 1);
91226   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
91227   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
91228 }
91229
91230 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
91231 /*
91232 ** Check to see if zRight and zLeft refer to a pragma that queries
91233 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
91234 ** Also, implement the pragma.
91235 */
91236 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
91237   static const struct sPragmaType {
91238     const char *zName;  /* Name of the pragma */
91239     int mask;           /* Mask for the db->flags value */
91240   } aPragma[] = {
91241     { "full_column_names",        SQLITE_FullColNames  },
91242     { "short_column_names",       SQLITE_ShortColNames },
91243     { "count_changes",            SQLITE_CountRows     },
91244     { "empty_result_callbacks",   SQLITE_NullCallback  },
91245     { "legacy_file_format",       SQLITE_LegacyFileFmt },
91246     { "fullfsync",                SQLITE_FullFSync     },
91247     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
91248     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
91249 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
91250     { "automatic_index",          SQLITE_AutoIndex     },
91251 #endif
91252 #ifdef SQLITE_DEBUG
91253     { "sql_trace",                SQLITE_SqlTrace      },
91254     { "vdbe_listing",             SQLITE_VdbeListing   },
91255     { "vdbe_trace",               SQLITE_VdbeTrace     },
91256 #endif
91257 #ifndef SQLITE_OMIT_CHECK
91258     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
91259 #endif
91260     /* The following is VERY experimental */
91261     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
91262
91263     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
91264     ** flag if there are any active statements. */
91265     { "read_uncommitted",         SQLITE_ReadUncommitted },
91266     { "recursive_triggers",       SQLITE_RecTriggers },
91267
91268     /* This flag may only be set if both foreign-key and trigger support
91269     ** are present in the build.  */
91270 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
91271     { "foreign_keys",             SQLITE_ForeignKeys },
91272 #endif
91273   };
91274   int i;
91275   const struct sPragmaType *p;
91276   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
91277     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
91278       sqlite3 *db = pParse->db;
91279       Vdbe *v;
91280       v = sqlite3GetVdbe(pParse);
91281       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
91282       if( ALWAYS(v) ){
91283         if( zRight==0 ){
91284           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
91285         }else{
91286           int mask = p->mask;          /* Mask of bits to set or clear. */
91287           if( db->autoCommit==0 ){
91288             /* Foreign key support may not be enabled or disabled while not
91289             ** in auto-commit mode.  */
91290             mask &= ~(SQLITE_ForeignKeys);
91291           }
91292
91293           if( sqlite3GetBoolean(zRight, 0) ){
91294             db->flags |= mask;
91295           }else{
91296             db->flags &= ~mask;
91297           }
91298
91299           /* Many of the flag-pragmas modify the code generated by the SQL 
91300           ** compiler (eg. count_changes). So add an opcode to expire all
91301           ** compiled SQL statements after modifying a pragma value.
91302           */
91303           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
91304         }
91305       }
91306
91307       return 1;
91308     }
91309   }
91310   return 0;
91311 }
91312 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
91313
91314 /*
91315 ** Return a human-readable name for a constraint resolution action.
91316 */
91317 #ifndef SQLITE_OMIT_FOREIGN_KEY
91318 static const char *actionName(u8 action){
91319   const char *zName;
91320   switch( action ){
91321     case OE_SetNull:  zName = "SET NULL";        break;
91322     case OE_SetDflt:  zName = "SET DEFAULT";     break;
91323     case OE_Cascade:  zName = "CASCADE";         break;
91324     case OE_Restrict: zName = "RESTRICT";        break;
91325     default:          zName = "NO ACTION";  
91326                       assert( action==OE_None ); break;
91327   }
91328   return zName;
91329 }
91330 #endif
91331
91332
91333 /*
91334 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
91335 ** defined in pager.h. This function returns the associated lowercase
91336 ** journal-mode name.
91337 */
91338 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
91339   static char * const azModeName[] = {
91340     "delete", "persist", "off", "truncate", "memory"
91341 #ifndef SQLITE_OMIT_WAL
91342      , "wal"
91343 #endif
91344   };
91345   assert( PAGER_JOURNALMODE_DELETE==0 );
91346   assert( PAGER_JOURNALMODE_PERSIST==1 );
91347   assert( PAGER_JOURNALMODE_OFF==2 );
91348   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
91349   assert( PAGER_JOURNALMODE_MEMORY==4 );
91350   assert( PAGER_JOURNALMODE_WAL==5 );
91351   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
91352
91353   if( eMode==ArraySize(azModeName) ) return 0;
91354   return azModeName[eMode];
91355 }
91356
91357 /*
91358 ** Process a pragma statement.  
91359 **
91360 ** Pragmas are of this form:
91361 **
91362 **      PRAGMA [database.]id [= value]
91363 **
91364 ** The identifier might also be a string.  The value is a string, and
91365 ** identifier, or a number.  If minusFlag is true, then the value is
91366 ** a number that was preceded by a minus sign.
91367 **
91368 ** If the left side is "database.id" then pId1 is the database name
91369 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
91370 ** id and pId2 is any empty string.
91371 */
91372 SQLITE_PRIVATE void sqlite3Pragma(
91373   Parse *pParse, 
91374   Token *pId1,        /* First part of [database.]id field */
91375   Token *pId2,        /* Second part of [database.]id field, or NULL */
91376   Token *pValue,      /* Token for <value>, or NULL */
91377   int minusFlag       /* True if a '-' sign preceded <value> */
91378 ){
91379   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
91380   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
91381   const char *zDb = 0;   /* The database name */
91382   Token *pId;            /* Pointer to <id> token */
91383   int iDb;               /* Database index for <database> */
91384   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
91385   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
91386   sqlite3 *db = pParse->db;    /* The database connection */
91387   Db *pDb;                     /* The specific database being pragmaed */
91388   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
91389
91390   if( v==0 ) return;
91391   sqlite3VdbeRunOnlyOnce(v);
91392   pParse->nMem = 2;
91393
91394   /* Interpret the [database.] part of the pragma statement. iDb is the
91395   ** index of the database this pragma is being applied to in db.aDb[]. */
91396   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
91397   if( iDb<0 ) return;
91398   pDb = &db->aDb[iDb];
91399
91400   /* If the temp database has been explicitly named as part of the 
91401   ** pragma, make sure it is open. 
91402   */
91403   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
91404     return;
91405   }
91406
91407   zLeft = sqlite3NameFromToken(db, pId);
91408   if( !zLeft ) return;
91409   if( minusFlag ){
91410     zRight = sqlite3MPrintf(db, "-%T", pValue);
91411   }else{
91412     zRight = sqlite3NameFromToken(db, pValue);
91413   }
91414
91415   assert( pId2 );
91416   zDb = pId2->n>0 ? pDb->zName : 0;
91417   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
91418     goto pragma_out;
91419   }
91420
91421   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
91422   ** connection.  If it returns SQLITE_OK, then assume that the VFS
91423   ** handled the pragma and generate a no-op prepared statement.
91424   */
91425   aFcntl[0] = 0;
91426   aFcntl[1] = zLeft;
91427   aFcntl[2] = zRight;
91428   aFcntl[3] = 0;
91429   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
91430   if( rc==SQLITE_OK ){
91431     if( aFcntl[0] ){
91432       int mem = ++pParse->nMem;
91433       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
91434       sqlite3VdbeSetNumCols(v, 1);
91435       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
91436       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
91437       sqlite3_free(aFcntl[0]);
91438     }
91439   }else if( rc!=SQLITE_NOTFOUND ){
91440     if( aFcntl[0] ){
91441       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
91442       sqlite3_free(aFcntl[0]);
91443     }
91444     pParse->nErr++;
91445     pParse->rc = rc;
91446   }else
91447                             
91448  
91449 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
91450   /*
91451   **  PRAGMA [database.]default_cache_size
91452   **  PRAGMA [database.]default_cache_size=N
91453   **
91454   ** The first form reports the current persistent setting for the
91455   ** page cache size.  The value returned is the maximum number of
91456   ** pages in the page cache.  The second form sets both the current
91457   ** page cache size value and the persistent page cache size value
91458   ** stored in the database file.
91459   **
91460   ** Older versions of SQLite would set the default cache size to a
91461   ** negative number to indicate synchronous=OFF.  These days, synchronous
91462   ** is always on by default regardless of the sign of the default cache
91463   ** size.  But continue to take the absolute value of the default cache
91464   ** size of historical compatibility.
91465   */
91466   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
91467     static const VdbeOpList getCacheSize[] = {
91468       { OP_Transaction, 0, 0,        0},                         /* 0 */
91469       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
91470       { OP_IfPos,       1, 7,        0},
91471       { OP_Integer,     0, 2,        0},
91472       { OP_Subtract,    1, 2,        1},
91473       { OP_IfPos,       1, 7,        0},
91474       { OP_Integer,     0, 1,        0},                         /* 6 */
91475       { OP_ResultRow,   1, 1,        0},
91476     };
91477     int addr;
91478     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91479     sqlite3VdbeUsesBtree(v, iDb);
91480     if( !zRight ){
91481       sqlite3VdbeSetNumCols(v, 1);
91482       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
91483       pParse->nMem += 2;
91484       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
91485       sqlite3VdbeChangeP1(v, addr, iDb);
91486       sqlite3VdbeChangeP1(v, addr+1, iDb);
91487       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
91488     }else{
91489       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
91490       sqlite3BeginWriteOperation(pParse, 0, iDb);
91491       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
91492       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
91493       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91494       pDb->pSchema->cache_size = size;
91495       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
91496     }
91497   }else
91498 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
91499
91500 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
91501   /*
91502   **  PRAGMA [database.]page_size
91503   **  PRAGMA [database.]page_size=N
91504   **
91505   ** The first form reports the current setting for the
91506   ** database page size in bytes.  The second form sets the
91507   ** database page size value.  The value can only be set if
91508   ** the database has not yet been created.
91509   */
91510   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
91511     Btree *pBt = pDb->pBt;
91512     assert( pBt!=0 );
91513     if( !zRight ){
91514       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
91515       returnSingleInt(pParse, "page_size", size);
91516     }else{
91517       /* Malloc may fail when setting the page-size, as there is an internal
91518       ** buffer that the pager module resizes using sqlite3_realloc().
91519       */
91520       db->nextPagesize = sqlite3Atoi(zRight);
91521       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
91522         db->mallocFailed = 1;
91523       }
91524     }
91525   }else
91526
91527   /*
91528   **  PRAGMA [database.]secure_delete
91529   **  PRAGMA [database.]secure_delete=ON/OFF
91530   **
91531   ** The first form reports the current setting for the
91532   ** secure_delete flag.  The second form changes the secure_delete
91533   ** flag setting and reports thenew value.
91534   */
91535   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
91536     Btree *pBt = pDb->pBt;
91537     int b = -1;
91538     assert( pBt!=0 );
91539     if( zRight ){
91540       b = sqlite3GetBoolean(zRight, 0);
91541     }
91542     if( pId2->n==0 && b>=0 ){
91543       int ii;
91544       for(ii=0; ii<db->nDb; ii++){
91545         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
91546       }
91547     }
91548     b = sqlite3BtreeSecureDelete(pBt, b);
91549     returnSingleInt(pParse, "secure_delete", b);
91550   }else
91551
91552   /*
91553   **  PRAGMA [database.]max_page_count
91554   **  PRAGMA [database.]max_page_count=N
91555   **
91556   ** The first form reports the current setting for the
91557   ** maximum number of pages in the database file.  The 
91558   ** second form attempts to change this setting.  Both
91559   ** forms return the current setting.
91560   **
91561   ** The absolute value of N is used.  This is undocumented and might
91562   ** change.  The only purpose is to provide an easy way to test
91563   ** the sqlite3AbsInt32() function.
91564   **
91565   **  PRAGMA [database.]page_count
91566   **
91567   ** Return the number of pages in the specified database.
91568   */
91569   if( sqlite3StrICmp(zLeft,"page_count")==0
91570    || sqlite3StrICmp(zLeft,"max_page_count")==0
91571   ){
91572     int iReg;
91573     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91574     sqlite3CodeVerifySchema(pParse, iDb);
91575     iReg = ++pParse->nMem;
91576     if( sqlite3Tolower(zLeft[0])=='p' ){
91577       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
91578     }else{
91579       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
91580                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
91581     }
91582     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
91583     sqlite3VdbeSetNumCols(v, 1);
91584     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
91585   }else
91586
91587   /*
91588   **  PRAGMA [database.]locking_mode
91589   **  PRAGMA [database.]locking_mode = (normal|exclusive)
91590   */
91591   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
91592     const char *zRet = "normal";
91593     int eMode = getLockingMode(zRight);
91594
91595     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
91596       /* Simple "PRAGMA locking_mode;" statement. This is a query for
91597       ** the current default locking mode (which may be different to
91598       ** the locking-mode of the main database).
91599       */
91600       eMode = db->dfltLockMode;
91601     }else{
91602       Pager *pPager;
91603       if( pId2->n==0 ){
91604         /* This indicates that no database name was specified as part
91605         ** of the PRAGMA command. In this case the locking-mode must be
91606         ** set on all attached databases, as well as the main db file.
91607         **
91608         ** Also, the sqlite3.dfltLockMode variable is set so that
91609         ** any subsequently attached databases also use the specified
91610         ** locking mode.
91611         */
91612         int ii;
91613         assert(pDb==&db->aDb[0]);
91614         for(ii=2; ii<db->nDb; ii++){
91615           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
91616           sqlite3PagerLockingMode(pPager, eMode);
91617         }
91618         db->dfltLockMode = (u8)eMode;
91619       }
91620       pPager = sqlite3BtreePager(pDb->pBt);
91621       eMode = sqlite3PagerLockingMode(pPager, eMode);
91622     }
91623
91624     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
91625     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
91626       zRet = "exclusive";
91627     }
91628     sqlite3VdbeSetNumCols(v, 1);
91629     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
91630     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
91631     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91632   }else
91633
91634   /*
91635   **  PRAGMA [database.]journal_mode
91636   **  PRAGMA [database.]journal_mode =
91637   **                      (delete|persist|off|truncate|memory|wal|off)
91638   */
91639   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
91640     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
91641     int ii;           /* Loop counter */
91642
91643     /* Force the schema to be loaded on all databases.  This causes all
91644     ** database files to be opened and the journal_modes set.  This is
91645     ** necessary because subsequent processing must know if the databases
91646     ** are in WAL mode. */
91647     if( sqlite3ReadSchema(pParse) ){
91648       goto pragma_out;
91649     }
91650
91651     sqlite3VdbeSetNumCols(v, 1);
91652     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
91653
91654     if( zRight==0 ){
91655       /* If there is no "=MODE" part of the pragma, do a query for the
91656       ** current mode */
91657       eMode = PAGER_JOURNALMODE_QUERY;
91658     }else{
91659       const char *zMode;
91660       int n = sqlite3Strlen30(zRight);
91661       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
91662         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
91663       }
91664       if( !zMode ){
91665         /* If the "=MODE" part does not match any known journal mode,
91666         ** then do a query */
91667         eMode = PAGER_JOURNALMODE_QUERY;
91668       }
91669     }
91670     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
91671       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
91672       iDb = 0;
91673       pId2->n = 1;
91674     }
91675     for(ii=db->nDb-1; ii>=0; ii--){
91676       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
91677         sqlite3VdbeUsesBtree(v, ii);
91678         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
91679       }
91680     }
91681     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91682   }else
91683
91684   /*
91685   **  PRAGMA [database.]journal_size_limit
91686   **  PRAGMA [database.]journal_size_limit=N
91687   **
91688   ** Get or set the size limit on rollback journal files.
91689   */
91690   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
91691     Pager *pPager = sqlite3BtreePager(pDb->pBt);
91692     i64 iLimit = -2;
91693     if( zRight ){
91694       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
91695       if( iLimit<-1 ) iLimit = -1;
91696     }
91697     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
91698     returnSingleInt(pParse, "journal_size_limit", iLimit);
91699   }else
91700
91701 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
91702
91703   /*
91704   **  PRAGMA [database.]auto_vacuum
91705   **  PRAGMA [database.]auto_vacuum=N
91706   **
91707   ** Get or set the value of the database 'auto-vacuum' parameter.
91708   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
91709   */
91710 #ifndef SQLITE_OMIT_AUTOVACUUM
91711   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
91712     Btree *pBt = pDb->pBt;
91713     assert( pBt!=0 );
91714     if( sqlite3ReadSchema(pParse) ){
91715       goto pragma_out;
91716     }
91717     if( !zRight ){
91718       int auto_vacuum;
91719       if( ALWAYS(pBt) ){
91720          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
91721       }else{
91722          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
91723       }
91724       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
91725     }else{
91726       int eAuto = getAutoVacuum(zRight);
91727       assert( eAuto>=0 && eAuto<=2 );
91728       db->nextAutovac = (u8)eAuto;
91729       if( ALWAYS(eAuto>=0) ){
91730         /* Call SetAutoVacuum() to set initialize the internal auto and
91731         ** incr-vacuum flags. This is required in case this connection
91732         ** creates the database file. It is important that it is created
91733         ** as an auto-vacuum capable db.
91734         */
91735         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
91736         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
91737           /* When setting the auto_vacuum mode to either "full" or 
91738           ** "incremental", write the value of meta[6] in the database
91739           ** file. Before writing to meta[6], check that meta[3] indicates
91740           ** that this really is an auto-vacuum capable database.
91741           */
91742           static const VdbeOpList setMeta6[] = {
91743             { OP_Transaction,    0,         1,                 0},    /* 0 */
91744             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
91745             { OP_If,             1,         0,                 0},    /* 2 */
91746             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
91747             { OP_Integer,        0,         1,                 0},    /* 4 */
91748             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
91749           };
91750           int iAddr;
91751           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
91752           sqlite3VdbeChangeP1(v, iAddr, iDb);
91753           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
91754           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
91755           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
91756           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
91757           sqlite3VdbeUsesBtree(v, iDb);
91758         }
91759       }
91760     }
91761   }else
91762 #endif
91763
91764   /*
91765   **  PRAGMA [database.]incremental_vacuum(N)
91766   **
91767   ** Do N steps of incremental vacuuming on a database.
91768   */
91769 #ifndef SQLITE_OMIT_AUTOVACUUM
91770   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
91771     int iLimit, addr;
91772     if( sqlite3ReadSchema(pParse) ){
91773       goto pragma_out;
91774     }
91775     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
91776       iLimit = 0x7fffffff;
91777     }
91778     sqlite3BeginWriteOperation(pParse, 0, iDb);
91779     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
91780     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
91781     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
91782     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
91783     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
91784     sqlite3VdbeJumpHere(v, addr);
91785   }else
91786 #endif
91787
91788 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91789   /*
91790   **  PRAGMA [database.]cache_size
91791   **  PRAGMA [database.]cache_size=N
91792   **
91793   ** The first form reports the current local setting for the
91794   ** page cache size. The second form sets the local
91795   ** page cache size value.  If N is positive then that is the
91796   ** number of pages in the cache.  If N is negative, then the
91797   ** number of pages is adjusted so that the cache uses -N kibibytes
91798   ** of memory.
91799   */
91800   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
91801     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91802     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91803     if( !zRight ){
91804       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
91805     }else{
91806       int size = sqlite3Atoi(zRight);
91807       pDb->pSchema->cache_size = size;
91808       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
91809     }
91810   }else
91811
91812   /*
91813   **   PRAGMA temp_store
91814   **   PRAGMA temp_store = "default"|"memory"|"file"
91815   **
91816   ** Return or set the local value of the temp_store flag.  Changing
91817   ** the local value does not make changes to the disk file and the default
91818   ** value will be restored the next time the database is opened.
91819   **
91820   ** Note that it is possible for the library compile-time options to
91821   ** override this setting
91822   */
91823   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
91824     if( !zRight ){
91825       returnSingleInt(pParse, "temp_store", db->temp_store);
91826     }else{
91827       changeTempStorage(pParse, zRight);
91828     }
91829   }else
91830
91831   /*
91832   **   PRAGMA temp_store_directory
91833   **   PRAGMA temp_store_directory = ""|"directory_name"
91834   **
91835   ** Return or set the local value of the temp_store_directory flag.  Changing
91836   ** the value sets a specific directory to be used for temporary files.
91837   ** Setting to a null string reverts to the default temporary directory search.
91838   ** If temporary directory is changed, then invalidateTempStorage.
91839   **
91840   */
91841   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
91842     if( !zRight ){
91843       if( sqlite3_temp_directory ){
91844         sqlite3VdbeSetNumCols(v, 1);
91845         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
91846             "temp_store_directory", SQLITE_STATIC);
91847         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
91848         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91849       }
91850     }else{
91851 #ifndef SQLITE_OMIT_WSD
91852       if( zRight[0] ){
91853         int res;
91854         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
91855         if( rc!=SQLITE_OK || res==0 ){
91856           sqlite3ErrorMsg(pParse, "not a writable directory");
91857           goto pragma_out;
91858         }
91859       }
91860       if( SQLITE_TEMP_STORE==0
91861        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
91862        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
91863       ){
91864         invalidateTempStorage(pParse);
91865       }
91866       sqlite3_free(sqlite3_temp_directory);
91867       if( zRight[0] ){
91868         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
91869       }else{
91870         sqlite3_temp_directory = 0;
91871       }
91872 #endif /* SQLITE_OMIT_WSD */
91873     }
91874   }else
91875
91876 #if SQLITE_OS_WIN
91877   /*
91878   **   PRAGMA data_store_directory
91879   **   PRAGMA data_store_directory = ""|"directory_name"
91880   **
91881   ** Return or set the local value of the data_store_directory flag.  Changing
91882   ** the value sets a specific directory to be used for database files that
91883   ** were specified with a relative pathname.  Setting to a null string reverts
91884   ** to the default database directory, which for database files specified with
91885   ** a relative path will probably be based on the current directory for the
91886   ** process.  Database file specified with an absolute path are not impacted
91887   ** by this setting, regardless of its value.
91888   **
91889   */
91890   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
91891     if( !zRight ){
91892       if( sqlite3_data_directory ){
91893         sqlite3VdbeSetNumCols(v, 1);
91894         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
91895             "data_store_directory", SQLITE_STATIC);
91896         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
91897         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91898       }
91899     }else{
91900 #ifndef SQLITE_OMIT_WSD
91901       if( zRight[0] ){
91902         int res;
91903         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
91904         if( rc!=SQLITE_OK || res==0 ){
91905           sqlite3ErrorMsg(pParse, "not a writable directory");
91906           goto pragma_out;
91907         }
91908       }
91909       sqlite3_free(sqlite3_data_directory);
91910       if( zRight[0] ){
91911         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
91912       }else{
91913         sqlite3_data_directory = 0;
91914       }
91915 #endif /* SQLITE_OMIT_WSD */
91916     }
91917   }else
91918 #endif
91919
91920 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
91921 #  if defined(__APPLE__)
91922 #    define SQLITE_ENABLE_LOCKING_STYLE 1
91923 #  else
91924 #    define SQLITE_ENABLE_LOCKING_STYLE 0
91925 #  endif
91926 #endif
91927 #if SQLITE_ENABLE_LOCKING_STYLE
91928   /*
91929    **   PRAGMA [database.]lock_proxy_file
91930    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
91931    **
91932    ** Return or set the value of the lock_proxy_file flag.  Changing
91933    ** the value sets a specific file to be used for database access locks.
91934    **
91935    */
91936   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
91937     if( !zRight ){
91938       Pager *pPager = sqlite3BtreePager(pDb->pBt);
91939       char *proxy_file_path = NULL;
91940       sqlite3_file *pFile = sqlite3PagerFile(pPager);
91941       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
91942                            &proxy_file_path);
91943       
91944       if( proxy_file_path ){
91945         sqlite3VdbeSetNumCols(v, 1);
91946         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
91947                               "lock_proxy_file", SQLITE_STATIC);
91948         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
91949         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91950       }
91951     }else{
91952       Pager *pPager = sqlite3BtreePager(pDb->pBt);
91953       sqlite3_file *pFile = sqlite3PagerFile(pPager);
91954       int res;
91955       if( zRight[0] ){
91956         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
91957                                      zRight);
91958       } else {
91959         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
91960                                      NULL);
91961       }
91962       if( res!=SQLITE_OK ){
91963         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
91964         goto pragma_out;
91965       }
91966     }
91967   }else
91968 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
91969     
91970   /*
91971   **   PRAGMA [database.]synchronous
91972   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
91973   **
91974   ** Return or set the local value of the synchronous flag.  Changing
91975   ** the local value does not make changes to the disk file and the
91976   ** default value will be restored the next time the database is
91977   ** opened.
91978   */
91979   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
91980     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91981     if( !zRight ){
91982       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
91983     }else{
91984       if( !db->autoCommit ){
91985         sqlite3ErrorMsg(pParse, 
91986             "Safety level may not be changed inside a transaction");
91987       }else{
91988         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
91989       }
91990     }
91991   }else
91992 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
91993
91994 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
91995   if( flagPragma(pParse, zLeft, zRight) ){
91996     /* The flagPragma() subroutine also generates any necessary code
91997     ** there is nothing more to do here */
91998   }else
91999 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92000
92001 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
92002   /*
92003   **   PRAGMA table_info(<table>)
92004   **
92005   ** Return a single row for each column of the named table. The columns of
92006   ** the returned data set are:
92007   **
92008   ** cid:        Column id (numbered from left to right, starting at 0)
92009   ** name:       Column name
92010   ** type:       Column declaration type.
92011   ** notnull:    True if 'NOT NULL' is part of column declaration
92012   ** dflt_value: The default value for the column, if any.
92013   */
92014   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
92015     Table *pTab;
92016     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92017     pTab = sqlite3FindTable(db, zRight, zDb);
92018     if( pTab ){
92019       int i;
92020       int nHidden = 0;
92021       Column *pCol;
92022       sqlite3VdbeSetNumCols(v, 6);
92023       pParse->nMem = 6;
92024       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
92025       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92026       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
92027       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
92028       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
92029       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
92030       sqlite3ViewGetColumnNames(pParse, pTab);
92031       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92032         if( IsHiddenColumn(pCol) ){
92033           nHidden++;
92034           continue;
92035         }
92036         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
92037         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
92038         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92039            pCol->zType ? pCol->zType : "", 0);
92040         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
92041         if( pCol->zDflt ){
92042           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
92043         }else{
92044           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
92045         }
92046         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
92047         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
92048       }
92049     }
92050   }else
92051
92052   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
92053     Index *pIdx;
92054     Table *pTab;
92055     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92056     pIdx = sqlite3FindIndex(db, zRight, zDb);
92057     if( pIdx ){
92058       int i;
92059       pTab = pIdx->pTable;
92060       sqlite3VdbeSetNumCols(v, 3);
92061       pParse->nMem = 3;
92062       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
92063       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
92064       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
92065       for(i=0; i<pIdx->nColumn; i++){
92066         int cnum = pIdx->aiColumn[i];
92067         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92068         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
92069         assert( pTab->nCol>cnum );
92070         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
92071         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92072       }
92073     }
92074   }else
92075
92076   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
92077     Index *pIdx;
92078     Table *pTab;
92079     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92080     pTab = sqlite3FindTable(db, zRight, zDb);
92081     if( pTab ){
92082       v = sqlite3GetVdbe(pParse);
92083       pIdx = pTab->pIndex;
92084       if( pIdx ){
92085         int i = 0; 
92086         sqlite3VdbeSetNumCols(v, 3);
92087         pParse->nMem = 3;
92088         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92089         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92090         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
92091         while(pIdx){
92092           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92093           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
92094           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
92095           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92096           ++i;
92097           pIdx = pIdx->pNext;
92098         }
92099       }
92100     }
92101   }else
92102
92103   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
92104     int i;
92105     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92106     sqlite3VdbeSetNumCols(v, 3);
92107     pParse->nMem = 3;
92108     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92109     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92110     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
92111     for(i=0; i<db->nDb; i++){
92112       if( db->aDb[i].pBt==0 ) continue;
92113       assert( db->aDb[i].zName!=0 );
92114       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92115       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
92116       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92117            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
92118       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92119     }
92120   }else
92121
92122   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
92123     int i = 0;
92124     HashElem *p;
92125     sqlite3VdbeSetNumCols(v, 2);
92126     pParse->nMem = 2;
92127     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92128     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92129     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
92130       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
92131       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
92132       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
92133       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
92134     }
92135   }else
92136 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
92137
92138 #ifndef SQLITE_OMIT_FOREIGN_KEY
92139   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
92140     FKey *pFK;
92141     Table *pTab;
92142     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92143     pTab = sqlite3FindTable(db, zRight, zDb);
92144     if( pTab ){
92145       v = sqlite3GetVdbe(pParse);
92146       pFK = pTab->pFKey;
92147       if( pFK ){
92148         int i = 0; 
92149         sqlite3VdbeSetNumCols(v, 8);
92150         pParse->nMem = 8;
92151         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
92152         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
92153         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
92154         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
92155         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
92156         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
92157         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
92158         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
92159         while(pFK){
92160           int j;
92161           for(j=0; j<pFK->nCol; j++){
92162             char *zCol = pFK->aCol[j].zCol;
92163             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
92164             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
92165             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92166             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
92167             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
92168             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
92169                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
92170             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
92171             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
92172             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
92173             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
92174             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
92175           }
92176           ++i;
92177           pFK = pFK->pNextFrom;
92178         }
92179       }
92180     }
92181   }else
92182 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
92183
92184 #ifndef NDEBUG
92185   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
92186     if( zRight ){
92187       if( sqlite3GetBoolean(zRight, 0) ){
92188         sqlite3ParserTrace(stderr, "parser: ");
92189       }else{
92190         sqlite3ParserTrace(0, 0);
92191       }
92192     }
92193   }else
92194 #endif
92195
92196   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
92197   ** used will be case sensitive or not depending on the RHS.
92198   */
92199   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
92200     if( zRight ){
92201       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
92202     }
92203   }else
92204
92205 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
92206 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
92207 #endif
92208
92209 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
92210   /* Pragma "quick_check" is an experimental reduced version of 
92211   ** integrity_check designed to detect most database corruption
92212   ** without most of the overhead of a full integrity-check.
92213   */
92214   if( sqlite3StrICmp(zLeft, "integrity_check")==0
92215    || sqlite3StrICmp(zLeft, "quick_check")==0 
92216   ){
92217     int i, j, addr, mxErr;
92218
92219     /* Code that appears at the end of the integrity check.  If no error
92220     ** messages have been generated, output OK.  Otherwise output the
92221     ** error message
92222     */
92223     static const VdbeOpList endCode[] = {
92224       { OP_AddImm,      1, 0,        0},    /* 0 */
92225       { OP_IfNeg,       1, 0,        0},    /* 1 */
92226       { OP_String8,     0, 3,        0},    /* 2 */
92227       { OP_ResultRow,   3, 1,        0},
92228     };
92229
92230     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
92231
92232     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
92233     ** then iDb is set to the index of the database identified by <db>.
92234     ** In this case, the integrity of database iDb only is verified by
92235     ** the VDBE created below.
92236     **
92237     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
92238     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
92239     ** to -1 here, to indicate that the VDBE should verify the integrity
92240     ** of all attached databases.  */
92241     assert( iDb>=0 );
92242     assert( iDb==0 || pId2->z );
92243     if( pId2->z==0 ) iDb = -1;
92244
92245     /* Initialize the VDBE program */
92246     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92247     pParse->nMem = 6;
92248     sqlite3VdbeSetNumCols(v, 1);
92249     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
92250
92251     /* Set the maximum error count */
92252     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
92253     if( zRight ){
92254       sqlite3GetInt32(zRight, &mxErr);
92255       if( mxErr<=0 ){
92256         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
92257       }
92258     }
92259     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
92260
92261     /* Do an integrity check on each database file */
92262     for(i=0; i<db->nDb; i++){
92263       HashElem *x;
92264       Hash *pTbls;
92265       int cnt = 0;
92266
92267       if( OMIT_TEMPDB && i==1 ) continue;
92268       if( iDb>=0 && i!=iDb ) continue;
92269
92270       sqlite3CodeVerifySchema(pParse, i);
92271       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
92272       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
92273       sqlite3VdbeJumpHere(v, addr);
92274
92275       /* Do an integrity check of the B-Tree
92276       **
92277       ** Begin by filling registers 2, 3, ... with the root pages numbers
92278       ** for all tables and indices in the database.
92279       */
92280       assert( sqlite3SchemaMutexHeld(db, i, 0) );
92281       pTbls = &db->aDb[i].pSchema->tblHash;
92282       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
92283         Table *pTab = sqliteHashData(x);
92284         Index *pIdx;
92285         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
92286         cnt++;
92287         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92288           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
92289           cnt++;
92290         }
92291       }
92292
92293       /* Make sure sufficient number of registers have been allocated */
92294       if( pParse->nMem < cnt+4 ){
92295         pParse->nMem = cnt+4;
92296       }
92297
92298       /* Do the b-tree integrity checks */
92299       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
92300       sqlite3VdbeChangeP5(v, (u8)i);
92301       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
92302       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92303          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
92304          P4_DYNAMIC);
92305       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
92306       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
92307       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
92308       sqlite3VdbeJumpHere(v, addr);
92309
92310       /* Make sure all the indices are constructed correctly.
92311       */
92312       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
92313         Table *pTab = sqliteHashData(x);
92314         Index *pIdx;
92315         int loopTop;
92316
92317         if( pTab->pIndex==0 ) continue;
92318         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
92319         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
92320         sqlite3VdbeJumpHere(v, addr);
92321         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
92322         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
92323         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
92324         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
92325         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92326           int jmp2;
92327           int r1;
92328           static const VdbeOpList idxErr[] = {
92329             { OP_AddImm,      1, -1,  0},
92330             { OP_String8,     0,  3,  0},    /* 1 */
92331             { OP_Rowid,       1,  4,  0},
92332             { OP_String8,     0,  5,  0},    /* 3 */
92333             { OP_String8,     0,  6,  0},    /* 4 */
92334             { OP_Concat,      4,  3,  3},
92335             { OP_Concat,      5,  3,  3},
92336             { OP_Concat,      6,  3,  3},
92337             { OP_ResultRow,   3,  1,  0},
92338             { OP_IfPos,       1,  0,  0},    /* 9 */
92339             { OP_Halt,        0,  0,  0},
92340           };
92341           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
92342           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
92343           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
92344           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
92345           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
92346           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
92347           sqlite3VdbeJumpHere(v, addr+9);
92348           sqlite3VdbeJumpHere(v, jmp2);
92349         }
92350         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
92351         sqlite3VdbeJumpHere(v, loopTop);
92352         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92353           static const VdbeOpList cntIdx[] = {
92354              { OP_Integer,      0,  3,  0},
92355              { OP_Rewind,       0,  0,  0},  /* 1 */
92356              { OP_AddImm,       3,  1,  0},
92357              { OP_Next,         0,  0,  0},  /* 3 */
92358              { OP_Eq,           2,  0,  3},  /* 4 */
92359              { OP_AddImm,       1, -1,  0},
92360              { OP_String8,      0,  2,  0},  /* 6 */
92361              { OP_String8,      0,  3,  0},  /* 7 */
92362              { OP_Concat,       3,  2,  2},
92363              { OP_ResultRow,    2,  1,  0},
92364           };
92365           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
92366           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
92367           sqlite3VdbeJumpHere(v, addr);
92368           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
92369           sqlite3VdbeChangeP1(v, addr+1, j+2);
92370           sqlite3VdbeChangeP2(v, addr+1, addr+4);
92371           sqlite3VdbeChangeP1(v, addr+3, j+2);
92372           sqlite3VdbeChangeP2(v, addr+3, addr+2);
92373           sqlite3VdbeJumpHere(v, addr+4);
92374           sqlite3VdbeChangeP4(v, addr+6, 
92375                      "wrong # of entries in index ", P4_STATIC);
92376           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
92377         }
92378       } 
92379     }
92380     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
92381     sqlite3VdbeChangeP2(v, addr, -mxErr);
92382     sqlite3VdbeJumpHere(v, addr+1);
92383     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
92384   }else
92385 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
92386
92387 #ifndef SQLITE_OMIT_UTF16
92388   /*
92389   **   PRAGMA encoding
92390   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
92391   **
92392   ** In its first form, this pragma returns the encoding of the main
92393   ** database. If the database is not initialized, it is initialized now.
92394   **
92395   ** The second form of this pragma is a no-op if the main database file
92396   ** has not already been initialized. In this case it sets the default
92397   ** encoding that will be used for the main database file if a new file
92398   ** is created. If an existing main database file is opened, then the
92399   ** default text encoding for the existing database is used.
92400   ** 
92401   ** In all cases new databases created using the ATTACH command are
92402   ** created to use the same default text encoding as the main database. If
92403   ** the main database has not been initialized and/or created when ATTACH
92404   ** is executed, this is done before the ATTACH operation.
92405   **
92406   ** In the second form this pragma sets the text encoding to be used in
92407   ** new database files created using this database handle. It is only
92408   ** useful if invoked immediately after the main database i
92409   */
92410   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
92411     static const struct EncName {
92412       char *zName;
92413       u8 enc;
92414     } encnames[] = {
92415       { "UTF8",     SQLITE_UTF8        },
92416       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
92417       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
92418       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
92419       { "UTF16le",  SQLITE_UTF16LE     },
92420       { "UTF16be",  SQLITE_UTF16BE     },
92421       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
92422       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
92423       { 0, 0 }
92424     };
92425     const struct EncName *pEnc;
92426     if( !zRight ){    /* "PRAGMA encoding" */
92427       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92428       sqlite3VdbeSetNumCols(v, 1);
92429       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
92430       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
92431       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
92432       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
92433       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
92434       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
92435       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92436     }else{                        /* "PRAGMA encoding = XXX" */
92437       /* Only change the value of sqlite.enc if the database handle is not
92438       ** initialized. If the main database exists, the new sqlite.enc value
92439       ** will be overwritten when the schema is next loaded. If it does not
92440       ** already exists, it will be created to use the new encoding value.
92441       */
92442       if( 
92443         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
92444         DbHasProperty(db, 0, DB_Empty) 
92445       ){
92446         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
92447           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
92448             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
92449             break;
92450           }
92451         }
92452         if( !pEnc->zName ){
92453           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
92454         }
92455       }
92456     }
92457   }else
92458 #endif /* SQLITE_OMIT_UTF16 */
92459
92460 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
92461   /*
92462   **   PRAGMA [database.]schema_version
92463   **   PRAGMA [database.]schema_version = <integer>
92464   **
92465   **   PRAGMA [database.]user_version
92466   **   PRAGMA [database.]user_version = <integer>
92467   **
92468   ** The pragma's schema_version and user_version are used to set or get
92469   ** the value of the schema-version and user-version, respectively. Both
92470   ** the schema-version and the user-version are 32-bit signed integers
92471   ** stored in the database header.
92472   **
92473   ** The schema-cookie is usually only manipulated internally by SQLite. It
92474   ** is incremented by SQLite whenever the database schema is modified (by
92475   ** creating or dropping a table or index). The schema version is used by
92476   ** SQLite each time a query is executed to ensure that the internal cache
92477   ** of the schema used when compiling the SQL query matches the schema of
92478   ** the database against which the compiled query is actually executed.
92479   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
92480   ** the schema-version is potentially dangerous and may lead to program
92481   ** crashes or database corruption. Use with caution!
92482   **
92483   ** The user-version is not used internally by SQLite. It may be used by
92484   ** applications for any purpose.
92485   */
92486   if( sqlite3StrICmp(zLeft, "schema_version")==0 
92487    || sqlite3StrICmp(zLeft, "user_version")==0 
92488    || sqlite3StrICmp(zLeft, "freelist_count")==0 
92489   ){
92490     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
92491     sqlite3VdbeUsesBtree(v, iDb);
92492     switch( zLeft[0] ){
92493       case 'f': case 'F':
92494         iCookie = BTREE_FREE_PAGE_COUNT;
92495         break;
92496       case 's': case 'S':
92497         iCookie = BTREE_SCHEMA_VERSION;
92498         break;
92499       default:
92500         iCookie = BTREE_USER_VERSION;
92501         break;
92502     }
92503
92504     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
92505       /* Write the specified cookie value */
92506       static const VdbeOpList setCookie[] = {
92507         { OP_Transaction,    0,  1,  0},    /* 0 */
92508         { OP_Integer,        0,  1,  0},    /* 1 */
92509         { OP_SetCookie,      0,  0,  1},    /* 2 */
92510       };
92511       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
92512       sqlite3VdbeChangeP1(v, addr, iDb);
92513       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
92514       sqlite3VdbeChangeP1(v, addr+2, iDb);
92515       sqlite3VdbeChangeP2(v, addr+2, iCookie);
92516     }else{
92517       /* Read the specified cookie value */
92518       static const VdbeOpList readCookie[] = {
92519         { OP_Transaction,     0,  0,  0},    /* 0 */
92520         { OP_ReadCookie,      0,  1,  0},    /* 1 */
92521         { OP_ResultRow,       1,  1,  0}
92522       };
92523       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
92524       sqlite3VdbeChangeP1(v, addr, iDb);
92525       sqlite3VdbeChangeP1(v, addr+1, iDb);
92526       sqlite3VdbeChangeP3(v, addr+1, iCookie);
92527       sqlite3VdbeSetNumCols(v, 1);
92528       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92529     }
92530   }else
92531 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
92532
92533 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
92534   /*
92535   **   PRAGMA compile_options
92536   **
92537   ** Return the names of all compile-time options used in this build,
92538   ** one option per row.
92539   */
92540   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
92541     int i = 0;
92542     const char *zOpt;
92543     sqlite3VdbeSetNumCols(v, 1);
92544     pParse->nMem = 1;
92545     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
92546     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
92547       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
92548       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92549     }
92550   }else
92551 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
92552
92553 #ifndef SQLITE_OMIT_WAL
92554   /*
92555   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
92556   **
92557   ** Checkpoint the database.
92558   */
92559   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
92560     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
92561     int eMode = SQLITE_CHECKPOINT_PASSIVE;
92562     if( zRight ){
92563       if( sqlite3StrICmp(zRight, "full")==0 ){
92564         eMode = SQLITE_CHECKPOINT_FULL;
92565       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
92566         eMode = SQLITE_CHECKPOINT_RESTART;
92567       }
92568     }
92569     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92570     sqlite3VdbeSetNumCols(v, 3);
92571     pParse->nMem = 3;
92572     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
92573     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
92574     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
92575
92576     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
92577     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92578   }else
92579
92580   /*
92581   **   PRAGMA wal_autocheckpoint
92582   **   PRAGMA wal_autocheckpoint = N
92583   **
92584   ** Configure a database connection to automatically checkpoint a database
92585   ** after accumulating N frames in the log. Or query for the current value
92586   ** of N.
92587   */
92588   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
92589     if( zRight ){
92590       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
92591     }
92592     returnSingleInt(pParse, "wal_autocheckpoint", 
92593        db->xWalCallback==sqlite3WalDefaultHook ? 
92594            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
92595   }else
92596 #endif
92597
92598   /*
92599   **  PRAGMA shrink_memory
92600   **
92601   ** This pragma attempts to free as much memory as possible from the
92602   ** current database connection.
92603   */
92604   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
92605     sqlite3_db_release_memory(db);
92606   }else
92607
92608 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
92609   /*
92610   ** Report the current state of file logs for all databases
92611   */
92612   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
92613     static const char *const azLockName[] = {
92614       "unlocked", "shared", "reserved", "pending", "exclusive"
92615     };
92616     int i;
92617     sqlite3VdbeSetNumCols(v, 2);
92618     pParse->nMem = 2;
92619     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
92620     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
92621     for(i=0; i<db->nDb; i++){
92622       Btree *pBt;
92623       Pager *pPager;
92624       const char *zState = "unknown";
92625       int j;
92626       if( db->aDb[i].zName==0 ) continue;
92627       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
92628       pBt = db->aDb[i].pBt;
92629       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
92630         zState = "closed";
92631       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
92632                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
92633          zState = azLockName[j];
92634       }
92635       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
92636       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
92637     }
92638
92639   }else
92640 #endif
92641
92642 #ifdef SQLITE_HAS_CODEC
92643   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
92644     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
92645   }else
92646   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
92647     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
92648   }else
92649   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
92650                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
92651     int i, h1, h2;
92652     char zKey[40];
92653     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
92654       h1 += 9*(1&(h1>>6));
92655       h2 += 9*(1&(h2>>6));
92656       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
92657     }
92658     if( (zLeft[3] & 0xf)==0xb ){
92659       sqlite3_key(db, zKey, i/2);
92660     }else{
92661       sqlite3_rekey(db, zKey, i/2);
92662     }
92663   }else
92664 #endif
92665 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
92666   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
92667 #ifdef SQLITE_HAS_CODEC
92668     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
92669       sqlite3_activate_see(&zRight[4]);
92670     }
92671 #endif
92672 #ifdef SQLITE_ENABLE_CEROD
92673     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
92674       sqlite3_activate_cerod(&zRight[6]);
92675     }
92676 #endif
92677   }else
92678 #endif
92679
92680  
92681   {/* Empty ELSE clause */}
92682
92683   /*
92684   ** Reset the safety level, in case the fullfsync flag or synchronous
92685   ** setting changed.
92686   */
92687 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92688   if( db->autoCommit ){
92689     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
92690                (db->flags&SQLITE_FullFSync)!=0,
92691                (db->flags&SQLITE_CkptFullFSync)!=0);
92692   }
92693 #endif
92694 pragma_out:
92695   sqlite3DbFree(db, zLeft);
92696   sqlite3DbFree(db, zRight);
92697 }
92698
92699 #endif /* SQLITE_OMIT_PRAGMA */
92700
92701 /************** End of pragma.c **********************************************/
92702 /************** Begin file prepare.c *****************************************/
92703 /*
92704 ** 2005 May 25
92705 **
92706 ** The author disclaims copyright to this source code.  In place of
92707 ** a legal notice, here is a blessing:
92708 **
92709 **    May you do good and not evil.
92710 **    May you find forgiveness for yourself and forgive others.
92711 **    May you share freely, never taking more than you give.
92712 **
92713 *************************************************************************
92714 ** This file contains the implementation of the sqlite3_prepare()
92715 ** interface, and routines that contribute to loading the database schema
92716 ** from disk.
92717 */
92718
92719 /*
92720 ** Fill the InitData structure with an error message that indicates
92721 ** that the database is corrupt.
92722 */
92723 static void corruptSchema(
92724   InitData *pData,     /* Initialization context */
92725   const char *zObj,    /* Object being parsed at the point of error */
92726   const char *zExtra   /* Error information */
92727 ){
92728   sqlite3 *db = pData->db;
92729   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
92730     if( zObj==0 ) zObj = "?";
92731     sqlite3SetString(pData->pzErrMsg, db,
92732       "malformed database schema (%s)", zObj);
92733     if( zExtra ){
92734       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
92735                                  "%s - %s", *pData->pzErrMsg, zExtra);
92736     }
92737   }
92738   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
92739 }
92740
92741 /*
92742 ** This is the callback routine for the code that initializes the
92743 ** database.  See sqlite3Init() below for additional information.
92744 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
92745 **
92746 ** Each callback contains the following information:
92747 **
92748 **     argv[0] = name of thing being created
92749 **     argv[1] = root page number for table or index. 0 for trigger or view.
92750 **     argv[2] = SQL text for the CREATE statement.
92751 **
92752 */
92753 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
92754   InitData *pData = (InitData*)pInit;
92755   sqlite3 *db = pData->db;
92756   int iDb = pData->iDb;
92757
92758   assert( argc==3 );
92759   UNUSED_PARAMETER2(NotUsed, argc);
92760   assert( sqlite3_mutex_held(db->mutex) );
92761   DbClearProperty(db, iDb, DB_Empty);
92762   if( db->mallocFailed ){
92763     corruptSchema(pData, argv[0], 0);
92764     return 1;
92765   }
92766
92767   assert( iDb>=0 && iDb<db->nDb );
92768   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
92769   if( argv[1]==0 ){
92770     corruptSchema(pData, argv[0], 0);
92771   }else if( argv[2] && argv[2][0] ){
92772     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
92773     ** But because db->init.busy is set to 1, no VDBE code is generated
92774     ** or executed.  All the parser does is build the internal data
92775     ** structures that describe the table, index, or view.
92776     */
92777     int rc;
92778     sqlite3_stmt *pStmt;
92779     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
92780
92781     assert( db->init.busy );
92782     db->init.iDb = iDb;
92783     db->init.newTnum = sqlite3Atoi(argv[1]);
92784     db->init.orphanTrigger = 0;
92785     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
92786     rc = db->errCode;
92787     assert( (rc&0xFF)==(rcp&0xFF) );
92788     db->init.iDb = 0;
92789     if( SQLITE_OK!=rc ){
92790       if( db->init.orphanTrigger ){
92791         assert( iDb==1 );
92792       }else{
92793         pData->rc = rc;
92794         if( rc==SQLITE_NOMEM ){
92795           db->mallocFailed = 1;
92796         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
92797           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
92798         }
92799       }
92800     }
92801     sqlite3_finalize(pStmt);
92802   }else if( argv[0]==0 ){
92803     corruptSchema(pData, 0, 0);
92804   }else{
92805     /* If the SQL column is blank it means this is an index that
92806     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
92807     ** constraint for a CREATE TABLE.  The index should have already
92808     ** been created when we processed the CREATE TABLE.  All we have
92809     ** to do here is record the root page number for that index.
92810     */
92811     Index *pIndex;
92812     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
92813     if( pIndex==0 ){
92814       /* This can occur if there exists an index on a TEMP table which
92815       ** has the same name as another index on a permanent index.  Since
92816       ** the permanent table is hidden by the TEMP table, we can also
92817       ** safely ignore the index on the permanent table.
92818       */
92819       /* Do Nothing */;
92820     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
92821       corruptSchema(pData, argv[0], "invalid rootpage");
92822     }
92823   }
92824   return 0;
92825 }
92826
92827 /*
92828 ** Attempt to read the database schema and initialize internal
92829 ** data structures for a single database file.  The index of the
92830 ** database file is given by iDb.  iDb==0 is used for the main
92831 ** database.  iDb==1 should never be used.  iDb>=2 is used for
92832 ** auxiliary databases.  Return one of the SQLITE_ error codes to
92833 ** indicate success or failure.
92834 */
92835 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
92836   int rc;
92837   int i;
92838   int size;
92839   Table *pTab;
92840   Db *pDb;
92841   char const *azArg[4];
92842   int meta[5];
92843   InitData initData;
92844   char const *zMasterSchema;
92845   char const *zMasterName;
92846   int openedTransaction = 0;
92847
92848   /*
92849   ** The master database table has a structure like this
92850   */
92851   static const char master_schema[] = 
92852      "CREATE TABLE sqlite_master(\n"
92853      "  type text,\n"
92854      "  name text,\n"
92855      "  tbl_name text,\n"
92856      "  rootpage integer,\n"
92857      "  sql text\n"
92858      ")"
92859   ;
92860 #ifndef SQLITE_OMIT_TEMPDB
92861   static const char temp_master_schema[] = 
92862      "CREATE TEMP TABLE sqlite_temp_master(\n"
92863      "  type text,\n"
92864      "  name text,\n"
92865      "  tbl_name text,\n"
92866      "  rootpage integer,\n"
92867      "  sql text\n"
92868      ")"
92869   ;
92870 #else
92871   #define temp_master_schema 0
92872 #endif
92873
92874   assert( iDb>=0 && iDb<db->nDb );
92875   assert( db->aDb[iDb].pSchema );
92876   assert( sqlite3_mutex_held(db->mutex) );
92877   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
92878
92879   /* zMasterSchema and zInitScript are set to point at the master schema
92880   ** and initialisation script appropriate for the database being
92881   ** initialised. zMasterName is the name of the master table.
92882   */
92883   if( !OMIT_TEMPDB && iDb==1 ){
92884     zMasterSchema = temp_master_schema;
92885   }else{
92886     zMasterSchema = master_schema;
92887   }
92888   zMasterName = SCHEMA_TABLE(iDb);
92889
92890   /* Construct the schema tables.  */
92891   azArg[0] = zMasterName;
92892   azArg[1] = "1";
92893   azArg[2] = zMasterSchema;
92894   azArg[3] = 0;
92895   initData.db = db;
92896   initData.iDb = iDb;
92897   initData.rc = SQLITE_OK;
92898   initData.pzErrMsg = pzErrMsg;
92899   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
92900   if( initData.rc ){
92901     rc = initData.rc;
92902     goto error_out;
92903   }
92904   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
92905   if( ALWAYS(pTab) ){
92906     pTab->tabFlags |= TF_Readonly;
92907   }
92908
92909   /* Create a cursor to hold the database open
92910   */
92911   pDb = &db->aDb[iDb];
92912   if( pDb->pBt==0 ){
92913     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
92914       DbSetProperty(db, 1, DB_SchemaLoaded);
92915     }
92916     return SQLITE_OK;
92917   }
92918
92919   /* If there is not already a read-only (or read-write) transaction opened
92920   ** on the b-tree database, open one now. If a transaction is opened, it 
92921   ** will be closed before this function returns.  */
92922   sqlite3BtreeEnter(pDb->pBt);
92923   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
92924     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
92925     if( rc!=SQLITE_OK ){
92926       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
92927       goto initone_error_out;
92928     }
92929     openedTransaction = 1;
92930   }
92931
92932   /* Get the database meta information.
92933   **
92934   ** Meta values are as follows:
92935   **    meta[0]   Schema cookie.  Changes with each schema change.
92936   **    meta[1]   File format of schema layer.
92937   **    meta[2]   Size of the page cache.
92938   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
92939   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
92940   **    meta[5]   User version
92941   **    meta[6]   Incremental vacuum mode
92942   **    meta[7]   unused
92943   **    meta[8]   unused
92944   **    meta[9]   unused
92945   **
92946   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
92947   ** the possible values of meta[4].
92948   */
92949   for(i=0; i<ArraySize(meta); i++){
92950     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
92951   }
92952   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
92953
92954   /* If opening a non-empty database, check the text encoding. For the
92955   ** main database, set sqlite3.enc to the encoding of the main database.
92956   ** For an attached db, it is an error if the encoding is not the same
92957   ** as sqlite3.enc.
92958   */
92959   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
92960     if( iDb==0 ){
92961       u8 encoding;
92962       /* If opening the main database, set ENC(db). */
92963       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
92964       if( encoding==0 ) encoding = SQLITE_UTF8;
92965       ENC(db) = encoding;
92966     }else{
92967       /* If opening an attached database, the encoding much match ENC(db) */
92968       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
92969         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
92970             " text encoding as main database");
92971         rc = SQLITE_ERROR;
92972         goto initone_error_out;
92973       }
92974     }
92975   }else{
92976     DbSetProperty(db, iDb, DB_Empty);
92977   }
92978   pDb->pSchema->enc = ENC(db);
92979
92980   if( pDb->pSchema->cache_size==0 ){
92981 #ifndef SQLITE_OMIT_DEPRECATED
92982     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
92983     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
92984     pDb->pSchema->cache_size = size;
92985 #else
92986     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
92987 #endif
92988     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92989   }
92990
92991   /*
92992   ** file_format==1    Version 3.0.0.
92993   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
92994   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
92995   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
92996   */
92997   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
92998   if( pDb->pSchema->file_format==0 ){
92999     pDb->pSchema->file_format = 1;
93000   }
93001   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
93002     sqlite3SetString(pzErrMsg, db, "unsupported file format");
93003     rc = SQLITE_ERROR;
93004     goto initone_error_out;
93005   }
93006
93007   /* Ticket #2804:  When we open a database in the newer file format,
93008   ** clear the legacy_file_format pragma flag so that a VACUUM will
93009   ** not downgrade the database and thus invalidate any descending
93010   ** indices that the user might have created.
93011   */
93012   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93013     db->flags &= ~SQLITE_LegacyFileFmt;
93014   }
93015
93016   /* Read the schema information out of the schema tables
93017   */
93018   assert( db->init.busy );
93019   {
93020     char *zSql;
93021     zSql = sqlite3MPrintf(db, 
93022         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93023         db->aDb[iDb].zName, zMasterName);
93024 #ifndef SQLITE_OMIT_AUTHORIZATION
93025     {
93026       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93027       xAuth = db->xAuth;
93028       db->xAuth = 0;
93029 #endif
93030       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
93031 #ifndef SQLITE_OMIT_AUTHORIZATION
93032       db->xAuth = xAuth;
93033     }
93034 #endif
93035     if( rc==SQLITE_OK ) rc = initData.rc;
93036     sqlite3DbFree(db, zSql);
93037 #ifndef SQLITE_OMIT_ANALYZE
93038     if( rc==SQLITE_OK ){
93039       sqlite3AnalysisLoad(db, iDb);
93040     }
93041 #endif
93042   }
93043   if( db->mallocFailed ){
93044     rc = SQLITE_NOMEM;
93045     sqlite3ResetAllSchemasOfConnection(db);
93046   }
93047   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
93048     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
93049     ** the schema loaded, even if errors occurred. In this situation the 
93050     ** current sqlite3_prepare() operation will fail, but the following one
93051     ** will attempt to compile the supplied statement against whatever subset
93052     ** of the schema was loaded before the error occurred. The primary
93053     ** purpose of this is to allow access to the sqlite_master table
93054     ** even when its contents have been corrupted.
93055     */
93056     DbSetProperty(db, iDb, DB_SchemaLoaded);
93057     rc = SQLITE_OK;
93058   }
93059
93060   /* Jump here for an error that occurs after successfully allocating
93061   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
93062   ** before that point, jump to error_out.
93063   */
93064 initone_error_out:
93065   if( openedTransaction ){
93066     sqlite3BtreeCommit(pDb->pBt);
93067   }
93068   sqlite3BtreeLeave(pDb->pBt);
93069
93070 error_out:
93071   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
93072     db->mallocFailed = 1;
93073   }
93074   return rc;
93075 }
93076
93077 /*
93078 ** Initialize all database files - the main database file, the file
93079 ** used to store temporary tables, and any additional database files
93080 ** created using ATTACH statements.  Return a success code.  If an
93081 ** error occurs, write an error message into *pzErrMsg.
93082 **
93083 ** After a database is initialized, the DB_SchemaLoaded bit is set
93084 ** bit is set in the flags field of the Db structure. If the database
93085 ** file was of zero-length, then the DB_Empty flag is also set.
93086 */
93087 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
93088   int i, rc;
93089   int commit_internal = !(db->flags&SQLITE_InternChanges);
93090   
93091   assert( sqlite3_mutex_held(db->mutex) );
93092   rc = SQLITE_OK;
93093   db->init.busy = 1;
93094   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
93095     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
93096     rc = sqlite3InitOne(db, i, pzErrMsg);
93097     if( rc ){
93098       sqlite3ResetOneSchema(db, i);
93099     }
93100   }
93101
93102   /* Once all the other databases have been initialised, load the schema
93103   ** for the TEMP database. This is loaded last, as the TEMP database
93104   ** schema may contain references to objects in other databases.
93105   */
93106 #ifndef SQLITE_OMIT_TEMPDB
93107   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
93108                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
93109     rc = sqlite3InitOne(db, 1, pzErrMsg);
93110     if( rc ){
93111       sqlite3ResetOneSchema(db, 1);
93112     }
93113   }
93114 #endif
93115
93116   db->init.busy = 0;
93117   if( rc==SQLITE_OK && commit_internal ){
93118     sqlite3CommitInternalChanges(db);
93119   }
93120
93121   return rc; 
93122 }
93123
93124 /*
93125 ** This routine is a no-op if the database schema is already initialised.
93126 ** Otherwise, the schema is loaded. An error code is returned.
93127 */
93128 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
93129   int rc = SQLITE_OK;
93130   sqlite3 *db = pParse->db;
93131   assert( sqlite3_mutex_held(db->mutex) );
93132   if( !db->init.busy ){
93133     rc = sqlite3Init(db, &pParse->zErrMsg);
93134   }
93135   if( rc!=SQLITE_OK ){
93136     pParse->rc = rc;
93137     pParse->nErr++;
93138   }
93139   return rc;
93140 }
93141
93142
93143 /*
93144 ** Check schema cookies in all databases.  If any cookie is out
93145 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
93146 ** make no changes to pParse->rc.
93147 */
93148 static void schemaIsValid(Parse *pParse){
93149   sqlite3 *db = pParse->db;
93150   int iDb;
93151   int rc;
93152   int cookie;
93153
93154   assert( pParse->checkSchema );
93155   assert( sqlite3_mutex_held(db->mutex) );
93156   for(iDb=0; iDb<db->nDb; iDb++){
93157     int openedTransaction = 0;         /* True if a transaction is opened */
93158     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
93159     if( pBt==0 ) continue;
93160
93161     /* If there is not already a read-only (or read-write) transaction opened
93162     ** on the b-tree database, open one now. If a transaction is opened, it 
93163     ** will be closed immediately after reading the meta-value. */
93164     if( !sqlite3BtreeIsInReadTrans(pBt) ){
93165       rc = sqlite3BtreeBeginTrans(pBt, 0);
93166       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
93167         db->mallocFailed = 1;
93168       }
93169       if( rc!=SQLITE_OK ) return;
93170       openedTransaction = 1;
93171     }
93172
93173     /* Read the schema cookie from the database. If it does not match the 
93174     ** value stored as part of the in-memory schema representation,
93175     ** set Parse.rc to SQLITE_SCHEMA. */
93176     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
93177     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93178     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
93179       sqlite3ResetOneSchema(db, iDb);
93180       pParse->rc = SQLITE_SCHEMA;
93181     }
93182
93183     /* Close the transaction, if one was opened. */
93184     if( openedTransaction ){
93185       sqlite3BtreeCommit(pBt);
93186     }
93187   }
93188 }
93189
93190 /*
93191 ** Convert a schema pointer into the iDb index that indicates
93192 ** which database file in db->aDb[] the schema refers to.
93193 **
93194 ** If the same database is attached more than once, the first
93195 ** attached database is returned.
93196 */
93197 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
93198   int i = -1000000;
93199
93200   /* If pSchema is NULL, then return -1000000. This happens when code in 
93201   ** expr.c is trying to resolve a reference to a transient table (i.e. one
93202   ** created by a sub-select). In this case the return value of this 
93203   ** function should never be used.
93204   **
93205   ** We return -1000000 instead of the more usual -1 simply because using
93206   ** -1000000 as the incorrect index into db->aDb[] is much 
93207   ** more likely to cause a segfault than -1 (of course there are assert()
93208   ** statements too, but it never hurts to play the odds).
93209   */
93210   assert( sqlite3_mutex_held(db->mutex) );
93211   if( pSchema ){
93212     for(i=0; ALWAYS(i<db->nDb); i++){
93213       if( db->aDb[i].pSchema==pSchema ){
93214         break;
93215       }
93216     }
93217     assert( i>=0 && i<db->nDb );
93218   }
93219   return i;
93220 }
93221
93222 /*
93223 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
93224 */
93225 static int sqlite3Prepare(
93226   sqlite3 *db,              /* Database handle. */
93227   const char *zSql,         /* UTF-8 encoded SQL statement. */
93228   int nBytes,               /* Length of zSql in bytes. */
93229   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
93230   Vdbe *pReprepare,         /* VM being reprepared */
93231   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93232   const char **pzTail       /* OUT: End of parsed string */
93233 ){
93234   Parse *pParse;            /* Parsing context */
93235   char *zErrMsg = 0;        /* Error message */
93236   int rc = SQLITE_OK;       /* Result code */
93237   int i;                    /* Loop counter */
93238
93239   /* Allocate the parsing context */
93240   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
93241   if( pParse==0 ){
93242     rc = SQLITE_NOMEM;
93243     goto end_prepare;
93244   }
93245   pParse->pReprepare = pReprepare;
93246   assert( ppStmt && *ppStmt==0 );
93247   assert( !db->mallocFailed );
93248   assert( sqlite3_mutex_held(db->mutex) );
93249
93250   /* Check to verify that it is possible to get a read lock on all
93251   ** database schemas.  The inability to get a read lock indicates that
93252   ** some other database connection is holding a write-lock, which in
93253   ** turn means that the other connection has made uncommitted changes
93254   ** to the schema.
93255   **
93256   ** Were we to proceed and prepare the statement against the uncommitted
93257   ** schema changes and if those schema changes are subsequently rolled
93258   ** back and different changes are made in their place, then when this
93259   ** prepared statement goes to run the schema cookie would fail to detect
93260   ** the schema change.  Disaster would follow.
93261   **
93262   ** This thread is currently holding mutexes on all Btrees (because
93263   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
93264   ** is not possible for another thread to start a new schema change
93265   ** while this routine is running.  Hence, we do not need to hold 
93266   ** locks on the schema, we just need to make sure nobody else is 
93267   ** holding them.
93268   **
93269   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
93270   ** but it does *not* override schema lock detection, so this all still
93271   ** works even if READ_UNCOMMITTED is set.
93272   */
93273   for(i=0; i<db->nDb; i++) {
93274     Btree *pBt = db->aDb[i].pBt;
93275     if( pBt ){
93276       assert( sqlite3BtreeHoldsMutex(pBt) );
93277       rc = sqlite3BtreeSchemaLocked(pBt);
93278       if( rc ){
93279         const char *zDb = db->aDb[i].zName;
93280         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
93281         testcase( db->flags & SQLITE_ReadUncommitted );
93282         goto end_prepare;
93283       }
93284     }
93285   }
93286
93287   sqlite3VtabUnlockList(db);
93288
93289   pParse->db = db;
93290   pParse->nQueryLoop = (double)1;
93291   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
93292     char *zSqlCopy;
93293     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
93294     testcase( nBytes==mxLen );
93295     testcase( nBytes==mxLen+1 );
93296     if( nBytes>mxLen ){
93297       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
93298       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
93299       goto end_prepare;
93300     }
93301     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
93302     if( zSqlCopy ){
93303       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
93304       sqlite3DbFree(db, zSqlCopy);
93305       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
93306     }else{
93307       pParse->zTail = &zSql[nBytes];
93308     }
93309   }else{
93310     sqlite3RunParser(pParse, zSql, &zErrMsg);
93311   }
93312   assert( 1==(int)pParse->nQueryLoop );
93313
93314   if( db->mallocFailed ){
93315     pParse->rc = SQLITE_NOMEM;
93316   }
93317   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
93318   if( pParse->checkSchema ){
93319     schemaIsValid(pParse);
93320   }
93321   if( db->mallocFailed ){
93322     pParse->rc = SQLITE_NOMEM;
93323   }
93324   if( pzTail ){
93325     *pzTail = pParse->zTail;
93326   }
93327   rc = pParse->rc;
93328
93329 #ifndef SQLITE_OMIT_EXPLAIN
93330   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
93331     static const char * const azColName[] = {
93332        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
93333        "selectid", "order", "from", "detail"
93334     };
93335     int iFirst, mx;
93336     if( pParse->explain==2 ){
93337       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
93338       iFirst = 8;
93339       mx = 12;
93340     }else{
93341       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
93342       iFirst = 0;
93343       mx = 8;
93344     }
93345     for(i=iFirst; i<mx; i++){
93346       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
93347                             azColName[i], SQLITE_STATIC);
93348     }
93349   }
93350 #endif
93351
93352   assert( db->init.busy==0 || saveSqlFlag==0 );
93353   if( db->init.busy==0 ){
93354     Vdbe *pVdbe = pParse->pVdbe;
93355     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
93356   }
93357   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
93358     sqlite3VdbeFinalize(pParse->pVdbe);
93359     assert(!(*ppStmt));
93360   }else{
93361     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
93362   }
93363
93364   if( zErrMsg ){
93365     sqlite3Error(db, rc, "%s", zErrMsg);
93366     sqlite3DbFree(db, zErrMsg);
93367   }else{
93368     sqlite3Error(db, rc, 0);
93369   }
93370
93371   /* Delete any TriggerPrg structures allocated while parsing this statement. */
93372   while( pParse->pTriggerPrg ){
93373     TriggerPrg *pT = pParse->pTriggerPrg;
93374     pParse->pTriggerPrg = pT->pNext;
93375     sqlite3DbFree(db, pT);
93376   }
93377
93378 end_prepare:
93379
93380   sqlite3StackFree(db, pParse);
93381   rc = sqlite3ApiExit(db, rc);
93382   assert( (rc&db->errMask)==rc );
93383   return rc;
93384 }
93385 static int sqlite3LockAndPrepare(
93386   sqlite3 *db,              /* Database handle. */
93387   const char *zSql,         /* UTF-8 encoded SQL statement. */
93388   int nBytes,               /* Length of zSql in bytes. */
93389   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
93390   Vdbe *pOld,               /* VM being reprepared */
93391   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93392   const char **pzTail       /* OUT: End of parsed string */
93393 ){
93394   int rc;
93395   assert( ppStmt!=0 );
93396   *ppStmt = 0;
93397   if( !sqlite3SafetyCheckOk(db) ){
93398     return SQLITE_MISUSE_BKPT;
93399   }
93400   sqlite3_mutex_enter(db->mutex);
93401   sqlite3BtreeEnterAll(db);
93402   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
93403   if( rc==SQLITE_SCHEMA ){
93404     sqlite3_finalize(*ppStmt);
93405     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
93406   }
93407   sqlite3BtreeLeaveAll(db);
93408   sqlite3_mutex_leave(db->mutex);
93409   assert( rc==SQLITE_OK || *ppStmt==0 );
93410   return rc;
93411 }
93412
93413 /*
93414 ** Rerun the compilation of a statement after a schema change.
93415 **
93416 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
93417 ** if the statement cannot be recompiled because another connection has
93418 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
93419 ** occurs, return SQLITE_SCHEMA.
93420 */
93421 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
93422   int rc;
93423   sqlite3_stmt *pNew;
93424   const char *zSql;
93425   sqlite3 *db;
93426
93427   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
93428   zSql = sqlite3_sql((sqlite3_stmt *)p);
93429   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
93430   db = sqlite3VdbeDb(p);
93431   assert( sqlite3_mutex_held(db->mutex) );
93432   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
93433   if( rc ){
93434     if( rc==SQLITE_NOMEM ){
93435       db->mallocFailed = 1;
93436     }
93437     assert( pNew==0 );
93438     return rc;
93439   }else{
93440     assert( pNew!=0 );
93441   }
93442   sqlite3VdbeSwap((Vdbe*)pNew, p);
93443   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
93444   sqlite3VdbeResetStepResult((Vdbe*)pNew);
93445   sqlite3VdbeFinalize((Vdbe*)pNew);
93446   return SQLITE_OK;
93447 }
93448
93449
93450 /*
93451 ** Two versions of the official API.  Legacy and new use.  In the legacy
93452 ** version, the original SQL text is not saved in the prepared statement
93453 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
93454 ** sqlite3_step().  In the new version, the original SQL text is retained
93455 ** and the statement is automatically recompiled if an schema change
93456 ** occurs.
93457 */
93458 SQLITE_API int sqlite3_prepare(
93459   sqlite3 *db,              /* Database handle. */
93460   const char *zSql,         /* UTF-8 encoded SQL statement. */
93461   int nBytes,               /* Length of zSql in bytes. */
93462   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93463   const char **pzTail       /* OUT: End of parsed string */
93464 ){
93465   int rc;
93466   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
93467   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
93468   return rc;
93469 }
93470 SQLITE_API int sqlite3_prepare_v2(
93471   sqlite3 *db,              /* Database handle. */
93472   const char *zSql,         /* UTF-8 encoded SQL statement. */
93473   int nBytes,               /* Length of zSql in bytes. */
93474   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93475   const char **pzTail       /* OUT: End of parsed string */
93476 ){
93477   int rc;
93478   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
93479   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
93480   return rc;
93481 }
93482
93483
93484 #ifndef SQLITE_OMIT_UTF16
93485 /*
93486 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
93487 */
93488 static int sqlite3Prepare16(
93489   sqlite3 *db,              /* Database handle. */ 
93490   const void *zSql,         /* UTF-16 encoded SQL statement. */
93491   int nBytes,               /* Length of zSql in bytes. */
93492   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
93493   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93494   const void **pzTail       /* OUT: End of parsed string */
93495 ){
93496   /* This function currently works by first transforming the UTF-16
93497   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
93498   ** tricky bit is figuring out the pointer to return in *pzTail.
93499   */
93500   char *zSql8;
93501   const char *zTail8 = 0;
93502   int rc = SQLITE_OK;
93503
93504   assert( ppStmt );
93505   *ppStmt = 0;
93506   if( !sqlite3SafetyCheckOk(db) ){
93507     return SQLITE_MISUSE_BKPT;
93508   }
93509   sqlite3_mutex_enter(db->mutex);
93510   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
93511   if( zSql8 ){
93512     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
93513   }
93514
93515   if( zTail8 && pzTail ){
93516     /* If sqlite3_prepare returns a tail pointer, we calculate the
93517     ** equivalent pointer into the UTF-16 string by counting the unicode
93518     ** characters between zSql8 and zTail8, and then returning a pointer
93519     ** the same number of characters into the UTF-16 string.
93520     */
93521     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
93522     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
93523   }
93524   sqlite3DbFree(db, zSql8); 
93525   rc = sqlite3ApiExit(db, rc);
93526   sqlite3_mutex_leave(db->mutex);
93527   return rc;
93528 }
93529
93530 /*
93531 ** Two versions of the official API.  Legacy and new use.  In the legacy
93532 ** version, the original SQL text is not saved in the prepared statement
93533 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
93534 ** sqlite3_step().  In the new version, the original SQL text is retained
93535 ** and the statement is automatically recompiled if an schema change
93536 ** occurs.
93537 */
93538 SQLITE_API int sqlite3_prepare16(
93539   sqlite3 *db,              /* Database handle. */ 
93540   const void *zSql,         /* UTF-16 encoded SQL statement. */
93541   int nBytes,               /* Length of zSql in bytes. */
93542   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93543   const void **pzTail       /* OUT: End of parsed string */
93544 ){
93545   int rc;
93546   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
93547   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
93548   return rc;
93549 }
93550 SQLITE_API int sqlite3_prepare16_v2(
93551   sqlite3 *db,              /* Database handle. */ 
93552   const void *zSql,         /* UTF-16 encoded SQL statement. */
93553   int nBytes,               /* Length of zSql in bytes. */
93554   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93555   const void **pzTail       /* OUT: End of parsed string */
93556 ){
93557   int rc;
93558   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
93559   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
93560   return rc;
93561 }
93562
93563 #endif /* SQLITE_OMIT_UTF16 */
93564
93565 /************** End of prepare.c *********************************************/
93566 /************** Begin file select.c ******************************************/
93567 /*
93568 ** 2001 September 15
93569 **
93570 ** The author disclaims copyright to this source code.  In place of
93571 ** a legal notice, here is a blessing:
93572 **
93573 **    May you do good and not evil.
93574 **    May you find forgiveness for yourself and forgive others.
93575 **    May you share freely, never taking more than you give.
93576 **
93577 *************************************************************************
93578 ** This file contains C code routines that are called by the parser
93579 ** to handle SELECT statements in SQLite.
93580 */
93581
93582
93583 /*
93584 ** Delete all the content of a Select structure but do not deallocate
93585 ** the select structure itself.
93586 */
93587 static void clearSelect(sqlite3 *db, Select *p){
93588   sqlite3ExprListDelete(db, p->pEList);
93589   sqlite3SrcListDelete(db, p->pSrc);
93590   sqlite3ExprDelete(db, p->pWhere);
93591   sqlite3ExprListDelete(db, p->pGroupBy);
93592   sqlite3ExprDelete(db, p->pHaving);
93593   sqlite3ExprListDelete(db, p->pOrderBy);
93594   sqlite3SelectDelete(db, p->pPrior);
93595   sqlite3ExprDelete(db, p->pLimit);
93596   sqlite3ExprDelete(db, p->pOffset);
93597 }
93598
93599 /*
93600 ** Initialize a SelectDest structure.
93601 */
93602 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
93603   pDest->eDest = (u8)eDest;
93604   pDest->iSDParm = iParm;
93605   pDest->affSdst = 0;
93606   pDest->iSdst = 0;
93607   pDest->nSdst = 0;
93608 }
93609
93610
93611 /*
93612 ** Allocate a new Select structure and return a pointer to that
93613 ** structure.
93614 */
93615 SQLITE_PRIVATE Select *sqlite3SelectNew(
93616   Parse *pParse,        /* Parsing context */
93617   ExprList *pEList,     /* which columns to include in the result */
93618   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
93619   Expr *pWhere,         /* the WHERE clause */
93620   ExprList *pGroupBy,   /* the GROUP BY clause */
93621   Expr *pHaving,        /* the HAVING clause */
93622   ExprList *pOrderBy,   /* the ORDER BY clause */
93623   int isDistinct,       /* true if the DISTINCT keyword is present */
93624   Expr *pLimit,         /* LIMIT value.  NULL means not used */
93625   Expr *pOffset         /* OFFSET value.  NULL means no offset */
93626 ){
93627   Select *pNew;
93628   Select standin;
93629   sqlite3 *db = pParse->db;
93630   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
93631   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
93632   if( pNew==0 ){
93633     assert( db->mallocFailed );
93634     pNew = &standin;
93635     memset(pNew, 0, sizeof(*pNew));
93636   }
93637   if( pEList==0 ){
93638     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
93639   }
93640   pNew->pEList = pEList;
93641   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
93642   pNew->pSrc = pSrc;
93643   pNew->pWhere = pWhere;
93644   pNew->pGroupBy = pGroupBy;
93645   pNew->pHaving = pHaving;
93646   pNew->pOrderBy = pOrderBy;
93647   pNew->selFlags = isDistinct ? SF_Distinct : 0;
93648   pNew->op = TK_SELECT;
93649   pNew->pLimit = pLimit;
93650   pNew->pOffset = pOffset;
93651   assert( pOffset==0 || pLimit!=0 );
93652   pNew->addrOpenEphm[0] = -1;
93653   pNew->addrOpenEphm[1] = -1;
93654   pNew->addrOpenEphm[2] = -1;
93655   if( db->mallocFailed ) {
93656     clearSelect(db, pNew);
93657     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93658     pNew = 0;
93659   }else{
93660     assert( pNew->pSrc!=0 || pParse->nErr>0 );
93661   }
93662   assert( pNew!=&standin );
93663   return pNew;
93664 }
93665
93666 /*
93667 ** Delete the given Select structure and all of its substructures.
93668 */
93669 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
93670   if( p ){
93671     clearSelect(db, p);
93672     sqlite3DbFree(db, p);
93673   }
93674 }
93675
93676 /*
93677 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
93678 ** type of join.  Return an integer constant that expresses that type
93679 ** in terms of the following bit values:
93680 **
93681 **     JT_INNER
93682 **     JT_CROSS
93683 **     JT_OUTER
93684 **     JT_NATURAL
93685 **     JT_LEFT
93686 **     JT_RIGHT
93687 **
93688 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
93689 **
93690 ** If an illegal or unsupported join type is seen, then still return
93691 ** a join type, but put an error in the pParse structure.
93692 */
93693 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
93694   int jointype = 0;
93695   Token *apAll[3];
93696   Token *p;
93697                              /*   0123456789 123456789 123456789 123 */
93698   static const char zKeyText[] = "naturaleftouterightfullinnercross";
93699   static const struct {
93700     u8 i;        /* Beginning of keyword text in zKeyText[] */
93701     u8 nChar;    /* Length of the keyword in characters */
93702     u8 code;     /* Join type mask */
93703   } aKeyword[] = {
93704     /* natural */ { 0,  7, JT_NATURAL                },
93705     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
93706     /* outer   */ { 10, 5, JT_OUTER                  },
93707     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
93708     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
93709     /* inner   */ { 23, 5, JT_INNER                  },
93710     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
93711   };
93712   int i, j;
93713   apAll[0] = pA;
93714   apAll[1] = pB;
93715   apAll[2] = pC;
93716   for(i=0; i<3 && apAll[i]; i++){
93717     p = apAll[i];
93718     for(j=0; j<ArraySize(aKeyword); j++){
93719       if( p->n==aKeyword[j].nChar 
93720           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
93721         jointype |= aKeyword[j].code;
93722         break;
93723       }
93724     }
93725     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
93726     if( j>=ArraySize(aKeyword) ){
93727       jointype |= JT_ERROR;
93728       break;
93729     }
93730   }
93731   if(
93732      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
93733      (jointype & JT_ERROR)!=0
93734   ){
93735     const char *zSp = " ";
93736     assert( pB!=0 );
93737     if( pC==0 ){ zSp++; }
93738     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
93739        "%T %T%s%T", pA, pB, zSp, pC);
93740     jointype = JT_INNER;
93741   }else if( (jointype & JT_OUTER)!=0 
93742          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
93743     sqlite3ErrorMsg(pParse, 
93744       "RIGHT and FULL OUTER JOINs are not currently supported");
93745     jointype = JT_INNER;
93746   }
93747   return jointype;
93748 }
93749
93750 /*
93751 ** Return the index of a column in a table.  Return -1 if the column
93752 ** is not contained in the table.
93753 */
93754 static int columnIndex(Table *pTab, const char *zCol){
93755   int i;
93756   for(i=0; i<pTab->nCol; i++){
93757     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
93758   }
93759   return -1;
93760 }
93761
93762 /*
93763 ** Search the first N tables in pSrc, from left to right, looking for a
93764 ** table that has a column named zCol.  
93765 **
93766 ** When found, set *piTab and *piCol to the table index and column index
93767 ** of the matching column and return TRUE.
93768 **
93769 ** If not found, return FALSE.
93770 */
93771 static int tableAndColumnIndex(
93772   SrcList *pSrc,       /* Array of tables to search */
93773   int N,               /* Number of tables in pSrc->a[] to search */
93774   const char *zCol,    /* Name of the column we are looking for */
93775   int *piTab,          /* Write index of pSrc->a[] here */
93776   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
93777 ){
93778   int i;               /* For looping over tables in pSrc */
93779   int iCol;            /* Index of column matching zCol */
93780
93781   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
93782   for(i=0; i<N; i++){
93783     iCol = columnIndex(pSrc->a[i].pTab, zCol);
93784     if( iCol>=0 ){
93785       if( piTab ){
93786         *piTab = i;
93787         *piCol = iCol;
93788       }
93789       return 1;
93790     }
93791   }
93792   return 0;
93793 }
93794
93795 /*
93796 ** This function is used to add terms implied by JOIN syntax to the
93797 ** WHERE clause expression of a SELECT statement. The new term, which
93798 ** is ANDed with the existing WHERE clause, is of the form:
93799 **
93800 **    (tab1.col1 = tab2.col2)
93801 **
93802 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
93803 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
93804 ** column iColRight of tab2.
93805 */
93806 static void addWhereTerm(
93807   Parse *pParse,                  /* Parsing context */
93808   SrcList *pSrc,                  /* List of tables in FROM clause */
93809   int iLeft,                      /* Index of first table to join in pSrc */
93810   int iColLeft,                   /* Index of column in first table */
93811   int iRight,                     /* Index of second table in pSrc */
93812   int iColRight,                  /* Index of column in second table */
93813   int isOuterJoin,                /* True if this is an OUTER join */
93814   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
93815 ){
93816   sqlite3 *db = pParse->db;
93817   Expr *pE1;
93818   Expr *pE2;
93819   Expr *pEq;
93820
93821   assert( iLeft<iRight );
93822   assert( pSrc->nSrc>iRight );
93823   assert( pSrc->a[iLeft].pTab );
93824   assert( pSrc->a[iRight].pTab );
93825
93826   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
93827   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
93828
93829   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
93830   if( pEq && isOuterJoin ){
93831     ExprSetProperty(pEq, EP_FromJoin);
93832     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
93833     ExprSetIrreducible(pEq);
93834     pEq->iRightJoinTable = (i16)pE2->iTable;
93835   }
93836   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
93837 }
93838
93839 /*
93840 ** Set the EP_FromJoin property on all terms of the given expression.
93841 ** And set the Expr.iRightJoinTable to iTable for every term in the
93842 ** expression.
93843 **
93844 ** The EP_FromJoin property is used on terms of an expression to tell
93845 ** the LEFT OUTER JOIN processing logic that this term is part of the
93846 ** join restriction specified in the ON or USING clause and not a part
93847 ** of the more general WHERE clause.  These terms are moved over to the
93848 ** WHERE clause during join processing but we need to remember that they
93849 ** originated in the ON or USING clause.
93850 **
93851 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
93852 ** expression depends on table iRightJoinTable even if that table is not
93853 ** explicitly mentioned in the expression.  That information is needed
93854 ** for cases like this:
93855 **
93856 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
93857 **
93858 ** The where clause needs to defer the handling of the t1.x=5
93859 ** term until after the t2 loop of the join.  In that way, a
93860 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
93861 ** defer the handling of t1.x=5, it will be processed immediately
93862 ** after the t1 loop and rows with t1.x!=5 will never appear in
93863 ** the output, which is incorrect.
93864 */
93865 static void setJoinExpr(Expr *p, int iTable){
93866   while( p ){
93867     ExprSetProperty(p, EP_FromJoin);
93868     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
93869     ExprSetIrreducible(p);
93870     p->iRightJoinTable = (i16)iTable;
93871     setJoinExpr(p->pLeft, iTable);
93872     p = p->pRight;
93873   } 
93874 }
93875
93876 /*
93877 ** This routine processes the join information for a SELECT statement.
93878 ** ON and USING clauses are converted into extra terms of the WHERE clause.
93879 ** NATURAL joins also create extra WHERE clause terms.
93880 **
93881 ** The terms of a FROM clause are contained in the Select.pSrc structure.
93882 ** The left most table is the first entry in Select.pSrc.  The right-most
93883 ** table is the last entry.  The join operator is held in the entry to
93884 ** the left.  Thus entry 0 contains the join operator for the join between
93885 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
93886 ** also attached to the left entry.
93887 **
93888 ** This routine returns the number of errors encountered.
93889 */
93890 static int sqliteProcessJoin(Parse *pParse, Select *p){
93891   SrcList *pSrc;                  /* All tables in the FROM clause */
93892   int i, j;                       /* Loop counters */
93893   struct SrcList_item *pLeft;     /* Left table being joined */
93894   struct SrcList_item *pRight;    /* Right table being joined */
93895
93896   pSrc = p->pSrc;
93897   pLeft = &pSrc->a[0];
93898   pRight = &pLeft[1];
93899   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
93900     Table *pLeftTab = pLeft->pTab;
93901     Table *pRightTab = pRight->pTab;
93902     int isOuter;
93903
93904     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
93905     isOuter = (pRight->jointype & JT_OUTER)!=0;
93906
93907     /* When the NATURAL keyword is present, add WHERE clause terms for
93908     ** every column that the two tables have in common.
93909     */
93910     if( pRight->jointype & JT_NATURAL ){
93911       if( pRight->pOn || pRight->pUsing ){
93912         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
93913            "an ON or USING clause", 0);
93914         return 1;
93915       }
93916       for(j=0; j<pRightTab->nCol; j++){
93917         char *zName;   /* Name of column in the right table */
93918         int iLeft;     /* Matching left table */
93919         int iLeftCol;  /* Matching column in the left table */
93920
93921         zName = pRightTab->aCol[j].zName;
93922         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
93923           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
93924                        isOuter, &p->pWhere);
93925         }
93926       }
93927     }
93928
93929     /* Disallow both ON and USING clauses in the same join
93930     */
93931     if( pRight->pOn && pRight->pUsing ){
93932       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
93933         "clauses in the same join");
93934       return 1;
93935     }
93936
93937     /* Add the ON clause to the end of the WHERE clause, connected by
93938     ** an AND operator.
93939     */
93940     if( pRight->pOn ){
93941       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
93942       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
93943       pRight->pOn = 0;
93944     }
93945
93946     /* Create extra terms on the WHERE clause for each column named
93947     ** in the USING clause.  Example: If the two tables to be joined are 
93948     ** A and B and the USING clause names X, Y, and Z, then add this
93949     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
93950     ** Report an error if any column mentioned in the USING clause is
93951     ** not contained in both tables to be joined.
93952     */
93953     if( pRight->pUsing ){
93954       IdList *pList = pRight->pUsing;
93955       for(j=0; j<pList->nId; j++){
93956         char *zName;     /* Name of the term in the USING clause */
93957         int iLeft;       /* Table on the left with matching column name */
93958         int iLeftCol;    /* Column number of matching column on the left */
93959         int iRightCol;   /* Column number of matching column on the right */
93960
93961         zName = pList->a[j].zName;
93962         iRightCol = columnIndex(pRightTab, zName);
93963         if( iRightCol<0
93964          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
93965         ){
93966           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
93967             "not present in both tables", zName);
93968           return 1;
93969         }
93970         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
93971                      isOuter, &p->pWhere);
93972       }
93973     }
93974   }
93975   return 0;
93976 }
93977
93978 /*
93979 ** Insert code into "v" that will push the record on the top of the
93980 ** stack into the sorter.
93981 */
93982 static void pushOntoSorter(
93983   Parse *pParse,         /* Parser context */
93984   ExprList *pOrderBy,    /* The ORDER BY clause */
93985   Select *pSelect,       /* The whole SELECT statement */
93986   int regData            /* Register holding data to be sorted */
93987 ){
93988   Vdbe *v = pParse->pVdbe;
93989   int nExpr = pOrderBy->nExpr;
93990   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
93991   int regRecord = sqlite3GetTempReg(pParse);
93992   int op;
93993   sqlite3ExprCacheClear(pParse);
93994   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
93995   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
93996   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
93997   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
93998   if( pSelect->selFlags & SF_UseSorter ){
93999     op = OP_SorterInsert;
94000   }else{
94001     op = OP_IdxInsert;
94002   }
94003   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94004   sqlite3ReleaseTempReg(pParse, regRecord);
94005   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
94006   if( pSelect->iLimit ){
94007     int addr1, addr2;
94008     int iLimit;
94009     if( pSelect->iOffset ){
94010       iLimit = pSelect->iOffset+1;
94011     }else{
94012       iLimit = pSelect->iLimit;
94013     }
94014     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
94015     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94016     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
94017     sqlite3VdbeJumpHere(v, addr1);
94018     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94019     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94020     sqlite3VdbeJumpHere(v, addr2);
94021   }
94022 }
94023
94024 /*
94025 ** Add code to implement the OFFSET
94026 */
94027 static void codeOffset(
94028   Vdbe *v,          /* Generate code into this VM */
94029   Select *p,        /* The SELECT statement being coded */
94030   int iContinue     /* Jump here to skip the current record */
94031 ){
94032   if( p->iOffset && iContinue!=0 ){
94033     int addr;
94034     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94035     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94036     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94037     VdbeComment((v, "skip OFFSET records"));
94038     sqlite3VdbeJumpHere(v, addr);
94039   }
94040 }
94041
94042 /*
94043 ** Add code that will check to make sure the N registers starting at iMem
94044 ** form a distinct entry.  iTab is a sorting index that holds previously
94045 ** seen combinations of the N values.  A new entry is made in iTab
94046 ** if the current N values are new.
94047 **
94048 ** A jump to addrRepeat is made and the N+1 values are popped from the
94049 ** stack if the top N elements are not distinct.
94050 */
94051 static void codeDistinct(
94052   Parse *pParse,     /* Parsing and code generating context */
94053   int iTab,          /* A sorting index used to test for distinctness */
94054   int addrRepeat,    /* Jump to here if not distinct */
94055   int N,             /* Number of elements */
94056   int iMem           /* First element */
94057 ){
94058   Vdbe *v;
94059   int r1;
94060
94061   v = pParse->pVdbe;
94062   r1 = sqlite3GetTempReg(pParse);
94063   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
94064   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
94065   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
94066   sqlite3ReleaseTempReg(pParse, r1);
94067 }
94068
94069 #ifndef SQLITE_OMIT_SUBQUERY
94070 /*
94071 ** Generate an error message when a SELECT is used within a subexpression
94072 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
94073 ** column.  We do this in a subroutine because the error used to occur
94074 ** in multiple places.  (The error only occurs in one place now, but we
94075 ** retain the subroutine to minimize code disruption.)
94076 */
94077 static int checkForMultiColumnSelectError(
94078   Parse *pParse,       /* Parse context. */
94079   SelectDest *pDest,   /* Destination of SELECT results */
94080   int nExpr            /* Number of result columns returned by SELECT */
94081 ){
94082   int eDest = pDest->eDest;
94083   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
94084     sqlite3ErrorMsg(pParse, "only a single result allowed for "
94085        "a SELECT that is part of an expression");
94086     return 1;
94087   }else{
94088     return 0;
94089   }
94090 }
94091 #endif
94092
94093 /*
94094 ** This routine generates the code for the inside of the inner loop
94095 ** of a SELECT.
94096 **
94097 ** If srcTab and nColumn are both zero, then the pEList expressions
94098 ** are evaluated in order to get the data for this row.  If nColumn>0
94099 ** then data is pulled from srcTab and pEList is used only to get the
94100 ** datatypes for each column.
94101 */
94102 static void selectInnerLoop(
94103   Parse *pParse,          /* The parser context */
94104   Select *p,              /* The complete select statement being coded */
94105   ExprList *pEList,       /* List of values being extracted */
94106   int srcTab,             /* Pull data from this table */
94107   int nColumn,            /* Number of columns in the source table */
94108   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
94109   int distinct,           /* If >=0, make sure results are distinct */
94110   SelectDest *pDest,      /* How to dispose of the results */
94111   int iContinue,          /* Jump here to continue with next row */
94112   int iBreak              /* Jump here to break out of the inner loop */
94113 ){
94114   Vdbe *v = pParse->pVdbe;
94115   int i;
94116   int hasDistinct;        /* True if the DISTINCT keyword is present */
94117   int regResult;              /* Start of memory holding result set */
94118   int eDest = pDest->eDest;   /* How to dispose of results */
94119   int iParm = pDest->iSDParm; /* First argument to disposal method */
94120   int nResultCol;             /* Number of result columns */
94121
94122   assert( v );
94123   if( NEVER(v==0) ) return;
94124   assert( pEList!=0 );
94125   hasDistinct = distinct>=0;
94126   if( pOrderBy==0 && !hasDistinct ){
94127     codeOffset(v, p, iContinue);
94128   }
94129
94130   /* Pull the requested columns.
94131   */
94132   if( nColumn>0 ){
94133     nResultCol = nColumn;
94134   }else{
94135     nResultCol = pEList->nExpr;
94136   }
94137   if( pDest->iSdst==0 ){
94138     pDest->iSdst = pParse->nMem+1;
94139     pDest->nSdst = nResultCol;
94140     pParse->nMem += nResultCol;
94141   }else{ 
94142     assert( pDest->nSdst==nResultCol );
94143   }
94144   regResult = pDest->iSdst;
94145   if( nColumn>0 ){
94146     for(i=0; i<nColumn; i++){
94147       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
94148     }
94149   }else if( eDest!=SRT_Exists ){
94150     /* If the destination is an EXISTS(...) expression, the actual
94151     ** values returned by the SELECT are not required.
94152     */
94153     sqlite3ExprCacheClear(pParse);
94154     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
94155   }
94156   nColumn = nResultCol;
94157
94158   /* If the DISTINCT keyword was present on the SELECT statement
94159   ** and this row has been seen before, then do not make this row
94160   ** part of the result.
94161   */
94162   if( hasDistinct ){
94163     assert( pEList!=0 );
94164     assert( pEList->nExpr==nColumn );
94165     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
94166     if( pOrderBy==0 ){
94167       codeOffset(v, p, iContinue);
94168     }
94169   }
94170
94171   switch( eDest ){
94172     /* In this mode, write each query result to the key of the temporary
94173     ** table iParm.
94174     */
94175 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94176     case SRT_Union: {
94177       int r1;
94178       r1 = sqlite3GetTempReg(pParse);
94179       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94180       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94181       sqlite3ReleaseTempReg(pParse, r1);
94182       break;
94183     }
94184
94185     /* Construct a record from the query result, but instead of
94186     ** saving that record, use it as a key to delete elements from
94187     ** the temporary table iParm.
94188     */
94189     case SRT_Except: {
94190       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
94191       break;
94192     }
94193 #endif
94194
94195     /* Store the result as data using a unique key.
94196     */
94197     case SRT_Table:
94198     case SRT_EphemTab: {
94199       int r1 = sqlite3GetTempReg(pParse);
94200       testcase( eDest==SRT_Table );
94201       testcase( eDest==SRT_EphemTab );
94202       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94203       if( pOrderBy ){
94204         pushOntoSorter(pParse, pOrderBy, p, r1);
94205       }else{
94206         int r2 = sqlite3GetTempReg(pParse);
94207         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
94208         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
94209         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94210         sqlite3ReleaseTempReg(pParse, r2);
94211       }
94212       sqlite3ReleaseTempReg(pParse, r1);
94213       break;
94214     }
94215
94216 #ifndef SQLITE_OMIT_SUBQUERY
94217     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
94218     ** then there should be a single item on the stack.  Write this
94219     ** item into the set table with bogus data.
94220     */
94221     case SRT_Set: {
94222       assert( nColumn==1 );
94223       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
94224       if( pOrderBy ){
94225         /* At first glance you would think we could optimize out the
94226         ** ORDER BY in this case since the order of entries in the set
94227         ** does not matter.  But there might be a LIMIT clause, in which
94228         ** case the order does matter */
94229         pushOntoSorter(pParse, pOrderBy, p, regResult);
94230       }else{
94231         int r1 = sqlite3GetTempReg(pParse);
94232         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
94233         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
94234         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94235         sqlite3ReleaseTempReg(pParse, r1);
94236       }
94237       break;
94238     }
94239
94240     /* If any row exist in the result set, record that fact and abort.
94241     */
94242     case SRT_Exists: {
94243       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
94244       /* The LIMIT clause will terminate the loop for us */
94245       break;
94246     }
94247
94248     /* If this is a scalar select that is part of an expression, then
94249     ** store the results in the appropriate memory cell and break out
94250     ** of the scan loop.
94251     */
94252     case SRT_Mem: {
94253       assert( nColumn==1 );
94254       if( pOrderBy ){
94255         pushOntoSorter(pParse, pOrderBy, p, regResult);
94256       }else{
94257         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
94258         /* The LIMIT clause will jump out of the loop for us */
94259       }
94260       break;
94261     }
94262 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
94263
94264     /* Send the data to the callback function or to a subroutine.  In the
94265     ** case of a subroutine, the subroutine itself is responsible for
94266     ** popping the data from the stack.
94267     */
94268     case SRT_Coroutine:
94269     case SRT_Output: {
94270       testcase( eDest==SRT_Coroutine );
94271       testcase( eDest==SRT_Output );
94272       if( pOrderBy ){
94273         int r1 = sqlite3GetTempReg(pParse);
94274         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94275         pushOntoSorter(pParse, pOrderBy, p, r1);
94276         sqlite3ReleaseTempReg(pParse, r1);
94277       }else if( eDest==SRT_Coroutine ){
94278         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
94279       }else{
94280         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
94281         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
94282       }
94283       break;
94284     }
94285
94286 #if !defined(SQLITE_OMIT_TRIGGER)
94287     /* Discard the results.  This is used for SELECT statements inside
94288     ** the body of a TRIGGER.  The purpose of such selects is to call
94289     ** user-defined functions that have side effects.  We do not care
94290     ** about the actual results of the select.
94291     */
94292     default: {
94293       assert( eDest==SRT_Discard );
94294       break;
94295     }
94296 #endif
94297   }
94298
94299   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
94300   ** there is a sorter, in which case the sorter has already limited
94301   ** the output for us.
94302   */
94303   if( pOrderBy==0 && p->iLimit ){
94304     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
94305   }
94306 }
94307
94308 /*
94309 ** Given an expression list, generate a KeyInfo structure that records
94310 ** the collating sequence for each expression in that expression list.
94311 **
94312 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
94313 ** KeyInfo structure is appropriate for initializing a virtual index to
94314 ** implement that clause.  If the ExprList is the result set of a SELECT
94315 ** then the KeyInfo structure is appropriate for initializing a virtual
94316 ** index to implement a DISTINCT test.
94317 **
94318 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
94319 ** function is responsible for seeing that this structure is eventually
94320 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
94321 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
94322 */
94323 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
94324   sqlite3 *db = pParse->db;
94325   int nExpr;
94326   KeyInfo *pInfo;
94327   struct ExprList_item *pItem;
94328   int i;
94329
94330   nExpr = pList->nExpr;
94331   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
94332   if( pInfo ){
94333     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
94334     pInfo->nField = (u16)nExpr;
94335     pInfo->enc = ENC(db);
94336     pInfo->db = db;
94337     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
94338       CollSeq *pColl;
94339       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
94340       if( !pColl ){
94341         pColl = db->pDfltColl;
94342       }
94343       pInfo->aColl[i] = pColl;
94344       pInfo->aSortOrder[i] = pItem->sortOrder;
94345     }
94346   }
94347   return pInfo;
94348 }
94349
94350 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94351 /*
94352 ** Name of the connection operator, used for error messages.
94353 */
94354 static const char *selectOpName(int id){
94355   char *z;
94356   switch( id ){
94357     case TK_ALL:       z = "UNION ALL";   break;
94358     case TK_INTERSECT: z = "INTERSECT";   break;
94359     case TK_EXCEPT:    z = "EXCEPT";      break;
94360     default:           z = "UNION";       break;
94361   }
94362   return z;
94363 }
94364 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
94365
94366 #ifndef SQLITE_OMIT_EXPLAIN
94367 /*
94368 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
94369 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
94370 ** where the caption is of the form:
94371 **
94372 **   "USE TEMP B-TREE FOR xxx"
94373 **
94374 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
94375 ** is determined by the zUsage argument.
94376 */
94377 static void explainTempTable(Parse *pParse, const char *zUsage){
94378   if( pParse->explain==2 ){
94379     Vdbe *v = pParse->pVdbe;
94380     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
94381     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94382   }
94383 }
94384
94385 /*
94386 ** Assign expression b to lvalue a. A second, no-op, version of this macro
94387 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
94388 ** in sqlite3Select() to assign values to structure member variables that
94389 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
94390 ** code with #ifndef directives.
94391 */
94392 # define explainSetInteger(a, b) a = b
94393
94394 #else
94395 /* No-op versions of the explainXXX() functions and macros. */
94396 # define explainTempTable(y,z)
94397 # define explainSetInteger(y,z)
94398 #endif
94399
94400 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
94401 /*
94402 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
94403 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
94404 ** where the caption is of one of the two forms:
94405 **
94406 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
94407 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
94408 **
94409 ** where iSub1 and iSub2 are the integers passed as the corresponding
94410 ** function parameters, and op is the text representation of the parameter
94411 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
94412 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
94413 ** false, or the second form if it is true.
94414 */
94415 static void explainComposite(
94416   Parse *pParse,                  /* Parse context */
94417   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
94418   int iSub1,                      /* Subquery id 1 */
94419   int iSub2,                      /* Subquery id 2 */
94420   int bUseTmp                     /* True if a temp table was used */
94421 ){
94422   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
94423   if( pParse->explain==2 ){
94424     Vdbe *v = pParse->pVdbe;
94425     char *zMsg = sqlite3MPrintf(
94426         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
94427         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
94428     );
94429     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94430   }
94431 }
94432 #else
94433 /* No-op versions of the explainXXX() functions and macros. */
94434 # define explainComposite(v,w,x,y,z)
94435 #endif
94436
94437 /*
94438 ** If the inner loop was generated using a non-null pOrderBy argument,
94439 ** then the results were placed in a sorter.  After the loop is terminated
94440 ** we need to run the sorter and output the results.  The following
94441 ** routine generates the code needed to do that.
94442 */
94443 static void generateSortTail(
94444   Parse *pParse,    /* Parsing context */
94445   Select *p,        /* The SELECT statement */
94446   Vdbe *v,          /* Generate code into this VDBE */
94447   int nColumn,      /* Number of columns of data */
94448   SelectDest *pDest /* Write the sorted results here */
94449 ){
94450   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
94451   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
94452   int addr;
94453   int iTab;
94454   int pseudoTab = 0;
94455   ExprList *pOrderBy = p->pOrderBy;
94456
94457   int eDest = pDest->eDest;
94458   int iParm = pDest->iSDParm;
94459
94460   int regRow;
94461   int regRowid;
94462
94463   iTab = pOrderBy->iECursor;
94464   regRow = sqlite3GetTempReg(pParse);
94465   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
94466     pseudoTab = pParse->nTab++;
94467     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
94468     regRowid = 0;
94469   }else{
94470     regRowid = sqlite3GetTempReg(pParse);
94471   }
94472   if( p->selFlags & SF_UseSorter ){
94473     int regSortOut = ++pParse->nMem;
94474     int ptab2 = pParse->nTab++;
94475     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
94476     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
94477     codeOffset(v, p, addrContinue);
94478     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
94479     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
94480     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
94481   }else{
94482     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
94483     codeOffset(v, p, addrContinue);
94484     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
94485   }
94486   switch( eDest ){
94487     case SRT_Table:
94488     case SRT_EphemTab: {
94489       testcase( eDest==SRT_Table );
94490       testcase( eDest==SRT_EphemTab );
94491       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
94492       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
94493       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94494       break;
94495     }
94496 #ifndef SQLITE_OMIT_SUBQUERY
94497     case SRT_Set: {
94498       assert( nColumn==1 );
94499       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
94500       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
94501       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
94502       break;
94503     }
94504     case SRT_Mem: {
94505       assert( nColumn==1 );
94506       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
94507       /* The LIMIT clause will terminate the loop for us */
94508       break;
94509     }
94510 #endif
94511     default: {
94512       int i;
94513       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
94514       testcase( eDest==SRT_Output );
94515       testcase( eDest==SRT_Coroutine );
94516       for(i=0; i<nColumn; i++){
94517         assert( regRow!=pDest->iSdst+i );
94518         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
94519         if( i==0 ){
94520           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
94521         }
94522       }
94523       if( eDest==SRT_Output ){
94524         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
94525         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
94526       }else{
94527         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
94528       }
94529       break;
94530     }
94531   }
94532   sqlite3ReleaseTempReg(pParse, regRow);
94533   sqlite3ReleaseTempReg(pParse, regRowid);
94534
94535   /* The bottom of the loop
94536   */
94537   sqlite3VdbeResolveLabel(v, addrContinue);
94538   if( p->selFlags & SF_UseSorter ){
94539     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
94540   }else{
94541     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
94542   }
94543   sqlite3VdbeResolveLabel(v, addrBreak);
94544   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
94545     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
94546   }
94547 }
94548
94549 /*
94550 ** Return a pointer to a string containing the 'declaration type' of the
94551 ** expression pExpr. The string may be treated as static by the caller.
94552 **
94553 ** The declaration type is the exact datatype definition extracted from the
94554 ** original CREATE TABLE statement if the expression is a column. The
94555 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
94556 ** is considered a column can be complex in the presence of subqueries. The
94557 ** result-set expression in all of the following SELECT statements is 
94558 ** considered a column by this function.
94559 **
94560 **   SELECT col FROM tbl;
94561 **   SELECT (SELECT col FROM tbl;
94562 **   SELECT (SELECT col FROM tbl);
94563 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
94564 ** 
94565 ** The declaration type for any expression other than a column is NULL.
94566 */
94567 static const char *columnType(
94568   NameContext *pNC, 
94569   Expr *pExpr,
94570   const char **pzOriginDb,
94571   const char **pzOriginTab,
94572   const char **pzOriginCol
94573 ){
94574   char const *zType = 0;
94575   char const *zOriginDb = 0;
94576   char const *zOriginTab = 0;
94577   char const *zOriginCol = 0;
94578   int j;
94579   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
94580
94581   switch( pExpr->op ){
94582     case TK_AGG_COLUMN:
94583     case TK_COLUMN: {
94584       /* The expression is a column. Locate the table the column is being
94585       ** extracted from in NameContext.pSrcList. This table may be real
94586       ** database table or a subquery.
94587       */
94588       Table *pTab = 0;            /* Table structure column is extracted from */
94589       Select *pS = 0;             /* Select the column is extracted from */
94590       int iCol = pExpr->iColumn;  /* Index of column in pTab */
94591       testcase( pExpr->op==TK_AGG_COLUMN );
94592       testcase( pExpr->op==TK_COLUMN );
94593       while( pNC && !pTab ){
94594         SrcList *pTabList = pNC->pSrcList;
94595         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
94596         if( j<pTabList->nSrc ){
94597           pTab = pTabList->a[j].pTab;
94598           pS = pTabList->a[j].pSelect;
94599         }else{
94600           pNC = pNC->pNext;
94601         }
94602       }
94603
94604       if( pTab==0 ){
94605         /* At one time, code such as "SELECT new.x" within a trigger would
94606         ** cause this condition to run.  Since then, we have restructured how
94607         ** trigger code is generated and so this condition is no longer 
94608         ** possible. However, it can still be true for statements like
94609         ** the following:
94610         **
94611         **   CREATE TABLE t1(col INTEGER);
94612         **   SELECT (SELECT t1.col) FROM FROM t1;
94613         **
94614         ** when columnType() is called on the expression "t1.col" in the 
94615         ** sub-select. In this case, set the column type to NULL, even
94616         ** though it should really be "INTEGER".
94617         **
94618         ** This is not a problem, as the column type of "t1.col" is never
94619         ** used. When columnType() is called on the expression 
94620         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
94621         ** branch below.  */
94622         break;
94623       }
94624
94625       assert( pTab && pExpr->pTab==pTab );
94626       if( pS ){
94627         /* The "table" is actually a sub-select or a view in the FROM clause
94628         ** of the SELECT statement. Return the declaration type and origin
94629         ** data for the result-set column of the sub-select.
94630         */
94631         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
94632           /* If iCol is less than zero, then the expression requests the
94633           ** rowid of the sub-select or view. This expression is legal (see 
94634           ** test case misc2.2.2) - it always evaluates to NULL.
94635           */
94636           NameContext sNC;
94637           Expr *p = pS->pEList->a[iCol].pExpr;
94638           sNC.pSrcList = pS->pSrc;
94639           sNC.pNext = pNC;
94640           sNC.pParse = pNC->pParse;
94641           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
94642         }
94643       }else if( ALWAYS(pTab->pSchema) ){
94644         /* A real table */
94645         assert( !pS );
94646         if( iCol<0 ) iCol = pTab->iPKey;
94647         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
94648         if( iCol<0 ){
94649           zType = "INTEGER";
94650           zOriginCol = "rowid";
94651         }else{
94652           zType = pTab->aCol[iCol].zType;
94653           zOriginCol = pTab->aCol[iCol].zName;
94654         }
94655         zOriginTab = pTab->zName;
94656         if( pNC->pParse ){
94657           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
94658           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
94659         }
94660       }
94661       break;
94662     }
94663 #ifndef SQLITE_OMIT_SUBQUERY
94664     case TK_SELECT: {
94665       /* The expression is a sub-select. Return the declaration type and
94666       ** origin info for the single column in the result set of the SELECT
94667       ** statement.
94668       */
94669       NameContext sNC;
94670       Select *pS = pExpr->x.pSelect;
94671       Expr *p = pS->pEList->a[0].pExpr;
94672       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
94673       sNC.pSrcList = pS->pSrc;
94674       sNC.pNext = pNC;
94675       sNC.pParse = pNC->pParse;
94676       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
94677       break;
94678     }
94679 #endif
94680   }
94681   
94682   if( pzOriginDb ){
94683     assert( pzOriginTab && pzOriginCol );
94684     *pzOriginDb = zOriginDb;
94685     *pzOriginTab = zOriginTab;
94686     *pzOriginCol = zOriginCol;
94687   }
94688   return zType;
94689 }
94690
94691 /*
94692 ** Generate code that will tell the VDBE the declaration types of columns
94693 ** in the result set.
94694 */
94695 static void generateColumnTypes(
94696   Parse *pParse,      /* Parser context */
94697   SrcList *pTabList,  /* List of tables */
94698   ExprList *pEList    /* Expressions defining the result set */
94699 ){
94700 #ifndef SQLITE_OMIT_DECLTYPE
94701   Vdbe *v = pParse->pVdbe;
94702   int i;
94703   NameContext sNC;
94704   sNC.pSrcList = pTabList;
94705   sNC.pParse = pParse;
94706   for(i=0; i<pEList->nExpr; i++){
94707     Expr *p = pEList->a[i].pExpr;
94708     const char *zType;
94709 #ifdef SQLITE_ENABLE_COLUMN_METADATA
94710     const char *zOrigDb = 0;
94711     const char *zOrigTab = 0;
94712     const char *zOrigCol = 0;
94713     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
94714
94715     /* The vdbe must make its own copy of the column-type and other 
94716     ** column specific strings, in case the schema is reset before this
94717     ** virtual machine is deleted.
94718     */
94719     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
94720     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
94721     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
94722 #else
94723     zType = columnType(&sNC, p, 0, 0, 0);
94724 #endif
94725     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
94726   }
94727 #endif /* SQLITE_OMIT_DECLTYPE */
94728 }
94729
94730 /*
94731 ** Generate code that will tell the VDBE the names of columns
94732 ** in the result set.  This information is used to provide the
94733 ** azCol[] values in the callback.
94734 */
94735 static void generateColumnNames(
94736   Parse *pParse,      /* Parser context */
94737   SrcList *pTabList,  /* List of tables */
94738   ExprList *pEList    /* Expressions defining the result set */
94739 ){
94740   Vdbe *v = pParse->pVdbe;
94741   int i, j;
94742   sqlite3 *db = pParse->db;
94743   int fullNames, shortNames;
94744
94745 #ifndef SQLITE_OMIT_EXPLAIN
94746   /* If this is an EXPLAIN, skip this step */
94747   if( pParse->explain ){
94748     return;
94749   }
94750 #endif
94751
94752   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
94753   pParse->colNamesSet = 1;
94754   fullNames = (db->flags & SQLITE_FullColNames)!=0;
94755   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
94756   sqlite3VdbeSetNumCols(v, pEList->nExpr);
94757   for(i=0; i<pEList->nExpr; i++){
94758     Expr *p;
94759     p = pEList->a[i].pExpr;
94760     if( NEVER(p==0) ) continue;
94761     if( pEList->a[i].zName ){
94762       char *zName = pEList->a[i].zName;
94763       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
94764     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
94765       Table *pTab;
94766       char *zCol;
94767       int iCol = p->iColumn;
94768       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
94769         if( pTabList->a[j].iCursor==p->iTable ) break;
94770       }
94771       assert( j<pTabList->nSrc );
94772       pTab = pTabList->a[j].pTab;
94773       if( iCol<0 ) iCol = pTab->iPKey;
94774       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
94775       if( iCol<0 ){
94776         zCol = "rowid";
94777       }else{
94778         zCol = pTab->aCol[iCol].zName;
94779       }
94780       if( !shortNames && !fullNames ){
94781         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
94782             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
94783       }else if( fullNames ){
94784         char *zName = 0;
94785         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
94786         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
94787       }else{
94788         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
94789       }
94790     }else{
94791       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
94792           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
94793     }
94794   }
94795   generateColumnTypes(pParse, pTabList, pEList);
94796 }
94797
94798 /*
94799 ** Given a an expression list (which is really the list of expressions
94800 ** that form the result set of a SELECT statement) compute appropriate
94801 ** column names for a table that would hold the expression list.
94802 **
94803 ** All column names will be unique.
94804 **
94805 ** Only the column names are computed.  Column.zType, Column.zColl,
94806 ** and other fields of Column are zeroed.
94807 **
94808 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
94809 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
94810 */
94811 static int selectColumnsFromExprList(
94812   Parse *pParse,          /* Parsing context */
94813   ExprList *pEList,       /* Expr list from which to derive column names */
94814   int *pnCol,             /* Write the number of columns here */
94815   Column **paCol          /* Write the new column list here */
94816 ){
94817   sqlite3 *db = pParse->db;   /* Database connection */
94818   int i, j;                   /* Loop counters */
94819   int cnt;                    /* Index added to make the name unique */
94820   Column *aCol, *pCol;        /* For looping over result columns */
94821   int nCol;                   /* Number of columns in the result set */
94822   Expr *p;                    /* Expression for a single result column */
94823   char *zName;                /* Column name */
94824   int nName;                  /* Size of name in zName[] */
94825
94826   if( pEList ){
94827     nCol = pEList->nExpr;
94828     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
94829     testcase( aCol==0 );
94830   }else{
94831     nCol = 0;
94832     aCol = 0;
94833   }
94834   *pnCol = nCol;
94835   *paCol = aCol;
94836
94837   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
94838     /* Get an appropriate name for the column
94839     */
94840     p = pEList->a[i].pExpr;
94841     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
94842                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
94843     if( (zName = pEList->a[i].zName)!=0 ){
94844       /* If the column contains an "AS <name>" phrase, use <name> as the name */
94845       zName = sqlite3DbStrDup(db, zName);
94846     }else{
94847       Expr *pColExpr = p;  /* The expression that is the result column name */
94848       Table *pTab;         /* Table associated with this expression */
94849       while( pColExpr->op==TK_DOT ){
94850         pColExpr = pColExpr->pRight;
94851         assert( pColExpr!=0 );
94852       }
94853       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
94854         /* For columns use the column name name */
94855         int iCol = pColExpr->iColumn;
94856         pTab = pColExpr->pTab;
94857         if( iCol<0 ) iCol = pTab->iPKey;
94858         zName = sqlite3MPrintf(db, "%s",
94859                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
94860       }else if( pColExpr->op==TK_ID ){
94861         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
94862         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
94863       }else{
94864         /* Use the original text of the column expression as its name */
94865         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
94866       }
94867     }
94868     if( db->mallocFailed ){
94869       sqlite3DbFree(db, zName);
94870       break;
94871     }
94872
94873     /* Make sure the column name is unique.  If the name is not unique,
94874     ** append a integer to the name so that it becomes unique.
94875     */
94876     nName = sqlite3Strlen30(zName);
94877     for(j=cnt=0; j<i; j++){
94878       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
94879         char *zNewName;
94880         zName[nName] = 0;
94881         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
94882         sqlite3DbFree(db, zName);
94883         zName = zNewName;
94884         j = -1;
94885         if( zName==0 ) break;
94886       }
94887     }
94888     pCol->zName = zName;
94889   }
94890   if( db->mallocFailed ){
94891     for(j=0; j<i; j++){
94892       sqlite3DbFree(db, aCol[j].zName);
94893     }
94894     sqlite3DbFree(db, aCol);
94895     *paCol = 0;
94896     *pnCol = 0;
94897     return SQLITE_NOMEM;
94898   }
94899   return SQLITE_OK;
94900 }
94901
94902 /*
94903 ** Add type and collation information to a column list based on
94904 ** a SELECT statement.
94905 ** 
94906 ** The column list presumably came from selectColumnNamesFromExprList().
94907 ** The column list has only names, not types or collations.  This
94908 ** routine goes through and adds the types and collations.
94909 **
94910 ** This routine requires that all identifiers in the SELECT
94911 ** statement be resolved.
94912 */
94913 static void selectAddColumnTypeAndCollation(
94914   Parse *pParse,        /* Parsing contexts */
94915   int nCol,             /* Number of columns */
94916   Column *aCol,         /* List of columns */
94917   Select *pSelect       /* SELECT used to determine types and collations */
94918 ){
94919   sqlite3 *db = pParse->db;
94920   NameContext sNC;
94921   Column *pCol;
94922   CollSeq *pColl;
94923   int i;
94924   Expr *p;
94925   struct ExprList_item *a;
94926
94927   assert( pSelect!=0 );
94928   assert( (pSelect->selFlags & SF_Resolved)!=0 );
94929   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
94930   if( db->mallocFailed ) return;
94931   memset(&sNC, 0, sizeof(sNC));
94932   sNC.pSrcList = pSelect->pSrc;
94933   a = pSelect->pEList->a;
94934   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
94935     p = a[i].pExpr;
94936     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
94937     pCol->affinity = sqlite3ExprAffinity(p);
94938     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
94939     pColl = sqlite3ExprCollSeq(pParse, p);
94940     if( pColl ){
94941       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
94942     }
94943   }
94944 }
94945
94946 /*
94947 ** Given a SELECT statement, generate a Table structure that describes
94948 ** the result set of that SELECT.
94949 */
94950 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
94951   Table *pTab;
94952   sqlite3 *db = pParse->db;
94953   int savedFlags;
94954
94955   savedFlags = db->flags;
94956   db->flags &= ~SQLITE_FullColNames;
94957   db->flags |= SQLITE_ShortColNames;
94958   sqlite3SelectPrep(pParse, pSelect, 0);
94959   if( pParse->nErr ) return 0;
94960   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
94961   db->flags = savedFlags;
94962   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
94963   if( pTab==0 ){
94964     return 0;
94965   }
94966   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
94967   ** is disabled */
94968   assert( db->lookaside.bEnabled==0 );
94969   pTab->nRef = 1;
94970   pTab->zName = 0;
94971   pTab->nRowEst = 1000000;
94972   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
94973   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
94974   pTab->iPKey = -1;
94975   if( db->mallocFailed ){
94976     sqlite3DeleteTable(db, pTab);
94977     return 0;
94978   }
94979   return pTab;
94980 }
94981
94982 /*
94983 ** Get a VDBE for the given parser context.  Create a new one if necessary.
94984 ** If an error occurs, return NULL and leave a message in pParse.
94985 */
94986 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
94987   Vdbe *v = pParse->pVdbe;
94988   if( v==0 ){
94989     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
94990 #ifndef SQLITE_OMIT_TRACE
94991     if( v ){
94992       sqlite3VdbeAddOp0(v, OP_Trace);
94993     }
94994 #endif
94995   }
94996   return v;
94997 }
94998
94999
95000 /*
95001 ** Compute the iLimit and iOffset fields of the SELECT based on the
95002 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95003 ** that appear in the original SQL statement after the LIMIT and OFFSET
95004 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
95005 ** are the integer memory register numbers for counters used to compute 
95006 ** the limit and offset.  If there is no limit and/or offset, then 
95007 ** iLimit and iOffset are negative.
95008 **
95009 ** This routine changes the values of iLimit and iOffset only if
95010 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
95011 ** iOffset should have been preset to appropriate default values
95012 ** (usually but not always -1) prior to calling this routine.
95013 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95014 ** redefined.  The UNION ALL operator uses this property to force
95015 ** the reuse of the same limit and offset registers across multiple
95016 ** SELECT statements.
95017 */
95018 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95019   Vdbe *v = 0;
95020   int iLimit = 0;
95021   int iOffset;
95022   int addr1, n;
95023   if( p->iLimit ) return;
95024
95025   /* 
95026   ** "LIMIT -1" always shows all rows.  There is some
95027   ** contraversy about what the correct behavior should be.
95028   ** The current implementation interprets "LIMIT 0" to mean
95029   ** no rows.
95030   */
95031   sqlite3ExprCacheClear(pParse);
95032   assert( p->pOffset==0 || p->pLimit!=0 );
95033   if( p->pLimit ){
95034     p->iLimit = iLimit = ++pParse->nMem;
95035     v = sqlite3GetVdbe(pParse);
95036     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95037     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
95038       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
95039       VdbeComment((v, "LIMIT counter"));
95040       if( n==0 ){
95041         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95042       }else{
95043         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95044       }
95045     }else{
95046       sqlite3ExprCode(pParse, p->pLimit, iLimit);
95047       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95048       VdbeComment((v, "LIMIT counter"));
95049       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95050     }
95051     if( p->pOffset ){
95052       p->iOffset = iOffset = ++pParse->nMem;
95053       pParse->nMem++;   /* Allocate an extra register for limit+offset */
95054       sqlite3ExprCode(pParse, p->pOffset, iOffset);
95055       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95056       VdbeComment((v, "OFFSET counter"));
95057       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
95058       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
95059       sqlite3VdbeJumpHere(v, addr1);
95060       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
95061       VdbeComment((v, "LIMIT+OFFSET"));
95062       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
95063       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
95064       sqlite3VdbeJumpHere(v, addr1);
95065     }
95066   }
95067 }
95068
95069 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95070 /*
95071 ** Return the appropriate collating sequence for the iCol-th column of
95072 ** the result set for the compound-select statement "p".  Return NULL if
95073 ** the column has no default collating sequence.
95074 **
95075 ** The collating sequence for the compound select is taken from the
95076 ** left-most term of the select that has a collating sequence.
95077 */
95078 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
95079   CollSeq *pRet;
95080   if( p->pPrior ){
95081     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
95082   }else{
95083     pRet = 0;
95084   }
95085   assert( iCol>=0 );
95086   if( pRet==0 && iCol<p->pEList->nExpr ){
95087     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
95088   }
95089   return pRet;
95090 }
95091 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95092
95093 /* Forward reference */
95094 static int multiSelectOrderBy(
95095   Parse *pParse,        /* Parsing context */
95096   Select *p,            /* The right-most of SELECTs to be coded */
95097   SelectDest *pDest     /* What to do with query results */
95098 );
95099
95100
95101 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95102 /*
95103 ** This routine is called to process a compound query form from
95104 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
95105 ** INTERSECT
95106 **
95107 ** "p" points to the right-most of the two queries.  the query on the
95108 ** left is p->pPrior.  The left query could also be a compound query
95109 ** in which case this routine will be called recursively. 
95110 **
95111 ** The results of the total query are to be written into a destination
95112 ** of type eDest with parameter iParm.
95113 **
95114 ** Example 1:  Consider a three-way compound SQL statement.
95115 **
95116 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
95117 **
95118 ** This statement is parsed up as follows:
95119 **
95120 **     SELECT c FROM t3
95121 **      |
95122 **      `----->  SELECT b FROM t2
95123 **                |
95124 **                `------>  SELECT a FROM t1
95125 **
95126 ** The arrows in the diagram above represent the Select.pPrior pointer.
95127 ** So if this routine is called with p equal to the t3 query, then
95128 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
95129 **
95130 ** Notice that because of the way SQLite parses compound SELECTs, the
95131 ** individual selects always group from left to right.
95132 */
95133 static int multiSelect(
95134   Parse *pParse,        /* Parsing context */
95135   Select *p,            /* The right-most of SELECTs to be coded */
95136   SelectDest *pDest     /* What to do with query results */
95137 ){
95138   int rc = SQLITE_OK;   /* Success code from a subroutine */
95139   Select *pPrior;       /* Another SELECT immediately to our left */
95140   Vdbe *v;              /* Generate code to this VDBE */
95141   SelectDest dest;      /* Alternative data destination */
95142   Select *pDelete = 0;  /* Chain of simple selects to delete */
95143   sqlite3 *db;          /* Database connection */
95144 #ifndef SQLITE_OMIT_EXPLAIN
95145   int iSub1;            /* EQP id of left-hand query */
95146   int iSub2;            /* EQP id of right-hand query */
95147 #endif
95148
95149   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
95150   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
95151   */
95152   assert( p && p->pPrior );  /* Calling function guarantees this much */
95153   db = pParse->db;
95154   pPrior = p->pPrior;
95155   assert( pPrior->pRightmost!=pPrior );
95156   assert( pPrior->pRightmost==p->pRightmost );
95157   dest = *pDest;
95158   if( pPrior->pOrderBy ){
95159     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
95160       selectOpName(p->op));
95161     rc = 1;
95162     goto multi_select_end;
95163   }
95164   if( pPrior->pLimit ){
95165     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
95166       selectOpName(p->op));
95167     rc = 1;
95168     goto multi_select_end;
95169   }
95170
95171   v = sqlite3GetVdbe(pParse);
95172   assert( v!=0 );  /* The VDBE already created by calling function */
95173
95174   /* Create the destination temporary table if necessary
95175   */
95176   if( dest.eDest==SRT_EphemTab ){
95177     assert( p->pEList );
95178     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
95179     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
95180     dest.eDest = SRT_Table;
95181   }
95182
95183   /* Make sure all SELECTs in the statement have the same number of elements
95184   ** in their result sets.
95185   */
95186   assert( p->pEList && pPrior->pEList );
95187   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
95188     if( p->selFlags & SF_Values ){
95189       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
95190     }else{
95191       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
95192         " do not have the same number of result columns", selectOpName(p->op));
95193     }
95194     rc = 1;
95195     goto multi_select_end;
95196   }
95197
95198   /* Compound SELECTs that have an ORDER BY clause are handled separately.
95199   */
95200   if( p->pOrderBy ){
95201     return multiSelectOrderBy(pParse, p, pDest);
95202   }
95203
95204   /* Generate code for the left and right SELECT statements.
95205   */
95206   switch( p->op ){
95207     case TK_ALL: {
95208       int addr = 0;
95209       int nLimit;
95210       assert( !pPrior->pLimit );
95211       pPrior->pLimit = p->pLimit;
95212       pPrior->pOffset = p->pOffset;
95213       explainSetInteger(iSub1, pParse->iNextSelectId);
95214       rc = sqlite3Select(pParse, pPrior, &dest);
95215       p->pLimit = 0;
95216       p->pOffset = 0;
95217       if( rc ){
95218         goto multi_select_end;
95219       }
95220       p->pPrior = 0;
95221       p->iLimit = pPrior->iLimit;
95222       p->iOffset = pPrior->iOffset;
95223       if( p->iLimit ){
95224         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
95225         VdbeComment((v, "Jump ahead if LIMIT reached"));
95226       }
95227       explainSetInteger(iSub2, pParse->iNextSelectId);
95228       rc = sqlite3Select(pParse, p, &dest);
95229       testcase( rc!=SQLITE_OK );
95230       pDelete = p->pPrior;
95231       p->pPrior = pPrior;
95232       p->nSelectRow += pPrior->nSelectRow;
95233       if( pPrior->pLimit
95234        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
95235        && p->nSelectRow > (double)nLimit 
95236       ){
95237         p->nSelectRow = (double)nLimit;
95238       }
95239       if( addr ){
95240         sqlite3VdbeJumpHere(v, addr);
95241       }
95242       break;
95243     }
95244     case TK_EXCEPT:
95245     case TK_UNION: {
95246       int unionTab;    /* Cursor number of the temporary table holding result */
95247       u8 op = 0;       /* One of the SRT_ operations to apply to self */
95248       int priorOp;     /* The SRT_ operation to apply to prior selects */
95249       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
95250       int addr;
95251       SelectDest uniondest;
95252
95253       testcase( p->op==TK_EXCEPT );
95254       testcase( p->op==TK_UNION );
95255       priorOp = SRT_Union;
95256       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
95257         /* We can reuse a temporary table generated by a SELECT to our
95258         ** right.
95259         */
95260         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
95261                                      ** of a 3-way or more compound */
95262         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
95263         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
95264         unionTab = dest.iSDParm;
95265       }else{
95266         /* We will need to create our own temporary table to hold the
95267         ** intermediate results.
95268         */
95269         unionTab = pParse->nTab++;
95270         assert( p->pOrderBy==0 );
95271         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
95272         assert( p->addrOpenEphm[0] == -1 );
95273         p->addrOpenEphm[0] = addr;
95274         p->pRightmost->selFlags |= SF_UsesEphemeral;
95275         assert( p->pEList );
95276       }
95277
95278       /* Code the SELECT statements to our left
95279       */
95280       assert( !pPrior->pOrderBy );
95281       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
95282       explainSetInteger(iSub1, pParse->iNextSelectId);
95283       rc = sqlite3Select(pParse, pPrior, &uniondest);
95284       if( rc ){
95285         goto multi_select_end;
95286       }
95287
95288       /* Code the current SELECT statement
95289       */
95290       if( p->op==TK_EXCEPT ){
95291         op = SRT_Except;
95292       }else{
95293         assert( p->op==TK_UNION );
95294         op = SRT_Union;
95295       }
95296       p->pPrior = 0;
95297       pLimit = p->pLimit;
95298       p->pLimit = 0;
95299       pOffset = p->pOffset;
95300       p->pOffset = 0;
95301       uniondest.eDest = op;
95302       explainSetInteger(iSub2, pParse->iNextSelectId);
95303       rc = sqlite3Select(pParse, p, &uniondest);
95304       testcase( rc!=SQLITE_OK );
95305       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
95306       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
95307       sqlite3ExprListDelete(db, p->pOrderBy);
95308       pDelete = p->pPrior;
95309       p->pPrior = pPrior;
95310       p->pOrderBy = 0;
95311       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
95312       sqlite3ExprDelete(db, p->pLimit);
95313       p->pLimit = pLimit;
95314       p->pOffset = pOffset;
95315       p->iLimit = 0;
95316       p->iOffset = 0;
95317
95318       /* Convert the data in the temporary table into whatever form
95319       ** it is that we currently need.
95320       */
95321       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
95322       if( dest.eDest!=priorOp ){
95323         int iCont, iBreak, iStart;
95324         assert( p->pEList );
95325         if( dest.eDest==SRT_Output ){
95326           Select *pFirst = p;
95327           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95328           generateColumnNames(pParse, 0, pFirst->pEList);
95329         }
95330         iBreak = sqlite3VdbeMakeLabel(v);
95331         iCont = sqlite3VdbeMakeLabel(v);
95332         computeLimitRegisters(pParse, p, iBreak);
95333         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
95334         iStart = sqlite3VdbeCurrentAddr(v);
95335         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
95336                         0, -1, &dest, iCont, iBreak);
95337         sqlite3VdbeResolveLabel(v, iCont);
95338         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
95339         sqlite3VdbeResolveLabel(v, iBreak);
95340         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
95341       }
95342       break;
95343     }
95344     default: assert( p->op==TK_INTERSECT ); {
95345       int tab1, tab2;
95346       int iCont, iBreak, iStart;
95347       Expr *pLimit, *pOffset;
95348       int addr;
95349       SelectDest intersectdest;
95350       int r1;
95351
95352       /* INTERSECT is different from the others since it requires
95353       ** two temporary tables.  Hence it has its own case.  Begin
95354       ** by allocating the tables we will need.
95355       */
95356       tab1 = pParse->nTab++;
95357       tab2 = pParse->nTab++;
95358       assert( p->pOrderBy==0 );
95359
95360       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
95361       assert( p->addrOpenEphm[0] == -1 );
95362       p->addrOpenEphm[0] = addr;
95363       p->pRightmost->selFlags |= SF_UsesEphemeral;
95364       assert( p->pEList );
95365
95366       /* Code the SELECTs to our left into temporary table "tab1".
95367       */
95368       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
95369       explainSetInteger(iSub1, pParse->iNextSelectId);
95370       rc = sqlite3Select(pParse, pPrior, &intersectdest);
95371       if( rc ){
95372         goto multi_select_end;
95373       }
95374
95375       /* Code the current SELECT into temporary table "tab2"
95376       */
95377       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
95378       assert( p->addrOpenEphm[1] == -1 );
95379       p->addrOpenEphm[1] = addr;
95380       p->pPrior = 0;
95381       pLimit = p->pLimit;
95382       p->pLimit = 0;
95383       pOffset = p->pOffset;
95384       p->pOffset = 0;
95385       intersectdest.iSDParm = tab2;
95386       explainSetInteger(iSub2, pParse->iNextSelectId);
95387       rc = sqlite3Select(pParse, p, &intersectdest);
95388       testcase( rc!=SQLITE_OK );
95389       pDelete = p->pPrior;
95390       p->pPrior = pPrior;
95391       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
95392       sqlite3ExprDelete(db, p->pLimit);
95393       p->pLimit = pLimit;
95394       p->pOffset = pOffset;
95395
95396       /* Generate code to take the intersection of the two temporary
95397       ** tables.
95398       */
95399       assert( p->pEList );
95400       if( dest.eDest==SRT_Output ){
95401         Select *pFirst = p;
95402         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95403         generateColumnNames(pParse, 0, pFirst->pEList);
95404       }
95405       iBreak = sqlite3VdbeMakeLabel(v);
95406       iCont = sqlite3VdbeMakeLabel(v);
95407       computeLimitRegisters(pParse, p, iBreak);
95408       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
95409       r1 = sqlite3GetTempReg(pParse);
95410       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
95411       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
95412       sqlite3ReleaseTempReg(pParse, r1);
95413       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
95414                       0, -1, &dest, iCont, iBreak);
95415       sqlite3VdbeResolveLabel(v, iCont);
95416       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
95417       sqlite3VdbeResolveLabel(v, iBreak);
95418       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
95419       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
95420       break;
95421     }
95422   }
95423
95424   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
95425
95426   /* Compute collating sequences used by 
95427   ** temporary tables needed to implement the compound select.
95428   ** Attach the KeyInfo structure to all temporary tables.
95429   **
95430   ** This section is run by the right-most SELECT statement only.
95431   ** SELECT statements to the left always skip this part.  The right-most
95432   ** SELECT might also skip this part if it has no ORDER BY clause and
95433   ** no temp tables are required.
95434   */
95435   if( p->selFlags & SF_UsesEphemeral ){
95436     int i;                        /* Loop counter */
95437     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
95438     Select *pLoop;                /* For looping through SELECT statements */
95439     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
95440     int nCol;                     /* Number of columns in result set */
95441
95442     assert( p->pRightmost==p );
95443     nCol = p->pEList->nExpr;
95444     pKeyInfo = sqlite3DbMallocZero(db,
95445                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
95446     if( !pKeyInfo ){
95447       rc = SQLITE_NOMEM;
95448       goto multi_select_end;
95449     }
95450
95451     pKeyInfo->enc = ENC(db);
95452     pKeyInfo->nField = (u16)nCol;
95453
95454     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
95455       *apColl = multiSelectCollSeq(pParse, p, i);
95456       if( 0==*apColl ){
95457         *apColl = db->pDfltColl;
95458       }
95459     }
95460
95461     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
95462       for(i=0; i<2; i++){
95463         int addr = pLoop->addrOpenEphm[i];
95464         if( addr<0 ){
95465           /* If [0] is unused then [1] is also unused.  So we can
95466           ** always safely abort as soon as the first unused slot is found */
95467           assert( pLoop->addrOpenEphm[1]<0 );
95468           break;
95469         }
95470         sqlite3VdbeChangeP2(v, addr, nCol);
95471         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
95472         pLoop->addrOpenEphm[i] = -1;
95473       }
95474     }
95475     sqlite3DbFree(db, pKeyInfo);
95476   }
95477
95478 multi_select_end:
95479   pDest->iSdst = dest.iSdst;
95480   pDest->nSdst = dest.nSdst;
95481   sqlite3SelectDelete(db, pDelete);
95482   return rc;
95483 }
95484 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95485
95486 /*
95487 ** Code an output subroutine for a coroutine implementation of a
95488 ** SELECT statment.
95489 **
95490 ** The data to be output is contained in pIn->iSdst.  There are
95491 ** pIn->nSdst columns to be output.  pDest is where the output should
95492 ** be sent.
95493 **
95494 ** regReturn is the number of the register holding the subroutine
95495 ** return address.
95496 **
95497 ** If regPrev>0 then it is the first register in a vector that
95498 ** records the previous output.  mem[regPrev] is a flag that is false
95499 ** if there has been no previous output.  If regPrev>0 then code is
95500 ** generated to suppress duplicates.  pKeyInfo is used for comparing
95501 ** keys.
95502 **
95503 ** If the LIMIT found in p->iLimit is reached, jump immediately to
95504 ** iBreak.
95505 */
95506 static int generateOutputSubroutine(
95507   Parse *pParse,          /* Parsing context */
95508   Select *p,              /* The SELECT statement */
95509   SelectDest *pIn,        /* Coroutine supplying data */
95510   SelectDest *pDest,      /* Where to send the data */
95511   int regReturn,          /* The return address register */
95512   int regPrev,            /* Previous result register.  No uniqueness if 0 */
95513   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
95514   int p4type,             /* The p4 type for pKeyInfo */
95515   int iBreak              /* Jump here if we hit the LIMIT */
95516 ){
95517   Vdbe *v = pParse->pVdbe;
95518   int iContinue;
95519   int addr;
95520
95521   addr = sqlite3VdbeCurrentAddr(v);
95522   iContinue = sqlite3VdbeMakeLabel(v);
95523
95524   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
95525   */
95526   if( regPrev ){
95527     int j1, j2;
95528     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
95529     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
95530                               (char*)pKeyInfo, p4type);
95531     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
95532     sqlite3VdbeJumpHere(v, j1);
95533     sqlite3ExprCodeCopy(pParse, pIn->iSdst, regPrev+1, pIn->nSdst);
95534     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
95535   }
95536   if( pParse->db->mallocFailed ) return 0;
95537
95538   /* Suppress the first OFFSET entries if there is an OFFSET clause
95539   */
95540   codeOffset(v, p, iContinue);
95541
95542   switch( pDest->eDest ){
95543     /* Store the result as data using a unique key.
95544     */
95545     case SRT_Table:
95546     case SRT_EphemTab: {
95547       int r1 = sqlite3GetTempReg(pParse);
95548       int r2 = sqlite3GetTempReg(pParse);
95549       testcase( pDest->eDest==SRT_Table );
95550       testcase( pDest->eDest==SRT_EphemTab );
95551       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
95552       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
95553       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
95554       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95555       sqlite3ReleaseTempReg(pParse, r2);
95556       sqlite3ReleaseTempReg(pParse, r1);
95557       break;
95558     }
95559
95560 #ifndef SQLITE_OMIT_SUBQUERY
95561     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95562     ** then there should be a single item on the stack.  Write this
95563     ** item into the set table with bogus data.
95564     */
95565     case SRT_Set: {
95566       int r1;
95567       assert( pIn->nSdst==1 );
95568       p->affinity = 
95569          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
95570       r1 = sqlite3GetTempReg(pParse);
95571       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &p->affinity, 1);
95572       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
95573       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
95574       sqlite3ReleaseTempReg(pParse, r1);
95575       break;
95576     }
95577
95578 #if 0  /* Never occurs on an ORDER BY query */
95579     /* If any row exist in the result set, record that fact and abort.
95580     */
95581     case SRT_Exists: {
95582       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
95583       /* The LIMIT clause will terminate the loop for us */
95584       break;
95585     }
95586 #endif
95587
95588     /* If this is a scalar select that is part of an expression, then
95589     ** store the results in the appropriate memory cell and break out
95590     ** of the scan loop.
95591     */
95592     case SRT_Mem: {
95593       assert( pIn->nSdst==1 );
95594       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
95595       /* The LIMIT clause will jump out of the loop for us */
95596       break;
95597     }
95598 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95599
95600     /* The results are stored in a sequence of registers
95601     ** starting at pDest->iSdst.  Then the co-routine yields.
95602     */
95603     case SRT_Coroutine: {
95604       if( pDest->iSdst==0 ){
95605         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
95606         pDest->nSdst = pIn->nSdst;
95607       }
95608       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
95609       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95610       break;
95611     }
95612
95613     /* If none of the above, then the result destination must be
95614     ** SRT_Output.  This routine is never called with any other
95615     ** destination other than the ones handled above or SRT_Output.
95616     **
95617     ** For SRT_Output, results are stored in a sequence of registers.  
95618     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
95619     ** return the next row of result.
95620     */
95621     default: {
95622       assert( pDest->eDest==SRT_Output );
95623       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
95624       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
95625       break;
95626     }
95627   }
95628
95629   /* Jump to the end of the loop if the LIMIT is reached.
95630   */
95631   if( p->iLimit ){
95632     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95633   }
95634
95635   /* Generate the subroutine return
95636   */
95637   sqlite3VdbeResolveLabel(v, iContinue);
95638   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
95639
95640   return addr;
95641 }
95642
95643 /*
95644 ** Alternative compound select code generator for cases when there
95645 ** is an ORDER BY clause.
95646 **
95647 ** We assume a query of the following form:
95648 **
95649 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
95650 **
95651 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
95652 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
95653 ** co-routines.  Then run the co-routines in parallel and merge the results
95654 ** into the output.  In addition to the two coroutines (called selectA and
95655 ** selectB) there are 7 subroutines:
95656 **
95657 **    outA:    Move the output of the selectA coroutine into the output
95658 **             of the compound query.
95659 **
95660 **    outB:    Move the output of the selectB coroutine into the output
95661 **             of the compound query.  (Only generated for UNION and
95662 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
95663 **             appears only in B.)
95664 **
95665 **    AltB:    Called when there is data from both coroutines and A<B.
95666 **
95667 **    AeqB:    Called when there is data from both coroutines and A==B.
95668 **
95669 **    AgtB:    Called when there is data from both coroutines and A>B.
95670 **
95671 **    EofA:    Called when data is exhausted from selectA.
95672 **
95673 **    EofB:    Called when data is exhausted from selectB.
95674 **
95675 ** The implementation of the latter five subroutines depend on which 
95676 ** <operator> is used:
95677 **
95678 **
95679 **             UNION ALL         UNION            EXCEPT          INTERSECT
95680 **          -------------  -----------------  --------------  -----------------
95681 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
95682 **
95683 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
95684 **
95685 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
95686 **
95687 **   EofA:   outB, nextB      outB, nextB          halt             halt
95688 **
95689 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
95690 **
95691 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
95692 ** causes an immediate jump to EofA and an EOF on B following nextB causes
95693 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
95694 ** following nextX causes a jump to the end of the select processing.
95695 **
95696 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
95697 ** within the output subroutine.  The regPrev register set holds the previously
95698 ** output value.  A comparison is made against this value and the output
95699 ** is skipped if the next results would be the same as the previous.
95700 **
95701 ** The implementation plan is to implement the two coroutines and seven
95702 ** subroutines first, then put the control logic at the bottom.  Like this:
95703 **
95704 **          goto Init
95705 **     coA: coroutine for left query (A)
95706 **     coB: coroutine for right query (B)
95707 **    outA: output one row of A
95708 **    outB: output one row of B (UNION and UNION ALL only)
95709 **    EofA: ...
95710 **    EofB: ...
95711 **    AltB: ...
95712 **    AeqB: ...
95713 **    AgtB: ...
95714 **    Init: initialize coroutine registers
95715 **          yield coA
95716 **          if eof(A) goto EofA
95717 **          yield coB
95718 **          if eof(B) goto EofB
95719 **    Cmpr: Compare A, B
95720 **          Jump AltB, AeqB, AgtB
95721 **     End: ...
95722 **
95723 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
95724 ** actually called using Gosub and they do not Return.  EofA and EofB loop
95725 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
95726 ** and AgtB jump to either L2 or to one of EofA or EofB.
95727 */
95728 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95729 static int multiSelectOrderBy(
95730   Parse *pParse,        /* Parsing context */
95731   Select *p,            /* The right-most of SELECTs to be coded */
95732   SelectDest *pDest     /* What to do with query results */
95733 ){
95734   int i, j;             /* Loop counters */
95735   Select *pPrior;       /* Another SELECT immediately to our left */
95736   Vdbe *v;              /* Generate code to this VDBE */
95737   SelectDest destA;     /* Destination for coroutine A */
95738   SelectDest destB;     /* Destination for coroutine B */
95739   int regAddrA;         /* Address register for select-A coroutine */
95740   int regEofA;          /* Flag to indicate when select-A is complete */
95741   int regAddrB;         /* Address register for select-B coroutine */
95742   int regEofB;          /* Flag to indicate when select-B is complete */
95743   int addrSelectA;      /* Address of the select-A coroutine */
95744   int addrSelectB;      /* Address of the select-B coroutine */
95745   int regOutA;          /* Address register for the output-A subroutine */
95746   int regOutB;          /* Address register for the output-B subroutine */
95747   int addrOutA;         /* Address of the output-A subroutine */
95748   int addrOutB = 0;     /* Address of the output-B subroutine */
95749   int addrEofA;         /* Address of the select-A-exhausted subroutine */
95750   int addrEofB;         /* Address of the select-B-exhausted subroutine */
95751   int addrAltB;         /* Address of the A<B subroutine */
95752   int addrAeqB;         /* Address of the A==B subroutine */
95753   int addrAgtB;         /* Address of the A>B subroutine */
95754   int regLimitA;        /* Limit register for select-A */
95755   int regLimitB;        /* Limit register for select-A */
95756   int regPrev;          /* A range of registers to hold previous output */
95757   int savedLimit;       /* Saved value of p->iLimit */
95758   int savedOffset;      /* Saved value of p->iOffset */
95759   int labelCmpr;        /* Label for the start of the merge algorithm */
95760   int labelEnd;         /* Label for the end of the overall SELECT stmt */
95761   int j1;               /* Jump instructions that get retargetted */
95762   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
95763   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
95764   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
95765   sqlite3 *db;          /* Database connection */
95766   ExprList *pOrderBy;   /* The ORDER BY clause */
95767   int nOrderBy;         /* Number of terms in the ORDER BY clause */
95768   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
95769 #ifndef SQLITE_OMIT_EXPLAIN
95770   int iSub1;            /* EQP id of left-hand query */
95771   int iSub2;            /* EQP id of right-hand query */
95772 #endif
95773
95774   assert( p->pOrderBy!=0 );
95775   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
95776   db = pParse->db;
95777   v = pParse->pVdbe;
95778   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
95779   labelEnd = sqlite3VdbeMakeLabel(v);
95780   labelCmpr = sqlite3VdbeMakeLabel(v);
95781
95782
95783   /* Patch up the ORDER BY clause
95784   */
95785   op = p->op;  
95786   pPrior = p->pPrior;
95787   assert( pPrior->pOrderBy==0 );
95788   pOrderBy = p->pOrderBy;
95789   assert( pOrderBy );
95790   nOrderBy = pOrderBy->nExpr;
95791
95792   /* For operators other than UNION ALL we have to make sure that
95793   ** the ORDER BY clause covers every term of the result set.  Add
95794   ** terms to the ORDER BY clause as necessary.
95795   */
95796   if( op!=TK_ALL ){
95797     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
95798       struct ExprList_item *pItem;
95799       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
95800         assert( pItem->iOrderByCol>0 );
95801         if( pItem->iOrderByCol==i ) break;
95802       }
95803       if( j==nOrderBy ){
95804         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
95805         if( pNew==0 ) return SQLITE_NOMEM;
95806         pNew->flags |= EP_IntValue;
95807         pNew->u.iValue = i;
95808         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
95809         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
95810       }
95811     }
95812   }
95813
95814   /* Compute the comparison permutation and keyinfo that is used with
95815   ** the permutation used to determine if the next
95816   ** row of results comes from selectA or selectB.  Also add explicit
95817   ** collations to the ORDER BY clause terms so that when the subqueries
95818   ** to the right and the left are evaluated, they use the correct
95819   ** collation.
95820   */
95821   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
95822   if( aPermute ){
95823     struct ExprList_item *pItem;
95824     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
95825       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
95826       aPermute[i] = pItem->iOrderByCol - 1;
95827     }
95828     pKeyMerge =
95829       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
95830     if( pKeyMerge ){
95831       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
95832       pKeyMerge->nField = (u16)nOrderBy;
95833       pKeyMerge->enc = ENC(db);
95834       for(i=0; i<nOrderBy; i++){
95835         CollSeq *pColl;
95836         Expr *pTerm = pOrderBy->a[i].pExpr;
95837         if( pTerm->flags & EP_ExpCollate ){
95838           pColl = pTerm->pColl;
95839         }else{
95840           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
95841           pTerm->flags |= EP_ExpCollate;
95842           pTerm->pColl = pColl;
95843         }
95844         pKeyMerge->aColl[i] = pColl;
95845         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
95846       }
95847     }
95848   }else{
95849     pKeyMerge = 0;
95850   }
95851
95852   /* Reattach the ORDER BY clause to the query.
95853   */
95854   p->pOrderBy = pOrderBy;
95855   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
95856
95857   /* Allocate a range of temporary registers and the KeyInfo needed
95858   ** for the logic that removes duplicate result rows when the
95859   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
95860   */
95861   if( op==TK_ALL ){
95862     regPrev = 0;
95863   }else{
95864     int nExpr = p->pEList->nExpr;
95865     assert( nOrderBy>=nExpr || db->mallocFailed );
95866     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
95867     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
95868     pKeyDup = sqlite3DbMallocZero(db,
95869                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
95870     if( pKeyDup ){
95871       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
95872       pKeyDup->nField = (u16)nExpr;
95873       pKeyDup->enc = ENC(db);
95874       for(i=0; i<nExpr; i++){
95875         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
95876         pKeyDup->aSortOrder[i] = 0;
95877       }
95878     }
95879   }
95880  
95881   /* Separate the left and the right query from one another
95882   */
95883   p->pPrior = 0;
95884   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
95885   if( pPrior->pPrior==0 ){
95886     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
95887   }
95888
95889   /* Compute the limit registers */
95890   computeLimitRegisters(pParse, p, labelEnd);
95891   if( p->iLimit && op==TK_ALL ){
95892     regLimitA = ++pParse->nMem;
95893     regLimitB = ++pParse->nMem;
95894     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
95895                                   regLimitA);
95896     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
95897   }else{
95898     regLimitA = regLimitB = 0;
95899   }
95900   sqlite3ExprDelete(db, p->pLimit);
95901   p->pLimit = 0;
95902   sqlite3ExprDelete(db, p->pOffset);
95903   p->pOffset = 0;
95904
95905   regAddrA = ++pParse->nMem;
95906   regEofA = ++pParse->nMem;
95907   regAddrB = ++pParse->nMem;
95908   regEofB = ++pParse->nMem;
95909   regOutA = ++pParse->nMem;
95910   regOutB = ++pParse->nMem;
95911   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
95912   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
95913
95914   /* Jump past the various subroutines and coroutines to the main
95915   ** merge loop
95916   */
95917   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
95918   addrSelectA = sqlite3VdbeCurrentAddr(v);
95919
95920
95921   /* Generate a coroutine to evaluate the SELECT statement to the
95922   ** left of the compound operator - the "A" select.
95923   */
95924   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
95925   pPrior->iLimit = regLimitA;
95926   explainSetInteger(iSub1, pParse->iNextSelectId);
95927   sqlite3Select(pParse, pPrior, &destA);
95928   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
95929   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95930   VdbeNoopComment((v, "End coroutine for left SELECT"));
95931
95932   /* Generate a coroutine to evaluate the SELECT statement on 
95933   ** the right - the "B" select
95934   */
95935   addrSelectB = sqlite3VdbeCurrentAddr(v);
95936   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
95937   savedLimit = p->iLimit;
95938   savedOffset = p->iOffset;
95939   p->iLimit = regLimitB;
95940   p->iOffset = 0;  
95941   explainSetInteger(iSub2, pParse->iNextSelectId);
95942   sqlite3Select(pParse, p, &destB);
95943   p->iLimit = savedLimit;
95944   p->iOffset = savedOffset;
95945   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
95946   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
95947   VdbeNoopComment((v, "End coroutine for right SELECT"));
95948
95949   /* Generate a subroutine that outputs the current row of the A
95950   ** select as the next output row of the compound select.
95951   */
95952   VdbeNoopComment((v, "Output routine for A"));
95953   addrOutA = generateOutputSubroutine(pParse,
95954                  p, &destA, pDest, regOutA,
95955                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
95956   
95957   /* Generate a subroutine that outputs the current row of the B
95958   ** select as the next output row of the compound select.
95959   */
95960   if( op==TK_ALL || op==TK_UNION ){
95961     VdbeNoopComment((v, "Output routine for B"));
95962     addrOutB = generateOutputSubroutine(pParse,
95963                  p, &destB, pDest, regOutB,
95964                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
95965   }
95966
95967   /* Generate a subroutine to run when the results from select A
95968   ** are exhausted and only data in select B remains.
95969   */
95970   VdbeNoopComment((v, "eof-A subroutine"));
95971   if( op==TK_EXCEPT || op==TK_INTERSECT ){
95972     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
95973   }else{  
95974     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
95975     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
95976     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
95977     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
95978     p->nSelectRow += pPrior->nSelectRow;
95979   }
95980
95981   /* Generate a subroutine to run when the results from select B
95982   ** are exhausted and only data in select A remains.
95983   */
95984   if( op==TK_INTERSECT ){
95985     addrEofB = addrEofA;
95986     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
95987   }else{  
95988     VdbeNoopComment((v, "eof-B subroutine"));
95989     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
95990     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
95991     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95992     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
95993   }
95994
95995   /* Generate code to handle the case of A<B
95996   */
95997   VdbeNoopComment((v, "A-lt-B subroutine"));
95998   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
95999   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96000   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96001   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96002
96003   /* Generate code to handle the case of A==B
96004   */
96005   if( op==TK_ALL ){
96006     addrAeqB = addrAltB;
96007   }else if( op==TK_INTERSECT ){
96008     addrAeqB = addrAltB;
96009     addrAltB++;
96010   }else{
96011     VdbeNoopComment((v, "A-eq-B subroutine"));
96012     addrAeqB =
96013     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96014     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96015     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96016   }
96017
96018   /* Generate code to handle the case of A>B
96019   */
96020   VdbeNoopComment((v, "A-gt-B subroutine"));
96021   addrAgtB = sqlite3VdbeCurrentAddr(v);
96022   if( op==TK_ALL || op==TK_UNION ){
96023     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96024   }
96025   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96026   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96027   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96028
96029   /* This code runs once to initialize everything.
96030   */
96031   sqlite3VdbeJumpHere(v, j1);
96032   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96033   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96034   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96035   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96036   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96037   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96038
96039   /* Implement the main merge loop
96040   */
96041   sqlite3VdbeResolveLabel(v, labelCmpr);
96042   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96043   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
96044                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96045   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96046
96047   /* Release temporary registers
96048   */
96049   if( regPrev ){
96050     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96051   }
96052
96053   /* Jump to the this point in order to terminate the query.
96054   */
96055   sqlite3VdbeResolveLabel(v, labelEnd);
96056
96057   /* Set the number of output columns
96058   */
96059   if( pDest->eDest==SRT_Output ){
96060     Select *pFirst = pPrior;
96061     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96062     generateColumnNames(pParse, 0, pFirst->pEList);
96063   }
96064
96065   /* Reassembly the compound query so that it will be freed correctly
96066   ** by the calling function */
96067   if( p->pPrior ){
96068     sqlite3SelectDelete(db, p->pPrior);
96069   }
96070   p->pPrior = pPrior;
96071
96072   /*** TBD:  Insert subroutine calls to close cursors on incomplete
96073   **** subqueries ****/
96074   explainComposite(pParse, p->op, iSub1, iSub2, 0);
96075   return SQLITE_OK;
96076 }
96077 #endif
96078
96079 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96080 /* Forward Declarations */
96081 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
96082 static void substSelect(sqlite3*, Select *, int, ExprList *);
96083
96084 /*
96085 ** Scan through the expression pExpr.  Replace every reference to
96086 ** a column in table number iTable with a copy of the iColumn-th
96087 ** entry in pEList.  (But leave references to the ROWID column 
96088 ** unchanged.)
96089 **
96090 ** This routine is part of the flattening procedure.  A subquery
96091 ** whose result set is defined by pEList appears as entry in the
96092 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
96093 ** FORM clause entry is iTable.  This routine make the necessary 
96094 ** changes to pExpr so that it refers directly to the source table
96095 ** of the subquery rather the result set of the subquery.
96096 */
96097 static Expr *substExpr(
96098   sqlite3 *db,        /* Report malloc errors to this connection */
96099   Expr *pExpr,        /* Expr in which substitution occurs */
96100   int iTable,         /* Table to be substituted */
96101   ExprList *pEList    /* Substitute expressions */
96102 ){
96103   if( pExpr==0 ) return 0;
96104   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
96105     if( pExpr->iColumn<0 ){
96106       pExpr->op = TK_NULL;
96107     }else{
96108       Expr *pNew;
96109       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
96110       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
96111       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
96112       if( pNew && pExpr->pColl ){
96113         pNew->pColl = pExpr->pColl;
96114       }
96115       sqlite3ExprDelete(db, pExpr);
96116       pExpr = pNew;
96117     }
96118   }else{
96119     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
96120     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
96121     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96122       substSelect(db, pExpr->x.pSelect, iTable, pEList);
96123     }else{
96124       substExprList(db, pExpr->x.pList, iTable, pEList);
96125     }
96126   }
96127   return pExpr;
96128 }
96129 static void substExprList(
96130   sqlite3 *db,         /* Report malloc errors here */
96131   ExprList *pList,     /* List to scan and in which to make substitutes */
96132   int iTable,          /* Table to be substituted */
96133   ExprList *pEList     /* Substitute values */
96134 ){
96135   int i;
96136   if( pList==0 ) return;
96137   for(i=0; i<pList->nExpr; i++){
96138     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
96139   }
96140 }
96141 static void substSelect(
96142   sqlite3 *db,         /* Report malloc errors here */
96143   Select *p,           /* SELECT statement in which to make substitutions */
96144   int iTable,          /* Table to be replaced */
96145   ExprList *pEList     /* Substitute values */
96146 ){
96147   SrcList *pSrc;
96148   struct SrcList_item *pItem;
96149   int i;
96150   if( !p ) return;
96151   substExprList(db, p->pEList, iTable, pEList);
96152   substExprList(db, p->pGroupBy, iTable, pEList);
96153   substExprList(db, p->pOrderBy, iTable, pEList);
96154   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
96155   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
96156   substSelect(db, p->pPrior, iTable, pEList);
96157   pSrc = p->pSrc;
96158   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
96159   if( ALWAYS(pSrc) ){
96160     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
96161       substSelect(db, pItem->pSelect, iTable, pEList);
96162     }
96163   }
96164 }
96165 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
96166
96167 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96168 /*
96169 ** This routine attempts to flatten subqueries as a performance optimization.
96170 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
96171 **
96172 ** To understand the concept of flattening, consider the following
96173 ** query:
96174 **
96175 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
96176 **
96177 ** The default way of implementing this query is to execute the
96178 ** subquery first and store the results in a temporary table, then
96179 ** run the outer query on that temporary table.  This requires two
96180 ** passes over the data.  Furthermore, because the temporary table
96181 ** has no indices, the WHERE clause on the outer query cannot be
96182 ** optimized.
96183 **
96184 ** This routine attempts to rewrite queries such as the above into
96185 ** a single flat select, like this:
96186 **
96187 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
96188 **
96189 ** The code generated for this simpification gives the same result
96190 ** but only has to scan the data once.  And because indices might 
96191 ** exist on the table t1, a complete scan of the data might be
96192 ** avoided.
96193 **
96194 ** Flattening is only attempted if all of the following are true:
96195 **
96196 **   (1)  The subquery and the outer query do not both use aggregates.
96197 **
96198 **   (2)  The subquery is not an aggregate or the outer query is not a join.
96199 **
96200 **   (3)  The subquery is not the right operand of a left outer join
96201 **        (Originally ticket #306.  Strengthened by ticket #3300)
96202 **
96203 **   (4)  The subquery is not DISTINCT.
96204 **
96205 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
96206 **        sub-queries that were excluded from this optimization. Restriction 
96207 **        (4) has since been expanded to exclude all DISTINCT subqueries.
96208 **
96209 **   (6)  The subquery does not use aggregates or the outer query is not
96210 **        DISTINCT.
96211 **
96212 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
96213 **        A FROM clause, consider adding a FROM close with the special
96214 **        table sqlite_once that consists of a single row containing a
96215 **        single NULL.
96216 **
96217 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
96218 **
96219 **   (9)  The subquery does not use LIMIT or the outer query does not use
96220 **        aggregates.
96221 **
96222 **  (10)  The subquery does not use aggregates or the outer query does not
96223 **        use LIMIT.
96224 **
96225 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
96226 **
96227 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
96228 **        a separate restriction deriving from ticket #350.
96229 **
96230 **  (13)  The subquery and outer query do not both use LIMIT.
96231 **
96232 **  (14)  The subquery does not use OFFSET.
96233 **
96234 **  (15)  The outer query is not part of a compound select or the
96235 **        subquery does not have a LIMIT clause.
96236 **        (See ticket #2339 and ticket [02a8e81d44]).
96237 **
96238 **  (16)  The outer query is not an aggregate or the subquery does
96239 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
96240 **        until we introduced the group_concat() function.  
96241 **
96242 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
96243 **        compound clause made up entirely of non-aggregate queries, and 
96244 **        the parent query:
96245 **
96246 **          * is not itself part of a compound select,
96247 **          * is not an aggregate or DISTINCT query, and
96248 **          * is not a join
96249 **
96250 **        The parent and sub-query may contain WHERE clauses. Subject to
96251 **        rules (11), (13) and (14), they may also contain ORDER BY,
96252 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
96253 **        operator other than UNION ALL because all the other compound
96254 **        operators have an implied DISTINCT which is disallowed by
96255 **        restriction (4).
96256 **
96257 **        Also, each component of the sub-query must return the same number
96258 **        of result columns. This is actually a requirement for any compound
96259 **        SELECT statement, but all the code here does is make sure that no
96260 **        such (illegal) sub-query is flattened. The caller will detect the
96261 **        syntax error and return a detailed message.
96262 **
96263 **  (18)  If the sub-query is a compound select, then all terms of the
96264 **        ORDER by clause of the parent must be simple references to 
96265 **        columns of the sub-query.
96266 **
96267 **  (19)  The subquery does not use LIMIT or the outer query does not
96268 **        have a WHERE clause.
96269 **
96270 **  (20)  If the sub-query is a compound select, then it must not use
96271 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
96272 **        somewhat by saying that the terms of the ORDER BY clause must
96273 **        appear as unmodified result columns in the outer query.  But we
96274 **        have other optimizations in mind to deal with that case.
96275 **
96276 **  (21)  The subquery does not use LIMIT or the outer query is not
96277 **        DISTINCT.  (See ticket [752e1646fc]).
96278 **
96279 ** In this routine, the "p" parameter is a pointer to the outer query.
96280 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
96281 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
96282 **
96283 ** If flattening is not attempted, this routine is a no-op and returns 0.
96284 ** If flattening is attempted this routine returns 1.
96285 **
96286 ** All of the expression analysis must occur on both the outer query and
96287 ** the subquery before this routine runs.
96288 */
96289 static int flattenSubquery(
96290   Parse *pParse,       /* Parsing context */
96291   Select *p,           /* The parent or outer SELECT statement */
96292   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
96293   int isAgg,           /* True if outer SELECT uses aggregate functions */
96294   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
96295 ){
96296   const char *zSavedAuthContext = pParse->zAuthContext;
96297   Select *pParent;
96298   Select *pSub;       /* The inner query or "subquery" */
96299   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
96300   SrcList *pSrc;      /* The FROM clause of the outer query */
96301   SrcList *pSubSrc;   /* The FROM clause of the subquery */
96302   ExprList *pList;    /* The result set of the outer query */
96303   int iParent;        /* VDBE cursor number of the pSub result set temp table */
96304   int i;              /* Loop counter */
96305   Expr *pWhere;                    /* The WHERE clause */
96306   struct SrcList_item *pSubitem;   /* The subquery */
96307   sqlite3 *db = pParse->db;
96308
96309   /* Check to see if flattening is permitted.  Return 0 if not.
96310   */
96311   assert( p!=0 );
96312   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
96313   if( db->flags & SQLITE_QueryFlattener ) return 0;
96314   pSrc = p->pSrc;
96315   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
96316   pSubitem = &pSrc->a[iFrom];
96317   iParent = pSubitem->iCursor;
96318   pSub = pSubitem->pSelect;
96319   assert( pSub!=0 );
96320   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
96321   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
96322   pSubSrc = pSub->pSrc;
96323   assert( pSubSrc );
96324   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
96325   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
96326   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
96327   ** became arbitrary expressions, we were forced to add restrictions (13)
96328   ** and (14). */
96329   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
96330   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
96331   if( p->pRightmost && pSub->pLimit ){
96332     return 0;                                            /* Restriction (15) */
96333   }
96334   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
96335   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
96336   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
96337      return 0;         /* Restrictions (8)(9) */
96338   }
96339   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
96340      return 0;         /* Restriction (6)  */
96341   }
96342   if( p->pOrderBy && pSub->pOrderBy ){
96343      return 0;                                           /* Restriction (11) */
96344   }
96345   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
96346   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
96347   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
96348      return 0;         /* Restriction (21) */
96349   }
96350
96351   /* OBSOLETE COMMENT 1:
96352   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
96353   ** not used as the right operand of an outer join.  Examples of why this
96354   ** is not allowed:
96355   **
96356   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
96357   **
96358   ** If we flatten the above, we would get
96359   **
96360   **         (t1 LEFT OUTER JOIN t2) JOIN t3
96361   **
96362   ** which is not at all the same thing.
96363   **
96364   ** OBSOLETE COMMENT 2:
96365   ** Restriction 12:  If the subquery is the right operand of a left outer
96366   ** join, make sure the subquery has no WHERE clause.
96367   ** An examples of why this is not allowed:
96368   **
96369   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
96370   **
96371   ** If we flatten the above, we would get
96372   **
96373   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
96374   **
96375   ** But the t2.x>0 test will always fail on a NULL row of t2, which
96376   ** effectively converts the OUTER JOIN into an INNER JOIN.
96377   **
96378   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
96379   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
96380   ** is fraught with danger.  Best to avoid the whole thing.  If the
96381   ** subquery is the right term of a LEFT JOIN, then do not flatten.
96382   */
96383   if( (pSubitem->jointype & JT_OUTER)!=0 ){
96384     return 0;
96385   }
96386
96387   /* Restriction 17: If the sub-query is a compound SELECT, then it must
96388   ** use only the UNION ALL operator. And none of the simple select queries
96389   ** that make up the compound SELECT are allowed to be aggregate or distinct
96390   ** queries.
96391   */
96392   if( pSub->pPrior ){
96393     if( pSub->pOrderBy ){
96394       return 0;  /* Restriction 20 */
96395     }
96396     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
96397       return 0;
96398     }
96399     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
96400       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
96401       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
96402       assert( pSub->pSrc!=0 );
96403       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
96404        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
96405        || pSub1->pSrc->nSrc<1
96406        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
96407       ){
96408         return 0;
96409       }
96410       testcase( pSub1->pSrc->nSrc>1 );
96411     }
96412
96413     /* Restriction 18. */
96414     if( p->pOrderBy ){
96415       int ii;
96416       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
96417         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
96418       }
96419     }
96420   }
96421
96422   /***** If we reach this point, flattening is permitted. *****/
96423
96424   /* Authorize the subquery */
96425   pParse->zAuthContext = pSubitem->zName;
96426   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
96427   testcase( i==SQLITE_DENY );
96428   pParse->zAuthContext = zSavedAuthContext;
96429
96430   /* If the sub-query is a compound SELECT statement, then (by restrictions
96431   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
96432   ** be of the form:
96433   **
96434   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
96435   **
96436   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
96437   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
96438   ** OFFSET clauses and joins them to the left-hand-side of the original
96439   ** using UNION ALL operators. In this case N is the number of simple
96440   ** select statements in the compound sub-query.
96441   **
96442   ** Example:
96443   **
96444   **     SELECT a+1 FROM (
96445   **        SELECT x FROM tab
96446   **        UNION ALL
96447   **        SELECT y FROM tab
96448   **        UNION ALL
96449   **        SELECT abs(z*2) FROM tab2
96450   **     ) WHERE a!=5 ORDER BY 1
96451   **
96452   ** Transformed into:
96453   **
96454   **     SELECT x+1 FROM tab WHERE x+1!=5
96455   **     UNION ALL
96456   **     SELECT y+1 FROM tab WHERE y+1!=5
96457   **     UNION ALL
96458   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
96459   **     ORDER BY 1
96460   **
96461   ** We call this the "compound-subquery flattening".
96462   */
96463   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
96464     Select *pNew;
96465     ExprList *pOrderBy = p->pOrderBy;
96466     Expr *pLimit = p->pLimit;
96467     Select *pPrior = p->pPrior;
96468     p->pOrderBy = 0;
96469     p->pSrc = 0;
96470     p->pPrior = 0;
96471     p->pLimit = 0;
96472     pNew = sqlite3SelectDup(db, p, 0);
96473     p->pLimit = pLimit;
96474     p->pOrderBy = pOrderBy;
96475     p->pSrc = pSrc;
96476     p->op = TK_ALL;
96477     p->pRightmost = 0;
96478     if( pNew==0 ){
96479       pNew = pPrior;
96480     }else{
96481       pNew->pPrior = pPrior;
96482       pNew->pRightmost = 0;
96483     }
96484     p->pPrior = pNew;
96485     if( db->mallocFailed ) return 1;
96486   }
96487
96488   /* Begin flattening the iFrom-th entry of the FROM clause 
96489   ** in the outer query.
96490   */
96491   pSub = pSub1 = pSubitem->pSelect;
96492
96493   /* Delete the transient table structure associated with the
96494   ** subquery
96495   */
96496   sqlite3DbFree(db, pSubitem->zDatabase);
96497   sqlite3DbFree(db, pSubitem->zName);
96498   sqlite3DbFree(db, pSubitem->zAlias);
96499   pSubitem->zDatabase = 0;
96500   pSubitem->zName = 0;
96501   pSubitem->zAlias = 0;
96502   pSubitem->pSelect = 0;
96503
96504   /* Defer deleting the Table object associated with the
96505   ** subquery until code generation is
96506   ** complete, since there may still exist Expr.pTab entries that
96507   ** refer to the subquery even after flattening.  Ticket #3346.
96508   **
96509   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
96510   */
96511   if( ALWAYS(pSubitem->pTab!=0) ){
96512     Table *pTabToDel = pSubitem->pTab;
96513     if( pTabToDel->nRef==1 ){
96514       Parse *pToplevel = sqlite3ParseToplevel(pParse);
96515       pTabToDel->pNextZombie = pToplevel->pZombieTab;
96516       pToplevel->pZombieTab = pTabToDel;
96517     }else{
96518       pTabToDel->nRef--;
96519     }
96520     pSubitem->pTab = 0;
96521   }
96522
96523   /* The following loop runs once for each term in a compound-subquery
96524   ** flattening (as described above).  If we are doing a different kind
96525   ** of flattening - a flattening other than a compound-subquery flattening -
96526   ** then this loop only runs once.
96527   **
96528   ** This loop moves all of the FROM elements of the subquery into the
96529   ** the FROM clause of the outer query.  Before doing this, remember
96530   ** the cursor number for the original outer query FROM element in
96531   ** iParent.  The iParent cursor will never be used.  Subsequent code
96532   ** will scan expressions looking for iParent references and replace
96533   ** those references with expressions that resolve to the subquery FROM
96534   ** elements we are now copying in.
96535   */
96536   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
96537     int nSubSrc;
96538     u8 jointype = 0;
96539     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
96540     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
96541     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
96542
96543     if( pSrc ){
96544       assert( pParent==p );  /* First time through the loop */
96545       jointype = pSubitem->jointype;
96546     }else{
96547       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
96548       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
96549       if( pSrc==0 ){
96550         assert( db->mallocFailed );
96551         break;
96552       }
96553     }
96554
96555     /* The subquery uses a single slot of the FROM clause of the outer
96556     ** query.  If the subquery has more than one element in its FROM clause,
96557     ** then expand the outer query to make space for it to hold all elements
96558     ** of the subquery.
96559     **
96560     ** Example:
96561     **
96562     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
96563     **
96564     ** The outer query has 3 slots in its FROM clause.  One slot of the
96565     ** outer query (the middle slot) is used by the subquery.  The next
96566     ** block of code will expand the out query to 4 slots.  The middle
96567     ** slot is expanded to two slots in order to make space for the
96568     ** two elements in the FROM clause of the subquery.
96569     */
96570     if( nSubSrc>1 ){
96571       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
96572       if( db->mallocFailed ){
96573         break;
96574       }
96575     }
96576
96577     /* Transfer the FROM clause terms from the subquery into the
96578     ** outer query.
96579     */
96580     for(i=0; i<nSubSrc; i++){
96581       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
96582       pSrc->a[i+iFrom] = pSubSrc->a[i];
96583       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
96584     }
96585     pSrc->a[iFrom].jointype = jointype;
96586   
96587     /* Now begin substituting subquery result set expressions for 
96588     ** references to the iParent in the outer query.
96589     ** 
96590     ** Example:
96591     **
96592     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
96593     **   \                     \_____________ subquery __________/          /
96594     **    \_____________________ outer query ______________________________/
96595     **
96596     ** We look at every expression in the outer query and every place we see
96597     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
96598     */
96599     pList = pParent->pEList;
96600     for(i=0; i<pList->nExpr; i++){
96601       if( pList->a[i].zName==0 ){
96602         const char *zSpan = pList->a[i].zSpan;
96603         if( ALWAYS(zSpan) ){
96604           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
96605         }
96606       }
96607     }
96608     substExprList(db, pParent->pEList, iParent, pSub->pEList);
96609     if( isAgg ){
96610       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
96611       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
96612     }
96613     if( pSub->pOrderBy ){
96614       assert( pParent->pOrderBy==0 );
96615       pParent->pOrderBy = pSub->pOrderBy;
96616       pSub->pOrderBy = 0;
96617     }else if( pParent->pOrderBy ){
96618       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
96619     }
96620     if( pSub->pWhere ){
96621       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
96622     }else{
96623       pWhere = 0;
96624     }
96625     if( subqueryIsAgg ){
96626       assert( pParent->pHaving==0 );
96627       pParent->pHaving = pParent->pWhere;
96628       pParent->pWhere = pWhere;
96629       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
96630       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
96631                                   sqlite3ExprDup(db, pSub->pHaving, 0));
96632       assert( pParent->pGroupBy==0 );
96633       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
96634     }else{
96635       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
96636       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
96637     }
96638   
96639     /* The flattened query is distinct if either the inner or the
96640     ** outer query is distinct. 
96641     */
96642     pParent->selFlags |= pSub->selFlags & SF_Distinct;
96643   
96644     /*
96645     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
96646     **
96647     ** One is tempted to try to add a and b to combine the limits.  But this
96648     ** does not work if either limit is negative.
96649     */
96650     if( pSub->pLimit ){
96651       pParent->pLimit = pSub->pLimit;
96652       pSub->pLimit = 0;
96653     }
96654   }
96655
96656   /* Finially, delete what is left of the subquery and return
96657   ** success.
96658   */
96659   sqlite3SelectDelete(db, pSub1);
96660
96661   return 1;
96662 }
96663 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
96664
96665 /*
96666 ** Analyze the SELECT statement passed as an argument to see if it
96667 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
96668 ** it is, or 0 otherwise. At present, a query is considered to be
96669 ** a min()/max() query if:
96670 **
96671 **   1. There is a single object in the FROM clause.
96672 **
96673 **   2. There is a single expression in the result set, and it is
96674 **      either min(x) or max(x), where x is a column reference.
96675 */
96676 static u8 minMaxQuery(Select *p){
96677   Expr *pExpr;
96678   ExprList *pEList = p->pEList;
96679
96680   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
96681   pExpr = pEList->a[0].pExpr;
96682   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
96683   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
96684   pEList = pExpr->x.pList;
96685   if( pEList==0 || pEList->nExpr!=1 ) return 0;
96686   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
96687   assert( !ExprHasProperty(pExpr, EP_IntValue) );
96688   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
96689     return WHERE_ORDERBY_MIN;
96690   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
96691     return WHERE_ORDERBY_MAX;
96692   }
96693   return WHERE_ORDERBY_NORMAL;
96694 }
96695
96696 /*
96697 ** The select statement passed as the first argument is an aggregate query.
96698 ** The second argment is the associated aggregate-info object. This 
96699 ** function tests if the SELECT is of the form:
96700 **
96701 **   SELECT count(*) FROM <tbl>
96702 **
96703 ** where table is a database table, not a sub-select or view. If the query
96704 ** does match this pattern, then a pointer to the Table object representing
96705 ** <tbl> is returned. Otherwise, 0 is returned.
96706 */
96707 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
96708   Table *pTab;
96709   Expr *pExpr;
96710
96711   assert( !p->pGroupBy );
96712
96713   if( p->pWhere || p->pEList->nExpr!=1 
96714    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
96715   ){
96716     return 0;
96717   }
96718   pTab = p->pSrc->a[0].pTab;
96719   pExpr = p->pEList->a[0].pExpr;
96720   assert( pTab && !pTab->pSelect && pExpr );
96721
96722   if( IsVirtual(pTab) ) return 0;
96723   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
96724   if( NEVER(pAggInfo->nFunc==0) ) return 0;
96725   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
96726   if( pExpr->flags&EP_Distinct ) return 0;
96727
96728   return pTab;
96729 }
96730
96731 /*
96732 ** If the source-list item passed as an argument was augmented with an
96733 ** INDEXED BY clause, then try to locate the specified index. If there
96734 ** was such a clause and the named index cannot be found, return 
96735 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
96736 ** pFrom->pIndex and return SQLITE_OK.
96737 */
96738 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
96739   if( pFrom->pTab && pFrom->zIndex ){
96740     Table *pTab = pFrom->pTab;
96741     char *zIndex = pFrom->zIndex;
96742     Index *pIdx;
96743     for(pIdx=pTab->pIndex; 
96744         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
96745         pIdx=pIdx->pNext
96746     );
96747     if( !pIdx ){
96748       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
96749       pParse->checkSchema = 1;
96750       return SQLITE_ERROR;
96751     }
96752     pFrom->pIndex = pIdx;
96753   }
96754   return SQLITE_OK;
96755 }
96756
96757 /*
96758 ** This routine is a Walker callback for "expanding" a SELECT statement.
96759 ** "Expanding" means to do the following:
96760 **
96761 **    (1)  Make sure VDBE cursor numbers have been assigned to every
96762 **         element of the FROM clause.
96763 **
96764 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
96765 **         defines FROM clause.  When views appear in the FROM clause,
96766 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
96767 **         that implements the view.  A copy is made of the view's SELECT
96768 **         statement so that we can freely modify or delete that statement
96769 **         without worrying about messing up the presistent representation
96770 **         of the view.
96771 **
96772 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
96773 **         on joins and the ON and USING clause of joins.
96774 **
96775 **    (4)  Scan the list of columns in the result set (pEList) looking
96776 **         for instances of the "*" operator or the TABLE.* operator.
96777 **         If found, expand each "*" to be every column in every table
96778 **         and TABLE.* to be every column in TABLE.
96779 **
96780 */
96781 static int selectExpander(Walker *pWalker, Select *p){
96782   Parse *pParse = pWalker->pParse;
96783   int i, j, k;
96784   SrcList *pTabList;
96785   ExprList *pEList;
96786   struct SrcList_item *pFrom;
96787   sqlite3 *db = pParse->db;
96788
96789   if( db->mallocFailed  ){
96790     return WRC_Abort;
96791   }
96792   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
96793     return WRC_Prune;
96794   }
96795   p->selFlags |= SF_Expanded;
96796   pTabList = p->pSrc;
96797   pEList = p->pEList;
96798
96799   /* Make sure cursor numbers have been assigned to all entries in
96800   ** the FROM clause of the SELECT statement.
96801   */
96802   sqlite3SrcListAssignCursors(pParse, pTabList);
96803
96804   /* Look up every table named in the FROM clause of the select.  If
96805   ** an entry of the FROM clause is a subquery instead of a table or view,
96806   ** then create a transient table structure to describe the subquery.
96807   */
96808   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
96809     Table *pTab;
96810     if( pFrom->pTab!=0 ){
96811       /* This statement has already been prepared.  There is no need
96812       ** to go further. */
96813       assert( i==0 );
96814       return WRC_Prune;
96815     }
96816     if( pFrom->zName==0 ){
96817 #ifndef SQLITE_OMIT_SUBQUERY
96818       Select *pSel = pFrom->pSelect;
96819       /* A sub-query in the FROM clause of a SELECT */
96820       assert( pSel!=0 );
96821       assert( pFrom->pTab==0 );
96822       sqlite3WalkSelect(pWalker, pSel);
96823       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
96824       if( pTab==0 ) return WRC_Abort;
96825       pTab->nRef = 1;
96826       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
96827       while( pSel->pPrior ){ pSel = pSel->pPrior; }
96828       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
96829       pTab->iPKey = -1;
96830       pTab->nRowEst = 1000000;
96831       pTab->tabFlags |= TF_Ephemeral;
96832 #endif
96833     }else{
96834       /* An ordinary table or view name in the FROM clause */
96835       assert( pFrom->pTab==0 );
96836       pFrom->pTab = pTab = 
96837         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
96838       if( pTab==0 ) return WRC_Abort;
96839       pTab->nRef++;
96840 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
96841       if( pTab->pSelect || IsVirtual(pTab) ){
96842         /* We reach here if the named table is a really a view */
96843         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
96844         assert( pFrom->pSelect==0 );
96845         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
96846         sqlite3WalkSelect(pWalker, pFrom->pSelect);
96847       }
96848 #endif
96849     }
96850
96851     /* Locate the index named by the INDEXED BY clause, if any. */
96852     if( sqlite3IndexedByLookup(pParse, pFrom) ){
96853       return WRC_Abort;
96854     }
96855   }
96856
96857   /* Process NATURAL keywords, and ON and USING clauses of joins.
96858   */
96859   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
96860     return WRC_Abort;
96861   }
96862
96863   /* For every "*" that occurs in the column list, insert the names of
96864   ** all columns in all tables.  And for every TABLE.* insert the names
96865   ** of all columns in TABLE.  The parser inserted a special expression
96866   ** with the TK_ALL operator for each "*" that it found in the column list.
96867   ** The following code just has to locate the TK_ALL expressions and expand
96868   ** each one to the list of all columns in all tables.
96869   **
96870   ** The first loop just checks to see if there are any "*" operators
96871   ** that need expanding.
96872   */
96873   for(k=0; k<pEList->nExpr; k++){
96874     Expr *pE = pEList->a[k].pExpr;
96875     if( pE->op==TK_ALL ) break;
96876     assert( pE->op!=TK_DOT || pE->pRight!=0 );
96877     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
96878     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
96879   }
96880   if( k<pEList->nExpr ){
96881     /*
96882     ** If we get here it means the result set contains one or more "*"
96883     ** operators that need to be expanded.  Loop through each expression
96884     ** in the result set and expand them one by one.
96885     */
96886     struct ExprList_item *a = pEList->a;
96887     ExprList *pNew = 0;
96888     int flags = pParse->db->flags;
96889     int longNames = (flags & SQLITE_FullColNames)!=0
96890                       && (flags & SQLITE_ShortColNames)==0;
96891
96892     for(k=0; k<pEList->nExpr; k++){
96893       Expr *pE = a[k].pExpr;
96894       assert( pE->op!=TK_DOT || pE->pRight!=0 );
96895       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
96896         /* This particular expression does not need to be expanded.
96897         */
96898         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
96899         if( pNew ){
96900           pNew->a[pNew->nExpr-1].zName = a[k].zName;
96901           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
96902           a[k].zName = 0;
96903           a[k].zSpan = 0;
96904         }
96905         a[k].pExpr = 0;
96906       }else{
96907         /* This expression is a "*" or a "TABLE.*" and needs to be
96908         ** expanded. */
96909         int tableSeen = 0;      /* Set to 1 when TABLE matches */
96910         char *zTName;            /* text of name of TABLE */
96911         if( pE->op==TK_DOT ){
96912           assert( pE->pLeft!=0 );
96913           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
96914           zTName = pE->pLeft->u.zToken;
96915         }else{
96916           zTName = 0;
96917         }
96918         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
96919           Table *pTab = pFrom->pTab;
96920           char *zTabName = pFrom->zAlias;
96921           if( zTabName==0 ){
96922             zTabName = pTab->zName;
96923           }
96924           if( db->mallocFailed ) break;
96925           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
96926             continue;
96927           }
96928           tableSeen = 1;
96929           for(j=0; j<pTab->nCol; j++){
96930             Expr *pExpr, *pRight;
96931             char *zName = pTab->aCol[j].zName;
96932             char *zColname;  /* The computed column name */
96933             char *zToFree;   /* Malloced string that needs to be freed */
96934             Token sColname;  /* Computed column name as a token */
96935
96936             /* If a column is marked as 'hidden' (currently only possible
96937             ** for virtual tables), do not include it in the expanded
96938             ** result-set list.
96939             */
96940             if( IsHiddenColumn(&pTab->aCol[j]) ){
96941               assert(IsVirtual(pTab));
96942               continue;
96943             }
96944
96945             if( i>0 && zTName==0 ){
96946               if( (pFrom->jointype & JT_NATURAL)!=0
96947                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
96948               ){
96949                 /* In a NATURAL join, omit the join columns from the 
96950                 ** table to the right of the join */
96951                 continue;
96952               }
96953               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
96954                 /* In a join with a USING clause, omit columns in the
96955                 ** using clause from the table on the right. */
96956                 continue;
96957               }
96958             }
96959             pRight = sqlite3Expr(db, TK_ID, zName);
96960             zColname = zName;
96961             zToFree = 0;
96962             if( longNames || pTabList->nSrc>1 ){
96963               Expr *pLeft;
96964               pLeft = sqlite3Expr(db, TK_ID, zTabName);
96965               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
96966               if( longNames ){
96967                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
96968                 zToFree = zColname;
96969               }
96970             }else{
96971               pExpr = pRight;
96972             }
96973             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
96974             sColname.z = zColname;
96975             sColname.n = sqlite3Strlen30(zColname);
96976             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
96977             sqlite3DbFree(db, zToFree);
96978           }
96979         }
96980         if( !tableSeen ){
96981           if( zTName ){
96982             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
96983           }else{
96984             sqlite3ErrorMsg(pParse, "no tables specified");
96985           }
96986         }
96987       }
96988     }
96989     sqlite3ExprListDelete(db, pEList);
96990     p->pEList = pNew;
96991   }
96992 #if SQLITE_MAX_COLUMN
96993   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
96994     sqlite3ErrorMsg(pParse, "too many columns in result set");
96995   }
96996 #endif
96997   return WRC_Continue;
96998 }
96999
97000 /*
97001 ** No-op routine for the parse-tree walker.
97002 **
97003 ** When this routine is the Walker.xExprCallback then expression trees
97004 ** are walked without any actions being taken at each node.  Presumably,
97005 ** when this routine is used for Walker.xExprCallback then 
97006 ** Walker.xSelectCallback is set to do something useful for every 
97007 ** subquery in the parser tree.
97008 */
97009 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97010   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97011   return WRC_Continue;
97012 }
97013
97014 /*
97015 ** This routine "expands" a SELECT statement and all of its subqueries.
97016 ** For additional information on what it means to "expand" a SELECT
97017 ** statement, see the comment on the selectExpand worker callback above.
97018 **
97019 ** Expanding a SELECT statement is the first step in processing a
97020 ** SELECT statement.  The SELECT statement must be expanded before
97021 ** name resolution is performed.
97022 **
97023 ** If anything goes wrong, an error message is written into pParse.
97024 ** The calling function can detect the problem by looking at pParse->nErr
97025 ** and/or pParse->db->mallocFailed.
97026 */
97027 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
97028   Walker w;
97029   w.xSelectCallback = selectExpander;
97030   w.xExprCallback = exprWalkNoop;
97031   w.pParse = pParse;
97032   sqlite3WalkSelect(&w, pSelect);
97033 }
97034
97035
97036 #ifndef SQLITE_OMIT_SUBQUERY
97037 /*
97038 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
97039 ** interface.
97040 **
97041 ** For each FROM-clause subquery, add Column.zType and Column.zColl
97042 ** information to the Table structure that represents the result set
97043 ** of that subquery.
97044 **
97045 ** The Table structure that represents the result set was constructed
97046 ** by selectExpander() but the type and collation information was omitted
97047 ** at that point because identifiers had not yet been resolved.  This
97048 ** routine is called after identifier resolution.
97049 */
97050 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97051   Parse *pParse;
97052   int i;
97053   SrcList *pTabList;
97054   struct SrcList_item *pFrom;
97055
97056   assert( p->selFlags & SF_Resolved );
97057   if( (p->selFlags & SF_HasTypeInfo)==0 ){
97058     p->selFlags |= SF_HasTypeInfo;
97059     pParse = pWalker->pParse;
97060     pTabList = p->pSrc;
97061     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97062       Table *pTab = pFrom->pTab;
97063       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97064         /* A sub-query in the FROM clause of a SELECT */
97065         Select *pSel = pFrom->pSelect;
97066         assert( pSel );
97067         while( pSel->pPrior ) pSel = pSel->pPrior;
97068         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
97069       }
97070     }
97071   }
97072   return WRC_Continue;
97073 }
97074 #endif
97075
97076
97077 /*
97078 ** This routine adds datatype and collating sequence information to
97079 ** the Table structures of all FROM-clause subqueries in a
97080 ** SELECT statement.
97081 **
97082 ** Use this routine after name resolution.
97083 */
97084 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
97085 #ifndef SQLITE_OMIT_SUBQUERY
97086   Walker w;
97087   w.xSelectCallback = selectAddSubqueryTypeInfo;
97088   w.xExprCallback = exprWalkNoop;
97089   w.pParse = pParse;
97090   sqlite3WalkSelect(&w, pSelect);
97091 #endif
97092 }
97093
97094
97095 /*
97096 ** This routine sets up a SELECT statement for processing.  The
97097 ** following is accomplished:
97098 **
97099 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
97100 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
97101 **     *  ON and USING clauses are shifted into WHERE statements
97102 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
97103 **     *  Identifiers in expression are matched to tables.
97104 **
97105 ** This routine acts recursively on all subqueries within the SELECT.
97106 */
97107 SQLITE_PRIVATE void sqlite3SelectPrep(
97108   Parse *pParse,         /* The parser context */
97109   Select *p,             /* The SELECT statement being coded. */
97110   NameContext *pOuterNC  /* Name context for container */
97111 ){
97112   sqlite3 *db;
97113   if( NEVER(p==0) ) return;
97114   db = pParse->db;
97115   if( p->selFlags & SF_HasTypeInfo ) return;
97116   sqlite3SelectExpand(pParse, p);
97117   if( pParse->nErr || db->mallocFailed ) return;
97118   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
97119   if( pParse->nErr || db->mallocFailed ) return;
97120   sqlite3SelectAddTypeInfo(pParse, p);
97121 }
97122
97123 /*
97124 ** Reset the aggregate accumulator.
97125 **
97126 ** The aggregate accumulator is a set of memory cells that hold
97127 ** intermediate results while calculating an aggregate.  This
97128 ** routine generates code that stores NULLs in all of those memory
97129 ** cells.
97130 */
97131 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
97132   Vdbe *v = pParse->pVdbe;
97133   int i;
97134   struct AggInfo_func *pFunc;
97135   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
97136     return;
97137   }
97138   for(i=0; i<pAggInfo->nColumn; i++){
97139     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
97140   }
97141   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
97142     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
97143     if( pFunc->iDistinct>=0 ){
97144       Expr *pE = pFunc->pExpr;
97145       assert( !ExprHasProperty(pE, EP_xIsSelect) );
97146       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
97147         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
97148            "argument");
97149         pFunc->iDistinct = -1;
97150       }else{
97151         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
97152         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
97153                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97154       }
97155     }
97156   }
97157 }
97158
97159 /*
97160 ** Invoke the OP_AggFinalize opcode for every aggregate function
97161 ** in the AggInfo structure.
97162 */
97163 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
97164   Vdbe *v = pParse->pVdbe;
97165   int i;
97166   struct AggInfo_func *pF;
97167   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97168     ExprList *pList = pF->pExpr->x.pList;
97169     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97170     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
97171                       (void*)pF->pFunc, P4_FUNCDEF);
97172   }
97173 }
97174
97175 /*
97176 ** Update the accumulator memory cells for an aggregate based on
97177 ** the current cursor position.
97178 */
97179 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
97180   Vdbe *v = pParse->pVdbe;
97181   int i;
97182   int regHit = 0;
97183   int addrHitTest = 0;
97184   struct AggInfo_func *pF;
97185   struct AggInfo_col *pC;
97186
97187   pAggInfo->directMode = 1;
97188   sqlite3ExprCacheClear(pParse);
97189   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97190     int nArg;
97191     int addrNext = 0;
97192     int regAgg;
97193     ExprList *pList = pF->pExpr->x.pList;
97194     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97195     if( pList ){
97196       nArg = pList->nExpr;
97197       regAgg = sqlite3GetTempRange(pParse, nArg);
97198       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
97199     }else{
97200       nArg = 0;
97201       regAgg = 0;
97202     }
97203     if( pF->iDistinct>=0 ){
97204       addrNext = sqlite3VdbeMakeLabel(v);
97205       assert( nArg==1 );
97206       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
97207     }
97208     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
97209       CollSeq *pColl = 0;
97210       struct ExprList_item *pItem;
97211       int j;
97212       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
97213       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
97214         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
97215       }
97216       if( !pColl ){
97217         pColl = pParse->db->pDfltColl;
97218       }
97219       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
97220       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
97221     }
97222     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
97223                       (void*)pF->pFunc, P4_FUNCDEF);
97224     sqlite3VdbeChangeP5(v, (u8)nArg);
97225     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
97226     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
97227     if( addrNext ){
97228       sqlite3VdbeResolveLabel(v, addrNext);
97229       sqlite3ExprCacheClear(pParse);
97230     }
97231   }
97232
97233   /* Before populating the accumulator registers, clear the column cache.
97234   ** Otherwise, if any of the required column values are already present 
97235   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
97236   ** to pC->iMem. But by the time the value is used, the original register
97237   ** may have been used, invalidating the underlying buffer holding the
97238   ** text or blob value. See ticket [883034dcb5].
97239   **
97240   ** Another solution would be to change the OP_SCopy used to copy cached
97241   ** values to an OP_Copy.
97242   */
97243   if( regHit ){
97244     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
97245   }
97246   sqlite3ExprCacheClear(pParse);
97247   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
97248     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
97249   }
97250   pAggInfo->directMode = 0;
97251   sqlite3ExprCacheClear(pParse);
97252   if( addrHitTest ){
97253     sqlite3VdbeJumpHere(v, addrHitTest);
97254   }
97255 }
97256
97257 /*
97258 ** Add a single OP_Explain instruction to the VDBE to explain a simple
97259 ** count(*) query ("SELECT count(*) FROM pTab").
97260 */
97261 #ifndef SQLITE_OMIT_EXPLAIN
97262 static void explainSimpleCount(
97263   Parse *pParse,                  /* Parse context */
97264   Table *pTab,                    /* Table being queried */
97265   Index *pIdx                     /* Index used to optimize scan, or NULL */
97266 ){
97267   if( pParse->explain==2 ){
97268     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
97269         pTab->zName, 
97270         pIdx ? "USING COVERING INDEX " : "",
97271         pIdx ? pIdx->zName : "",
97272         pTab->nRowEst
97273     );
97274     sqlite3VdbeAddOp4(
97275         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
97276     );
97277   }
97278 }
97279 #else
97280 # define explainSimpleCount(a,b,c)
97281 #endif
97282
97283 /*
97284 ** Generate code for the SELECT statement given in the p argument.  
97285 **
97286 ** The results are distributed in various ways depending on the
97287 ** contents of the SelectDest structure pointed to by argument pDest
97288 ** as follows:
97289 **
97290 **     pDest->eDest    Result
97291 **     ------------    -------------------------------------------
97292 **     SRT_Output      Generate a row of output (using the OP_ResultRow
97293 **                     opcode) for each row in the result set.
97294 **
97295 **     SRT_Mem         Only valid if the result is a single column.
97296 **                     Store the first column of the first result row
97297 **                     in register pDest->iSDParm then abandon the rest
97298 **                     of the query.  This destination implies "LIMIT 1".
97299 **
97300 **     SRT_Set         The result must be a single column.  Store each
97301 **                     row of result as the key in table pDest->iSDParm. 
97302 **                     Apply the affinity pDest->affSdst before storing
97303 **                     results.  Used to implement "IN (SELECT ...)".
97304 **
97305 **     SRT_Union       Store results as a key in a temporary table 
97306 **                     identified by pDest->iSDParm.
97307 **
97308 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
97309 **
97310 **     SRT_Table       Store results in temporary table pDest->iSDParm.
97311 **                     This is like SRT_EphemTab except that the table
97312 **                     is assumed to already be open.
97313 **
97314 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
97315 **                     the result there. The cursor is left open after
97316 **                     returning.  This is like SRT_Table except that
97317 **                     this destination uses OP_OpenEphemeral to create
97318 **                     the table first.
97319 **
97320 **     SRT_Coroutine   Generate a co-routine that returns a new row of
97321 **                     results each time it is invoked.  The entry point
97322 **                     of the co-routine is stored in register pDest->iSDParm.
97323 **
97324 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
97325 **                     set is not empty.
97326 **
97327 **     SRT_Discard     Throw the results away.  This is used by SELECT
97328 **                     statements within triggers whose only purpose is
97329 **                     the side-effects of functions.
97330 **
97331 ** This routine returns the number of errors.  If any errors are
97332 ** encountered, then an appropriate error message is left in
97333 ** pParse->zErrMsg.
97334 **
97335 ** This routine does NOT free the Select structure passed in.  The
97336 ** calling function needs to do that.
97337 */
97338 SQLITE_PRIVATE int sqlite3Select(
97339   Parse *pParse,         /* The parser context */
97340   Select *p,             /* The SELECT statement being coded. */
97341   SelectDest *pDest      /* What to do with the query results */
97342 ){
97343   int i, j;              /* Loop counters */
97344   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
97345   Vdbe *v;               /* The virtual machine under construction */
97346   int isAgg;             /* True for select lists like "count(*)" */
97347   ExprList *pEList;      /* List of columns to extract. */
97348   SrcList *pTabList;     /* List of tables to select from */
97349   Expr *pWhere;          /* The WHERE clause.  May be NULL */
97350   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
97351   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
97352   Expr *pHaving;         /* The HAVING clause.  May be NULL */
97353   int isDistinct;        /* True if the DISTINCT keyword is present */
97354   int distinct;          /* Table to use for the distinct set */
97355   int rc = 1;            /* Value to return from this function */
97356   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
97357   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
97358   AggInfo sAggInfo;      /* Information used by aggregate queries */
97359   int iEnd;              /* Address of the end of the query */
97360   sqlite3 *db;           /* The database connection */
97361
97362 #ifndef SQLITE_OMIT_EXPLAIN
97363   int iRestoreSelectId = pParse->iSelectId;
97364   pParse->iSelectId = pParse->iNextSelectId++;
97365 #endif
97366
97367   db = pParse->db;
97368   if( p==0 || db->mallocFailed || pParse->nErr ){
97369     return 1;
97370   }
97371   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
97372   memset(&sAggInfo, 0, sizeof(sAggInfo));
97373
97374   if( IgnorableOrderby(pDest) ){
97375     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
97376            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
97377     /* If ORDER BY makes no difference in the output then neither does
97378     ** DISTINCT so it can be removed too. */
97379     sqlite3ExprListDelete(db, p->pOrderBy);
97380     p->pOrderBy = 0;
97381     p->selFlags &= ~SF_Distinct;
97382   }
97383   sqlite3SelectPrep(pParse, p, 0);
97384   pOrderBy = p->pOrderBy;
97385   pTabList = p->pSrc;
97386   pEList = p->pEList;
97387   if( pParse->nErr || db->mallocFailed ){
97388     goto select_end;
97389   }
97390   isAgg = (p->selFlags & SF_Aggregate)!=0;
97391   assert( pEList!=0 );
97392
97393   /* Begin generating code.
97394   */
97395   v = sqlite3GetVdbe(pParse);
97396   if( v==0 ) goto select_end;
97397
97398   /* If writing to memory or generating a set
97399   ** only a single column may be output.
97400   */
97401 #ifndef SQLITE_OMIT_SUBQUERY
97402   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
97403     goto select_end;
97404   }
97405 #endif
97406
97407   /* Generate code for all sub-queries in the FROM clause
97408   */
97409 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97410   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
97411     struct SrcList_item *pItem = &pTabList->a[i];
97412     SelectDest dest;
97413     Select *pSub = pItem->pSelect;
97414     int isAggSub;
97415
97416     if( pSub==0 ) continue;
97417     if( pItem->addrFillSub ){
97418       sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
97419       continue;
97420     }
97421
97422     /* Increment Parse.nHeight by the height of the largest expression
97423     ** tree refered to by this, the parent select. The child select
97424     ** may contain expression trees of at most
97425     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
97426     ** more conservative than necessary, but much easier than enforcing
97427     ** an exact limit.
97428     */
97429     pParse->nHeight += sqlite3SelectExprHeight(p);
97430
97431     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
97432     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
97433       /* This subquery can be absorbed into its parent. */
97434       if( isAggSub ){
97435         isAgg = 1;
97436         p->selFlags |= SF_Aggregate;
97437       }
97438       i = -1;
97439     }else{
97440       /* Generate a subroutine that will fill an ephemeral table with
97441       ** the content of this subquery.  pItem->addrFillSub will point
97442       ** to the address of the generated subroutine.  pItem->regReturn
97443       ** is a register allocated to hold the subroutine return address
97444       */
97445       int topAddr;
97446       int onceAddr = 0;
97447       int retAddr;
97448       assert( pItem->addrFillSub==0 );
97449       pItem->regReturn = ++pParse->nMem;
97450       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
97451       pItem->addrFillSub = topAddr+1;
97452       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
97453       if( pItem->isCorrelated==0 ){
97454         /* If the subquery is no correlated and if we are not inside of
97455         ** a trigger, then we only need to compute the value of the subquery
97456         ** once. */
97457         onceAddr = sqlite3CodeOnce(pParse);
97458       }
97459       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
97460       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
97461       sqlite3Select(pParse, pSub, &dest);
97462       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
97463       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
97464       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
97465       VdbeComment((v, "end %s", pItem->pTab->zName));
97466       sqlite3VdbeChangeP1(v, topAddr, retAddr);
97467       sqlite3ClearTempRegCache(pParse);
97468     }
97469     if( /*pParse->nErr ||*/ db->mallocFailed ){
97470       goto select_end;
97471     }
97472     pParse->nHeight -= sqlite3SelectExprHeight(p);
97473     pTabList = p->pSrc;
97474     if( !IgnorableOrderby(pDest) ){
97475       pOrderBy = p->pOrderBy;
97476     }
97477   }
97478   pEList = p->pEList;
97479 #endif
97480   pWhere = p->pWhere;
97481   pGroupBy = p->pGroupBy;
97482   pHaving = p->pHaving;
97483   isDistinct = (p->selFlags & SF_Distinct)!=0;
97484
97485 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97486   /* If there is are a sequence of queries, do the earlier ones first.
97487   */
97488   if( p->pPrior ){
97489     if( p->pRightmost==0 ){
97490       Select *pLoop, *pRight = 0;
97491       int cnt = 0;
97492       int mxSelect;
97493       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
97494         pLoop->pRightmost = p;
97495         pLoop->pNext = pRight;
97496         pRight = pLoop;
97497       }
97498       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
97499       if( mxSelect && cnt>mxSelect ){
97500         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
97501         goto select_end;
97502       }
97503     }
97504     rc = multiSelect(pParse, p, pDest);
97505     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
97506     return rc;
97507   }
97508 #endif
97509
97510   /* If there is both a GROUP BY and an ORDER BY clause and they are
97511   ** identical, then disable the ORDER BY clause since the GROUP BY
97512   ** will cause elements to come out in the correct order.  This is
97513   ** an optimization - the correct answer should result regardless.
97514   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
97515   ** to disable this optimization for testing purposes.
97516   */
97517   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
97518          && (db->flags & SQLITE_GroupByOrder)==0 ){
97519     pOrderBy = 0;
97520   }
97521
97522   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
97523   ** if the select-list is the same as the ORDER BY list, then this query
97524   ** can be rewritten as a GROUP BY. In other words, this:
97525   **
97526   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
97527   **
97528   ** is transformed to:
97529   **
97530   **     SELECT xyz FROM ... GROUP BY xyz
97531   **
97532   ** The second form is preferred as a single index (or temp-table) may be 
97533   ** used for both the ORDER BY and DISTINCT processing. As originally 
97534   ** written the query must use a temp-table for at least one of the ORDER 
97535   ** BY and DISTINCT, and an index or separate temp-table for the other.
97536   */
97537   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
97538    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
97539   ){
97540     p->selFlags &= ~SF_Distinct;
97541     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
97542     pGroupBy = p->pGroupBy;
97543     pOrderBy = 0;
97544   }
97545
97546   /* If there is an ORDER BY clause, then this sorting
97547   ** index might end up being unused if the data can be 
97548   ** extracted in pre-sorted order.  If that is the case, then the
97549   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
97550   ** we figure out that the sorting index is not needed.  The addrSortIndex
97551   ** variable is used to facilitate that change.
97552   */
97553   if( pOrderBy ){
97554     KeyInfo *pKeyInfo;
97555     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
97556     pOrderBy->iECursor = pParse->nTab++;
97557     p->addrOpenEphm[2] = addrSortIndex =
97558       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
97559                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
97560                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97561   }else{
97562     addrSortIndex = -1;
97563   }
97564
97565   /* If the output is destined for a temporary table, open that table.
97566   */
97567   if( pDest->eDest==SRT_EphemTab ){
97568     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
97569   }
97570
97571   /* Set the limiter.
97572   */
97573   iEnd = sqlite3VdbeMakeLabel(v);
97574   p->nSelectRow = (double)LARGEST_INT64;
97575   computeLimitRegisters(pParse, p, iEnd);
97576   if( p->iLimit==0 && addrSortIndex>=0 ){
97577     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
97578     p->selFlags |= SF_UseSorter;
97579   }
97580
97581   /* Open a virtual index to use for the distinct set.
97582   */
97583   if( p->selFlags & SF_Distinct ){
97584     KeyInfo *pKeyInfo;
97585     distinct = pParse->nTab++;
97586     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
97587     addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
97588         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97589     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
97590   }else{
97591     distinct = addrDistinctIndex = -1;
97592   }
97593
97594   /* Aggregate and non-aggregate queries are handled differently */
97595   if( !isAgg && pGroupBy==0 ){
97596     ExprList *pDist = (isDistinct ? p->pEList : 0);
97597
97598     /* Begin the database scan. */
97599     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0,0);
97600     if( pWInfo==0 ) goto select_end;
97601     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
97602
97603     /* If sorting index that was created by a prior OP_OpenEphemeral 
97604     ** instruction ended up not being needed, then change the OP_OpenEphemeral
97605     ** into an OP_Noop.
97606     */
97607     if( addrSortIndex>=0 && pOrderBy==0 ){
97608       sqlite3VdbeChangeToNoop(v, addrSortIndex);
97609       p->addrOpenEphm[2] = -1;
97610     }
97611
97612     if( pWInfo->eDistinct ){
97613       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
97614      
97615       assert( addrDistinctIndex>=0 );
97616       pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
97617
97618       assert( isDistinct );
97619       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 
97620            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 
97621       );
97622       distinct = -1;
97623       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
97624         int iJump;
97625         int iExpr;
97626         int iFlag = ++pParse->nMem;
97627         int iBase = pParse->nMem+1;
97628         int iBase2 = iBase + pEList->nExpr;
97629         pParse->nMem += (pEList->nExpr*2);
97630
97631         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
97632         ** OP_Integer initializes the "first row" flag.  */
97633         pOp->opcode = OP_Integer;
97634         pOp->p1 = 1;
97635         pOp->p2 = iFlag;
97636
97637         sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
97638         iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
97639         sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
97640         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
97641           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
97642           sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
97643           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
97644           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
97645         }
97646         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
97647
97648         sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
97649         assert( sqlite3VdbeCurrentAddr(v)==iJump );
97650         sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
97651       }else{
97652         pOp->opcode = OP_Noop;
97653       }
97654     }
97655
97656     /* Use the standard inner loop. */
97657     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
97658                     pWInfo->iContinue, pWInfo->iBreak);
97659
97660     /* End the database scan loop.
97661     */
97662     sqlite3WhereEnd(pWInfo);
97663   }else{
97664     /* This is the processing for aggregate queries */
97665     NameContext sNC;    /* Name context for processing aggregate information */
97666     int iAMem;          /* First Mem address for storing current GROUP BY */
97667     int iBMem;          /* First Mem address for previous GROUP BY */
97668     int iUseFlag;       /* Mem address holding flag indicating that at least
97669                         ** one row of the input to the aggregator has been
97670                         ** processed */
97671     int iAbortFlag;     /* Mem address which causes query abort if positive */
97672     int groupBySort;    /* Rows come from source in GROUP BY order */
97673     int addrEnd;        /* End of processing for this SELECT */
97674     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
97675     int sortOut = 0;    /* Output register from the sorter */
97676
97677     /* Remove any and all aliases between the result set and the
97678     ** GROUP BY clause.
97679     */
97680     if( pGroupBy ){
97681       int k;                        /* Loop counter */
97682       struct ExprList_item *pItem;  /* For looping over expression in a list */
97683
97684       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
97685         pItem->iAlias = 0;
97686       }
97687       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
97688         pItem->iAlias = 0;
97689       }
97690       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
97691     }else{
97692       p->nSelectRow = (double)1;
97693     }
97694
97695  
97696     /* Create a label to jump to when we want to abort the query */
97697     addrEnd = sqlite3VdbeMakeLabel(v);
97698
97699     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
97700     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
97701     ** SELECT statement.
97702     */
97703     memset(&sNC, 0, sizeof(sNC));
97704     sNC.pParse = pParse;
97705     sNC.pSrcList = pTabList;
97706     sNC.pAggInfo = &sAggInfo;
97707     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
97708     sAggInfo.pGroupBy = pGroupBy;
97709     sqlite3ExprAnalyzeAggList(&sNC, pEList);
97710     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
97711     if( pHaving ){
97712       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
97713     }
97714     sAggInfo.nAccumulator = sAggInfo.nColumn;
97715     for(i=0; i<sAggInfo.nFunc; i++){
97716       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
97717       sNC.ncFlags |= NC_InAggFunc;
97718       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
97719       sNC.ncFlags &= ~NC_InAggFunc;
97720     }
97721     if( db->mallocFailed ) goto select_end;
97722
97723     /* Processing for aggregates with GROUP BY is very different and
97724     ** much more complex than aggregates without a GROUP BY.
97725     */
97726     if( pGroupBy ){
97727       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
97728       int j1;             /* A-vs-B comparision jump */
97729       int addrOutputRow;  /* Start of subroutine that outputs a result row */
97730       int regOutputRow;   /* Return address register for output subroutine */
97731       int addrSetAbort;   /* Set the abort flag and return */
97732       int addrTopOfLoop;  /* Top of the input loop */
97733       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
97734       int addrReset;      /* Subroutine for resetting the accumulator */
97735       int regReset;       /* Return address register for reset subroutine */
97736
97737       /* If there is a GROUP BY clause we might need a sorting index to
97738       ** implement it.  Allocate that sorting index now.  If it turns out
97739       ** that we do not need it after all, the OP_SorterOpen instruction
97740       ** will be converted into a Noop.  
97741       */
97742       sAggInfo.sortingIdx = pParse->nTab++;
97743       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
97744       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
97745           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
97746           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97747
97748       /* Initialize memory locations used by GROUP BY aggregate processing
97749       */
97750       iUseFlag = ++pParse->nMem;
97751       iAbortFlag = ++pParse->nMem;
97752       regOutputRow = ++pParse->nMem;
97753       addrOutputRow = sqlite3VdbeMakeLabel(v);
97754       regReset = ++pParse->nMem;
97755       addrReset = sqlite3VdbeMakeLabel(v);
97756       iAMem = pParse->nMem + 1;
97757       pParse->nMem += pGroupBy->nExpr;
97758       iBMem = pParse->nMem + 1;
97759       pParse->nMem += pGroupBy->nExpr;
97760       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
97761       VdbeComment((v, "clear abort flag"));
97762       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
97763       VdbeComment((v, "indicate accumulator empty"));
97764       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
97765
97766       /* Begin a loop that will extract all source rows in GROUP BY order.
97767       ** This might involve two separate loops with an OP_Sort in between, or
97768       ** it might be a single loop that uses an index to extract information
97769       ** in the right order to begin with.
97770       */
97771       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
97772       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0, 0);
97773       if( pWInfo==0 ) goto select_end;
97774       if( pGroupBy==0 ){
97775         /* The optimizer is able to deliver rows in group by order so
97776         ** we do not have to sort.  The OP_OpenEphemeral table will be
97777         ** cancelled later because we still need to use the pKeyInfo
97778         */
97779         pGroupBy = p->pGroupBy;
97780         groupBySort = 0;
97781       }else{
97782         /* Rows are coming out in undetermined order.  We have to push
97783         ** each row into a sorting index, terminate the first loop,
97784         ** then loop over the sorting index in order to get the output
97785         ** in sorted order
97786         */
97787         int regBase;
97788         int regRecord;
97789         int nCol;
97790         int nGroupBy;
97791
97792         explainTempTable(pParse, 
97793             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
97794
97795         groupBySort = 1;
97796         nGroupBy = pGroupBy->nExpr;
97797         nCol = nGroupBy + 1;
97798         j = nGroupBy+1;
97799         for(i=0; i<sAggInfo.nColumn; i++){
97800           if( sAggInfo.aCol[i].iSorterColumn>=j ){
97801             nCol++;
97802             j++;
97803           }
97804         }
97805         regBase = sqlite3GetTempRange(pParse, nCol);
97806         sqlite3ExprCacheClear(pParse);
97807         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
97808         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
97809         j = nGroupBy+1;
97810         for(i=0; i<sAggInfo.nColumn; i++){
97811           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
97812           if( pCol->iSorterColumn>=j ){
97813             int r1 = j + regBase;
97814             int r2;
97815
97816             r2 = sqlite3ExprCodeGetColumn(pParse, 
97817                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
97818             if( r1!=r2 ){
97819               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
97820             }
97821             j++;
97822           }
97823         }
97824         regRecord = sqlite3GetTempReg(pParse);
97825         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
97826         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
97827         sqlite3ReleaseTempReg(pParse, regRecord);
97828         sqlite3ReleaseTempRange(pParse, regBase, nCol);
97829         sqlite3WhereEnd(pWInfo);
97830         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
97831         sortOut = sqlite3GetTempReg(pParse);
97832         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
97833         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
97834         VdbeComment((v, "GROUP BY sort"));
97835         sAggInfo.useSortingIdx = 1;
97836         sqlite3ExprCacheClear(pParse);
97837       }
97838
97839       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
97840       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
97841       ** Then compare the current GROUP BY terms against the GROUP BY terms
97842       ** from the previous row currently stored in a0, a1, a2...
97843       */
97844       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
97845       sqlite3ExprCacheClear(pParse);
97846       if( groupBySort ){
97847         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
97848       }
97849       for(j=0; j<pGroupBy->nExpr; j++){
97850         if( groupBySort ){
97851           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
97852           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97853         }else{
97854           sAggInfo.directMode = 1;
97855           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
97856         }
97857       }
97858       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
97859                           (char*)pKeyInfo, P4_KEYINFO);
97860       j1 = sqlite3VdbeCurrentAddr(v);
97861       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
97862
97863       /* Generate code that runs whenever the GROUP BY changes.
97864       ** Changes in the GROUP BY are detected by the previous code
97865       ** block.  If there were no changes, this block is skipped.
97866       **
97867       ** This code copies current group by terms in b0,b1,b2,...
97868       ** over to a0,a1,a2.  It then calls the output subroutine
97869       ** and resets the aggregate accumulator registers in preparation
97870       ** for the next GROUP BY batch.
97871       */
97872       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
97873       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
97874       VdbeComment((v, "output one row"));
97875       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
97876       VdbeComment((v, "check abort flag"));
97877       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
97878       VdbeComment((v, "reset accumulator"));
97879
97880       /* Update the aggregate accumulators based on the content of
97881       ** the current row
97882       */
97883       sqlite3VdbeJumpHere(v, j1);
97884       updateAccumulator(pParse, &sAggInfo);
97885       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
97886       VdbeComment((v, "indicate data in accumulator"));
97887
97888       /* End of the loop
97889       */
97890       if( groupBySort ){
97891         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
97892       }else{
97893         sqlite3WhereEnd(pWInfo);
97894         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
97895       }
97896
97897       /* Output the final row of result
97898       */
97899       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
97900       VdbeComment((v, "output final row"));
97901
97902       /* Jump over the subroutines
97903       */
97904       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
97905
97906       /* Generate a subroutine that outputs a single row of the result
97907       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
97908       ** is less than or equal to zero, the subroutine is a no-op.  If
97909       ** the processing calls for the query to abort, this subroutine
97910       ** increments the iAbortFlag memory location before returning in
97911       ** order to signal the caller to abort.
97912       */
97913       addrSetAbort = sqlite3VdbeCurrentAddr(v);
97914       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
97915       VdbeComment((v, "set abort flag"));
97916       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97917       sqlite3VdbeResolveLabel(v, addrOutputRow);
97918       addrOutputRow = sqlite3VdbeCurrentAddr(v);
97919       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
97920       VdbeComment((v, "Groupby result generator entry point"));
97921       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97922       finalizeAggFunctions(pParse, &sAggInfo);
97923       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
97924       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
97925                       distinct, pDest,
97926                       addrOutputRow+1, addrSetAbort);
97927       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97928       VdbeComment((v, "end groupby result generator"));
97929
97930       /* Generate a subroutine that will reset the group-by accumulator
97931       */
97932       sqlite3VdbeResolveLabel(v, addrReset);
97933       resetAccumulator(pParse, &sAggInfo);
97934       sqlite3VdbeAddOp1(v, OP_Return, regReset);
97935      
97936     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
97937     else {
97938       ExprList *pDel = 0;
97939 #ifndef SQLITE_OMIT_BTREECOUNT
97940       Table *pTab;
97941       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
97942         /* If isSimpleCount() returns a pointer to a Table structure, then
97943         ** the SQL statement is of the form:
97944         **
97945         **   SELECT count(*) FROM <tbl>
97946         **
97947         ** where the Table structure returned represents table <tbl>.
97948         **
97949         ** This statement is so common that it is optimized specially. The
97950         ** OP_Count instruction is executed either on the intkey table that
97951         ** contains the data for table <tbl> or on one of its indexes. It
97952         ** is better to execute the op on an index, as indexes are almost
97953         ** always spread across less pages than their corresponding tables.
97954         */
97955         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97956         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
97957         Index *pIdx;                         /* Iterator variable */
97958         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
97959         Index *pBest = 0;                    /* Best index found so far */
97960         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
97961
97962         sqlite3CodeVerifySchema(pParse, iDb);
97963         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97964
97965         /* Search for the index that has the least amount of columns. If
97966         ** there is such an index, and it has less columns than the table
97967         ** does, then we can assume that it consumes less space on disk and
97968         ** will therefore be cheaper to scan to determine the query result.
97969         ** In this case set iRoot to the root page number of the index b-tree
97970         ** and pKeyInfo to the KeyInfo structure required to navigate the
97971         ** index.
97972         **
97973         ** (2011-04-15) Do not do a full scan of an unordered index.
97974         **
97975         ** In practice the KeyInfo structure will not be used. It is only 
97976         ** passed to keep OP_OpenRead happy.
97977         */
97978         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
97979           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
97980             pBest = pIdx;
97981           }
97982         }
97983         if( pBest && pBest->nColumn<pTab->nCol ){
97984           iRoot = pBest->tnum;
97985           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
97986         }
97987
97988         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
97989         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
97990         if( pKeyInfo ){
97991           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
97992         }
97993         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
97994         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
97995         explainSimpleCount(pParse, pTab, pBest);
97996       }else
97997 #endif /* SQLITE_OMIT_BTREECOUNT */
97998       {
97999         /* Check if the query is of one of the following forms:
98000         **
98001         **   SELECT min(x) FROM ...
98002         **   SELECT max(x) FROM ...
98003         **
98004         ** If it is, then ask the code in where.c to attempt to sort results
98005         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
98006         ** If where.c is able to produce results sorted in this order, then
98007         ** add vdbe code to break out of the processing loop after the 
98008         ** first iteration (since the first iteration of the loop is 
98009         ** guaranteed to operate on the row with the minimum or maximum 
98010         ** value of x, the only row required).
98011         **
98012         ** A special flag must be passed to sqlite3WhereBegin() to slightly
98013         ** modify behaviour as follows:
98014         **
98015         **   + If the query is a "SELECT min(x)", then the loop coded by
98016         **     where.c should not iterate over any values with a NULL value
98017         **     for x.
98018         **
98019         **   + The optimizer code in where.c (the thing that decides which
98020         **     index or indices to use) should place a different priority on 
98021         **     satisfying the 'ORDER BY' clause than it does in other cases.
98022         **     Refer to code and comments in where.c for details.
98023         */
98024         ExprList *pMinMax = 0;
98025         u8 flag = minMaxQuery(p);
98026         if( flag ){
98027           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98028           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98029           pDel = pMinMax;
98030           if( pMinMax && !db->mallocFailed ){
98031             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98032             pMinMax->a[0].pExpr->op = TK_COLUMN;
98033           }
98034         }
98035   
98036         /* This case runs if the aggregate has no GROUP BY clause.  The
98037         ** processing is much simpler since there is only a single row
98038         ** of output.
98039         */
98040         resetAccumulator(pParse, &sAggInfo);
98041         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax,0,flag,0);
98042         if( pWInfo==0 ){
98043           sqlite3ExprListDelete(db, pDel);
98044           goto select_end;
98045         }
98046         updateAccumulator(pParse, &sAggInfo);
98047         if( !pMinMax && flag ){
98048           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98049           VdbeComment((v, "%s() by index",
98050                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
98051         }
98052         sqlite3WhereEnd(pWInfo);
98053         finalizeAggFunctions(pParse, &sAggInfo);
98054       }
98055
98056       pOrderBy = 0;
98057       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
98058       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
98059                       pDest, addrEnd, addrEnd);
98060       sqlite3ExprListDelete(db, pDel);
98061     }
98062     sqlite3VdbeResolveLabel(v, addrEnd);
98063     
98064   } /* endif aggregate query */
98065
98066   if( distinct>=0 ){
98067     explainTempTable(pParse, "DISTINCT");
98068   }
98069
98070   /* If there is an ORDER BY clause, then we need to sort the results
98071   ** and send them to the callback one by one.
98072   */
98073   if( pOrderBy ){
98074     explainTempTable(pParse, "ORDER BY");
98075     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
98076   }
98077
98078   /* Jump here to skip this query
98079   */
98080   sqlite3VdbeResolveLabel(v, iEnd);
98081
98082   /* The SELECT was successfully coded.   Set the return code to 0
98083   ** to indicate no errors.
98084   */
98085   rc = 0;
98086
98087   /* Control jumps to here if an error is encountered above, or upon
98088   ** successful coding of the SELECT.
98089   */
98090 select_end:
98091   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98092
98093   /* Identify column names if results of the SELECT are to be output.
98094   */
98095   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
98096     generateColumnNames(pParse, pTabList, pEList);
98097   }
98098
98099   sqlite3DbFree(db, sAggInfo.aCol);
98100   sqlite3DbFree(db, sAggInfo.aFunc);
98101   return rc;
98102 }
98103
98104 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
98105 /*
98106 ** Generate a human-readable description of a the Select object.
98107 */
98108 static void explainOneSelect(Vdbe *pVdbe, Select *p){
98109   sqlite3ExplainPrintf(pVdbe, "SELECT ");
98110   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
98111     if( p->selFlags & SF_Distinct ){
98112       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
98113     }
98114     if( p->selFlags & SF_Aggregate ){
98115       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
98116     }
98117     sqlite3ExplainNL(pVdbe);
98118     sqlite3ExplainPrintf(pVdbe, "   ");
98119   }
98120   sqlite3ExplainExprList(pVdbe, p->pEList);
98121   sqlite3ExplainNL(pVdbe);
98122   if( p->pSrc && p->pSrc->nSrc ){
98123     int i;
98124     sqlite3ExplainPrintf(pVdbe, "FROM ");
98125     sqlite3ExplainPush(pVdbe);
98126     for(i=0; i<p->pSrc->nSrc; i++){
98127       struct SrcList_item *pItem = &p->pSrc->a[i];
98128       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
98129       if( pItem->pSelect ){
98130         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
98131         if( pItem->pTab ){
98132           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
98133         }
98134       }else if( pItem->zName ){
98135         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
98136       }
98137       if( pItem->zAlias ){
98138         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
98139       }
98140       if( pItem->jointype & JT_LEFT ){
98141         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
98142       }
98143       sqlite3ExplainNL(pVdbe);
98144     }
98145     sqlite3ExplainPop(pVdbe);
98146   }
98147   if( p->pWhere ){
98148     sqlite3ExplainPrintf(pVdbe, "WHERE ");
98149     sqlite3ExplainExpr(pVdbe, p->pWhere);
98150     sqlite3ExplainNL(pVdbe);
98151   }
98152   if( p->pGroupBy ){
98153     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
98154     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
98155     sqlite3ExplainNL(pVdbe);
98156   }
98157   if( p->pHaving ){
98158     sqlite3ExplainPrintf(pVdbe, "HAVING ");
98159     sqlite3ExplainExpr(pVdbe, p->pHaving);
98160     sqlite3ExplainNL(pVdbe);
98161   }
98162   if( p->pOrderBy ){
98163     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
98164     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
98165     sqlite3ExplainNL(pVdbe);
98166   }
98167   if( p->pLimit ){
98168     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
98169     sqlite3ExplainExpr(pVdbe, p->pLimit);
98170     sqlite3ExplainNL(pVdbe);
98171   }
98172   if( p->pOffset ){
98173     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
98174     sqlite3ExplainExpr(pVdbe, p->pOffset);
98175     sqlite3ExplainNL(pVdbe);
98176   }
98177 }
98178 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
98179   if( p==0 ){
98180     sqlite3ExplainPrintf(pVdbe, "(null-select)");
98181     return;
98182   }
98183   while( p->pPrior ) p = p->pPrior;
98184   sqlite3ExplainPush(pVdbe);
98185   while( p ){
98186     explainOneSelect(pVdbe, p);
98187     p = p->pNext;
98188     if( p==0 ) break;
98189     sqlite3ExplainNL(pVdbe);
98190     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
98191   }
98192   sqlite3ExplainPrintf(pVdbe, "END");
98193   sqlite3ExplainPop(pVdbe);
98194 }
98195
98196 /* End of the structure debug printing code
98197 *****************************************************************************/
98198 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
98199
98200 /************** End of select.c **********************************************/
98201 /************** Begin file table.c *******************************************/
98202 /*
98203 ** 2001 September 15
98204 **
98205 ** The author disclaims copyright to this source code.  In place of
98206 ** a legal notice, here is a blessing:
98207 **
98208 **    May you do good and not evil.
98209 **    May you find forgiveness for yourself and forgive others.
98210 **    May you share freely, never taking more than you give.
98211 **
98212 *************************************************************************
98213 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
98214 ** interface routines.  These are just wrappers around the main
98215 ** interface routine of sqlite3_exec().
98216 **
98217 ** These routines are in a separate files so that they will not be linked
98218 ** if they are not used.
98219 */
98220 /* #include <stdlib.h> */
98221 /* #include <string.h> */
98222
98223 #ifndef SQLITE_OMIT_GET_TABLE
98224
98225 /*
98226 ** This structure is used to pass data from sqlite3_get_table() through
98227 ** to the callback function is uses to build the result.
98228 */
98229 typedef struct TabResult {
98230   char **azResult;   /* Accumulated output */
98231   char *zErrMsg;     /* Error message text, if an error occurs */
98232   int nAlloc;        /* Slots allocated for azResult[] */
98233   int nRow;          /* Number of rows in the result */
98234   int nColumn;       /* Number of columns in the result */
98235   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
98236   int rc;            /* Return code from sqlite3_exec() */
98237 } TabResult;
98238
98239 /*
98240 ** This routine is called once for each row in the result table.  Its job
98241 ** is to fill in the TabResult structure appropriately, allocating new
98242 ** memory as necessary.
98243 */
98244 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
98245   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
98246   int need;                         /* Slots needed in p->azResult[] */
98247   int i;                            /* Loop counter */
98248   char *z;                          /* A single column of result */
98249
98250   /* Make sure there is enough space in p->azResult to hold everything
98251   ** we need to remember from this invocation of the callback.
98252   */
98253   if( p->nRow==0 && argv!=0 ){
98254     need = nCol*2;
98255   }else{
98256     need = nCol;
98257   }
98258   if( p->nData + need > p->nAlloc ){
98259     char **azNew;
98260     p->nAlloc = p->nAlloc*2 + need;
98261     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
98262     if( azNew==0 ) goto malloc_failed;
98263     p->azResult = azNew;
98264   }
98265
98266   /* If this is the first row, then generate an extra row containing
98267   ** the names of all columns.
98268   */
98269   if( p->nRow==0 ){
98270     p->nColumn = nCol;
98271     for(i=0; i<nCol; i++){
98272       z = sqlite3_mprintf("%s", colv[i]);
98273       if( z==0 ) goto malloc_failed;
98274       p->azResult[p->nData++] = z;
98275     }
98276   }else if( p->nColumn!=nCol ){
98277     sqlite3_free(p->zErrMsg);
98278     p->zErrMsg = sqlite3_mprintf(
98279        "sqlite3_get_table() called with two or more incompatible queries"
98280     );
98281     p->rc = SQLITE_ERROR;
98282     return 1;
98283   }
98284
98285   /* Copy over the row data
98286   */
98287   if( argv!=0 ){
98288     for(i=0; i<nCol; i++){
98289       if( argv[i]==0 ){
98290         z = 0;
98291       }else{
98292         int n = sqlite3Strlen30(argv[i])+1;
98293         z = sqlite3_malloc( n );
98294         if( z==0 ) goto malloc_failed;
98295         memcpy(z, argv[i], n);
98296       }
98297       p->azResult[p->nData++] = z;
98298     }
98299     p->nRow++;
98300   }
98301   return 0;
98302
98303 malloc_failed:
98304   p->rc = SQLITE_NOMEM;
98305   return 1;
98306 }
98307
98308 /*
98309 ** Query the database.  But instead of invoking a callback for each row,
98310 ** malloc() for space to hold the result and return the entire results
98311 ** at the conclusion of the call.
98312 **
98313 ** The result that is written to ***pazResult is held in memory obtained
98314 ** from malloc().  But the caller cannot free this memory directly.  
98315 ** Instead, the entire table should be passed to sqlite3_free_table() when
98316 ** the calling procedure is finished using it.
98317 */
98318 SQLITE_API int sqlite3_get_table(
98319   sqlite3 *db,                /* The database on which the SQL executes */
98320   const char *zSql,           /* The SQL to be executed */
98321   char ***pazResult,          /* Write the result table here */
98322   int *pnRow,                 /* Write the number of rows in the result here */
98323   int *pnColumn,              /* Write the number of columns of result here */
98324   char **pzErrMsg             /* Write error messages here */
98325 ){
98326   int rc;
98327   TabResult res;
98328
98329   *pazResult = 0;
98330   if( pnColumn ) *pnColumn = 0;
98331   if( pnRow ) *pnRow = 0;
98332   if( pzErrMsg ) *pzErrMsg = 0;
98333   res.zErrMsg = 0;
98334   res.nRow = 0;
98335   res.nColumn = 0;
98336   res.nData = 1;
98337   res.nAlloc = 20;
98338   res.rc = SQLITE_OK;
98339   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
98340   if( res.azResult==0 ){
98341      db->errCode = SQLITE_NOMEM;
98342      return SQLITE_NOMEM;
98343   }
98344   res.azResult[0] = 0;
98345   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
98346   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
98347   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
98348   if( (rc&0xff)==SQLITE_ABORT ){
98349     sqlite3_free_table(&res.azResult[1]);
98350     if( res.zErrMsg ){
98351       if( pzErrMsg ){
98352         sqlite3_free(*pzErrMsg);
98353         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
98354       }
98355       sqlite3_free(res.zErrMsg);
98356     }
98357     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
98358     return res.rc;
98359   }
98360   sqlite3_free(res.zErrMsg);
98361   if( rc!=SQLITE_OK ){
98362     sqlite3_free_table(&res.azResult[1]);
98363     return rc;
98364   }
98365   if( res.nAlloc>res.nData ){
98366     char **azNew;
98367     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
98368     if( azNew==0 ){
98369       sqlite3_free_table(&res.azResult[1]);
98370       db->errCode = SQLITE_NOMEM;
98371       return SQLITE_NOMEM;
98372     }
98373     res.azResult = azNew;
98374   }
98375   *pazResult = &res.azResult[1];
98376   if( pnColumn ) *pnColumn = res.nColumn;
98377   if( pnRow ) *pnRow = res.nRow;
98378   return rc;
98379 }
98380
98381 /*
98382 ** This routine frees the space the sqlite3_get_table() malloced.
98383 */
98384 SQLITE_API void sqlite3_free_table(
98385   char **azResult            /* Result returned from from sqlite3_get_table() */
98386 ){
98387   if( azResult ){
98388     int i, n;
98389     azResult--;
98390     assert( azResult!=0 );
98391     n = SQLITE_PTR_TO_INT(azResult[0]);
98392     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
98393     sqlite3_free(azResult);
98394   }
98395 }
98396
98397 #endif /* SQLITE_OMIT_GET_TABLE */
98398
98399 /************** End of table.c ***********************************************/
98400 /************** Begin file trigger.c *****************************************/
98401 /*
98402 **
98403 ** The author disclaims copyright to this source code.  In place of
98404 ** a legal notice, here is a blessing:
98405 **
98406 **    May you do good and not evil.
98407 **    May you find forgiveness for yourself and forgive others.
98408 **    May you share freely, never taking more than you give.
98409 **
98410 *************************************************************************
98411 ** This file contains the implementation for TRIGGERs
98412 */
98413
98414 #ifndef SQLITE_OMIT_TRIGGER
98415 /*
98416 ** Delete a linked list of TriggerStep structures.
98417 */
98418 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
98419   while( pTriggerStep ){
98420     TriggerStep * pTmp = pTriggerStep;
98421     pTriggerStep = pTriggerStep->pNext;
98422
98423     sqlite3ExprDelete(db, pTmp->pWhere);
98424     sqlite3ExprListDelete(db, pTmp->pExprList);
98425     sqlite3SelectDelete(db, pTmp->pSelect);
98426     sqlite3IdListDelete(db, pTmp->pIdList);
98427
98428     sqlite3DbFree(db, pTmp);
98429   }
98430 }
98431
98432 /*
98433 ** Given table pTab, return a list of all the triggers attached to 
98434 ** the table. The list is connected by Trigger.pNext pointers.
98435 **
98436 ** All of the triggers on pTab that are in the same database as pTab
98437 ** are already attached to pTab->pTrigger.  But there might be additional
98438 ** triggers on pTab in the TEMP schema.  This routine prepends all
98439 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
98440 ** and returns the combined list.
98441 **
98442 ** To state it another way:  This routine returns a list of all triggers
98443 ** that fire off of pTab.  The list will include any TEMP triggers on
98444 ** pTab as well as the triggers lised in pTab->pTrigger.
98445 */
98446 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
98447   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
98448   Trigger *pList = 0;                  /* List of triggers to return */
98449
98450   if( pParse->disableTriggers ){
98451     return 0;
98452   }
98453
98454   if( pTmpSchema!=pTab->pSchema ){
98455     HashElem *p;
98456     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
98457     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
98458       Trigger *pTrig = (Trigger *)sqliteHashData(p);
98459       if( pTrig->pTabSchema==pTab->pSchema
98460        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
98461       ){
98462         pTrig->pNext = (pList ? pList : pTab->pTrigger);
98463         pList = pTrig;
98464       }
98465     }
98466   }
98467
98468   return (pList ? pList : pTab->pTrigger);
98469 }
98470
98471 /*
98472 ** This is called by the parser when it sees a CREATE TRIGGER statement
98473 ** up to the point of the BEGIN before the trigger actions.  A Trigger
98474 ** structure is generated based on the information available and stored
98475 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
98476 ** sqlite3FinishTrigger() function is called to complete the trigger
98477 ** construction process.
98478 */
98479 SQLITE_PRIVATE void sqlite3BeginTrigger(
98480   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
98481   Token *pName1,      /* The name of the trigger */
98482   Token *pName2,      /* The name of the trigger */
98483   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
98484   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
98485   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
98486   SrcList *pTableName,/* The name of the table/view the trigger applies to */
98487   Expr *pWhen,        /* WHEN clause */
98488   int isTemp,         /* True if the TEMPORARY keyword is present */
98489   int noErr           /* Suppress errors if the trigger already exists */
98490 ){
98491   Trigger *pTrigger = 0;  /* The new trigger */
98492   Table *pTab;            /* Table that the trigger fires off of */
98493   char *zName = 0;        /* Name of the trigger */
98494   sqlite3 *db = pParse->db;  /* The database connection */
98495   int iDb;                /* The database to store the trigger in */
98496   Token *pName;           /* The unqualified db name */
98497   DbFixer sFix;           /* State vector for the DB fixer */
98498   int iTabDb;             /* Index of the database holding pTab */
98499
98500   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
98501   assert( pName2!=0 );
98502   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
98503   assert( op>0 && op<0xff );
98504   if( isTemp ){
98505     /* If TEMP was specified, then the trigger name may not be qualified. */
98506     if( pName2->n>0 ){
98507       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
98508       goto trigger_cleanup;
98509     }
98510     iDb = 1;
98511     pName = pName1;
98512   }else{
98513     /* Figure out the db that the trigger will be created in */
98514     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
98515     if( iDb<0 ){
98516       goto trigger_cleanup;
98517     }
98518   }
98519   if( !pTableName || db->mallocFailed ){
98520     goto trigger_cleanup;
98521   }
98522
98523   /* A long-standing parser bug is that this syntax was allowed:
98524   **
98525   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
98526   **                                                 ^^^^^^^^
98527   **
98528   ** To maintain backwards compatibility, ignore the database
98529   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
98530   */
98531   if( db->init.busy && iDb!=1 ){
98532     sqlite3DbFree(db, pTableName->a[0].zDatabase);
98533     pTableName->a[0].zDatabase = 0;
98534   }
98535
98536   /* If the trigger name was unqualified, and the table is a temp table,
98537   ** then set iDb to 1 to create the trigger in the temporary database.
98538   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
98539   ** exist, the error is caught by the block below.
98540   */
98541   pTab = sqlite3SrcListLookup(pParse, pTableName);
98542   if( db->init.busy==0 && pName2->n==0 && pTab
98543         && pTab->pSchema==db->aDb[1].pSchema ){
98544     iDb = 1;
98545   }
98546
98547   /* Ensure the table name matches database name and that the table exists */
98548   if( db->mallocFailed ) goto trigger_cleanup;
98549   assert( pTableName->nSrc==1 );
98550   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
98551       sqlite3FixSrcList(&sFix, pTableName) ){
98552     goto trigger_cleanup;
98553   }
98554   pTab = sqlite3SrcListLookup(pParse, pTableName);
98555   if( !pTab ){
98556     /* The table does not exist. */
98557     if( db->init.iDb==1 ){
98558       /* Ticket #3810.
98559       ** Normally, whenever a table is dropped, all associated triggers are
98560       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
98561       ** and the table is dropped by a different database connection, the
98562       ** trigger is not visible to the database connection that does the
98563       ** drop so the trigger cannot be dropped.  This results in an
98564       ** "orphaned trigger" - a trigger whose associated table is missing.
98565       */
98566       db->init.orphanTrigger = 1;
98567     }
98568     goto trigger_cleanup;
98569   }
98570   if( IsVirtual(pTab) ){
98571     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
98572     goto trigger_cleanup;
98573   }
98574
98575   /* Check that the trigger name is not reserved and that no trigger of the
98576   ** specified name exists */
98577   zName = sqlite3NameFromToken(db, pName);
98578   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
98579     goto trigger_cleanup;
98580   }
98581   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98582   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
98583                       zName, sqlite3Strlen30(zName)) ){
98584     if( !noErr ){
98585       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
98586     }else{
98587       assert( !db->init.busy );
98588       sqlite3CodeVerifySchema(pParse, iDb);
98589     }
98590     goto trigger_cleanup;
98591   }
98592
98593   /* Do not create a trigger on a system table */
98594   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
98595     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
98596     pParse->nErr++;
98597     goto trigger_cleanup;
98598   }
98599
98600   /* INSTEAD of triggers are only for views and views only support INSTEAD
98601   ** of triggers.
98602   */
98603   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
98604     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
98605         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
98606     goto trigger_cleanup;
98607   }
98608   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
98609     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
98610         " trigger on table: %S", pTableName, 0);
98611     goto trigger_cleanup;
98612   }
98613   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98614
98615 #ifndef SQLITE_OMIT_AUTHORIZATION
98616   {
98617     int code = SQLITE_CREATE_TRIGGER;
98618     const char *zDb = db->aDb[iTabDb].zName;
98619     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
98620     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
98621     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
98622       goto trigger_cleanup;
98623     }
98624     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
98625       goto trigger_cleanup;
98626     }
98627   }
98628 #endif
98629
98630   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
98631   ** cannot appear on views.  So we might as well translate every
98632   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
98633   ** elsewhere.
98634   */
98635   if (tr_tm == TK_INSTEAD){
98636     tr_tm = TK_BEFORE;
98637   }
98638
98639   /* Build the Trigger object */
98640   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
98641   if( pTrigger==0 ) goto trigger_cleanup;
98642   pTrigger->zName = zName;
98643   zName = 0;
98644   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
98645   pTrigger->pSchema = db->aDb[iDb].pSchema;
98646   pTrigger->pTabSchema = pTab->pSchema;
98647   pTrigger->op = (u8)op;
98648   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
98649   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
98650   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
98651   assert( pParse->pNewTrigger==0 );
98652   pParse->pNewTrigger = pTrigger;
98653
98654 trigger_cleanup:
98655   sqlite3DbFree(db, zName);
98656   sqlite3SrcListDelete(db, pTableName);
98657   sqlite3IdListDelete(db, pColumns);
98658   sqlite3ExprDelete(db, pWhen);
98659   if( !pParse->pNewTrigger ){
98660     sqlite3DeleteTrigger(db, pTrigger);
98661   }else{
98662     assert( pParse->pNewTrigger==pTrigger );
98663   }
98664 }
98665
98666 /*
98667 ** This routine is called after all of the trigger actions have been parsed
98668 ** in order to complete the process of building the trigger.
98669 */
98670 SQLITE_PRIVATE void sqlite3FinishTrigger(
98671   Parse *pParse,          /* Parser context */
98672   TriggerStep *pStepList, /* The triggered program */
98673   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
98674 ){
98675   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
98676   char *zName;                            /* Name of trigger */
98677   sqlite3 *db = pParse->db;               /* The database */
98678   DbFixer sFix;                           /* Fixer object */
98679   int iDb;                                /* Database containing the trigger */
98680   Token nameToken;                        /* Trigger name for error reporting */
98681
98682   pParse->pNewTrigger = 0;
98683   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
98684   zName = pTrig->zName;
98685   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
98686   pTrig->step_list = pStepList;
98687   while( pStepList ){
98688     pStepList->pTrig = pTrig;
98689     pStepList = pStepList->pNext;
98690   }
98691   nameToken.z = pTrig->zName;
98692   nameToken.n = sqlite3Strlen30(nameToken.z);
98693   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
98694           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
98695     goto triggerfinish_cleanup;
98696   }
98697
98698   /* if we are not initializing,
98699   ** build the sqlite_master entry
98700   */
98701   if( !db->init.busy ){
98702     Vdbe *v;
98703     char *z;
98704
98705     /* Make an entry in the sqlite_master table */
98706     v = sqlite3GetVdbe(pParse);
98707     if( v==0 ) goto triggerfinish_cleanup;
98708     sqlite3BeginWriteOperation(pParse, 0, iDb);
98709     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
98710     sqlite3NestedParse(pParse,
98711        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
98712        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
98713        pTrig->table, z);
98714     sqlite3DbFree(db, z);
98715     sqlite3ChangeCookie(pParse, iDb);
98716     sqlite3VdbeAddParseSchemaOp(v, iDb,
98717         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
98718   }
98719
98720   if( db->init.busy ){
98721     Trigger *pLink = pTrig;
98722     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
98723     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98724     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
98725     if( pTrig ){
98726       db->mallocFailed = 1;
98727     }else if( pLink->pSchema==pLink->pTabSchema ){
98728       Table *pTab;
98729       int n = sqlite3Strlen30(pLink->table);
98730       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
98731       assert( pTab!=0 );
98732       pLink->pNext = pTab->pTrigger;
98733       pTab->pTrigger = pLink;
98734     }
98735   }
98736
98737 triggerfinish_cleanup:
98738   sqlite3DeleteTrigger(db, pTrig);
98739   assert( !pParse->pNewTrigger );
98740   sqlite3DeleteTriggerStep(db, pStepList);
98741 }
98742
98743 /*
98744 ** Turn a SELECT statement (that the pSelect parameter points to) into
98745 ** a trigger step.  Return a pointer to a TriggerStep structure.
98746 **
98747 ** The parser calls this routine when it finds a SELECT statement in
98748 ** body of a TRIGGER.  
98749 */
98750 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
98751   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
98752   if( pTriggerStep==0 ) {
98753     sqlite3SelectDelete(db, pSelect);
98754     return 0;
98755   }
98756   pTriggerStep->op = TK_SELECT;
98757   pTriggerStep->pSelect = pSelect;
98758   pTriggerStep->orconf = OE_Default;
98759   return pTriggerStep;
98760 }
98761
98762 /*
98763 ** Allocate space to hold a new trigger step.  The allocated space
98764 ** holds both the TriggerStep object and the TriggerStep.target.z string.
98765 **
98766 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
98767 */
98768 static TriggerStep *triggerStepAllocate(
98769   sqlite3 *db,                /* Database connection */
98770   u8 op,                      /* Trigger opcode */
98771   Token *pName                /* The target name */
98772 ){
98773   TriggerStep *pTriggerStep;
98774
98775   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
98776   if( pTriggerStep ){
98777     char *z = (char*)&pTriggerStep[1];
98778     memcpy(z, pName->z, pName->n);
98779     pTriggerStep->target.z = z;
98780     pTriggerStep->target.n = pName->n;
98781     pTriggerStep->op = op;
98782   }
98783   return pTriggerStep;
98784 }
98785
98786 /*
98787 ** Build a trigger step out of an INSERT statement.  Return a pointer
98788 ** to the new trigger step.
98789 **
98790 ** The parser calls this routine when it sees an INSERT inside the
98791 ** body of a trigger.
98792 */
98793 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
98794   sqlite3 *db,        /* The database connection */
98795   Token *pTableName,  /* Name of the table into which we insert */
98796   IdList *pColumn,    /* List of columns in pTableName to insert into */
98797   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
98798   Select *pSelect,    /* A SELECT statement that supplies values */
98799   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
98800 ){
98801   TriggerStep *pTriggerStep;
98802
98803   assert(pEList == 0 || pSelect == 0);
98804   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
98805
98806   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
98807   if( pTriggerStep ){
98808     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
98809     pTriggerStep->pIdList = pColumn;
98810     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
98811     pTriggerStep->orconf = orconf;
98812   }else{
98813     sqlite3IdListDelete(db, pColumn);
98814   }
98815   sqlite3ExprListDelete(db, pEList);
98816   sqlite3SelectDelete(db, pSelect);
98817
98818   return pTriggerStep;
98819 }
98820
98821 /*
98822 ** Construct a trigger step that implements an UPDATE statement and return
98823 ** a pointer to that trigger step.  The parser calls this routine when it
98824 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
98825 */
98826 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
98827   sqlite3 *db,         /* The database connection */
98828   Token *pTableName,   /* Name of the table to be updated */
98829   ExprList *pEList,    /* The SET clause: list of column and new values */
98830   Expr *pWhere,        /* The WHERE clause */
98831   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
98832 ){
98833   TriggerStep *pTriggerStep;
98834
98835   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
98836   if( pTriggerStep ){
98837     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
98838     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
98839     pTriggerStep->orconf = orconf;
98840   }
98841   sqlite3ExprListDelete(db, pEList);
98842   sqlite3ExprDelete(db, pWhere);
98843   return pTriggerStep;
98844 }
98845
98846 /*
98847 ** Construct a trigger step that implements a DELETE statement and return
98848 ** a pointer to that trigger step.  The parser calls this routine when it
98849 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
98850 */
98851 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
98852   sqlite3 *db,            /* Database connection */
98853   Token *pTableName,      /* The table from which rows are deleted */
98854   Expr *pWhere            /* The WHERE clause */
98855 ){
98856   TriggerStep *pTriggerStep;
98857
98858   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
98859   if( pTriggerStep ){
98860     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
98861     pTriggerStep->orconf = OE_Default;
98862   }
98863   sqlite3ExprDelete(db, pWhere);
98864   return pTriggerStep;
98865 }
98866
98867 /* 
98868 ** Recursively delete a Trigger structure
98869 */
98870 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
98871   if( pTrigger==0 ) return;
98872   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
98873   sqlite3DbFree(db, pTrigger->zName);
98874   sqlite3DbFree(db, pTrigger->table);
98875   sqlite3ExprDelete(db, pTrigger->pWhen);
98876   sqlite3IdListDelete(db, pTrigger->pColumns);
98877   sqlite3DbFree(db, pTrigger);
98878 }
98879
98880 /*
98881 ** This function is called to drop a trigger from the database schema. 
98882 **
98883 ** This may be called directly from the parser and therefore identifies
98884 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
98885 ** same job as this routine except it takes a pointer to the trigger
98886 ** instead of the trigger name.
98887 **/
98888 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
98889   Trigger *pTrigger = 0;
98890   int i;
98891   const char *zDb;
98892   const char *zName;
98893   int nName;
98894   sqlite3 *db = pParse->db;
98895
98896   if( db->mallocFailed ) goto drop_trigger_cleanup;
98897   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98898     goto drop_trigger_cleanup;
98899   }
98900
98901   assert( pName->nSrc==1 );
98902   zDb = pName->a[0].zDatabase;
98903   zName = pName->a[0].zName;
98904   nName = sqlite3Strlen30(zName);
98905   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
98906   for(i=OMIT_TEMPDB; i<db->nDb; i++){
98907     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
98908     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
98909     assert( sqlite3SchemaMutexHeld(db, j, 0) );
98910     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
98911     if( pTrigger ) break;
98912   }
98913   if( !pTrigger ){
98914     if( !noErr ){
98915       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
98916     }else{
98917       sqlite3CodeVerifyNamedSchema(pParse, zDb);
98918     }
98919     pParse->checkSchema = 1;
98920     goto drop_trigger_cleanup;
98921   }
98922   sqlite3DropTriggerPtr(pParse, pTrigger);
98923
98924 drop_trigger_cleanup:
98925   sqlite3SrcListDelete(db, pName);
98926 }
98927
98928 /*
98929 ** Return a pointer to the Table structure for the table that a trigger
98930 ** is set on.
98931 */
98932 static Table *tableOfTrigger(Trigger *pTrigger){
98933   int n = sqlite3Strlen30(pTrigger->table);
98934   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
98935 }
98936
98937
98938 /*
98939 ** Drop a trigger given a pointer to that trigger. 
98940 */
98941 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
98942   Table   *pTable;
98943   Vdbe *v;
98944   sqlite3 *db = pParse->db;
98945   int iDb;
98946
98947   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
98948   assert( iDb>=0 && iDb<db->nDb );
98949   pTable = tableOfTrigger(pTrigger);
98950   assert( pTable );
98951   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
98952 #ifndef SQLITE_OMIT_AUTHORIZATION
98953   {
98954     int code = SQLITE_DROP_TRIGGER;
98955     const char *zDb = db->aDb[iDb].zName;
98956     const char *zTab = SCHEMA_TABLE(iDb);
98957     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
98958     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
98959       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
98960       return;
98961     }
98962   }
98963 #endif
98964
98965   /* Generate code to destroy the database record of the trigger.
98966   */
98967   assert( pTable!=0 );
98968   if( (v = sqlite3GetVdbe(pParse))!=0 ){
98969     int base;
98970     static const VdbeOpList dropTrigger[] = {
98971       { OP_Rewind,     0, ADDR(9),  0},
98972       { OP_String8,    0, 1,        0}, /* 1 */
98973       { OP_Column,     0, 1,        2},
98974       { OP_Ne,         2, ADDR(8),  1},
98975       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
98976       { OP_Column,     0, 0,        2},
98977       { OP_Ne,         2, ADDR(8),  1},
98978       { OP_Delete,     0, 0,        0},
98979       { OP_Next,       0, ADDR(1),  0}, /* 8 */
98980     };
98981
98982     sqlite3BeginWriteOperation(pParse, 0, iDb);
98983     sqlite3OpenMasterTable(pParse, iDb);
98984     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
98985     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
98986     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
98987     sqlite3ChangeCookie(pParse, iDb);
98988     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
98989     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
98990     if( pParse->nMem<3 ){
98991       pParse->nMem = 3;
98992     }
98993   }
98994 }
98995
98996 /*
98997 ** Remove a trigger from the hash tables of the sqlite* pointer.
98998 */
98999 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
99000   Trigger *pTrigger;
99001   Hash *pHash;
99002
99003   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99004   pHash = &(db->aDb[iDb].pSchema->trigHash);
99005   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
99006   if( ALWAYS(pTrigger) ){
99007     if( pTrigger->pSchema==pTrigger->pTabSchema ){
99008       Table *pTab = tableOfTrigger(pTrigger);
99009       Trigger **pp;
99010       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99011       *pp = (*pp)->pNext;
99012     }
99013     sqlite3DeleteTrigger(db, pTrigger);
99014     db->flags |= SQLITE_InternChanges;
99015   }
99016 }
99017
99018 /*
99019 ** pEList is the SET clause of an UPDATE statement.  Each entry
99020 ** in pEList is of the format <id>=<expr>.  If any of the entries
99021 ** in pEList have an <id> which matches an identifier in pIdList,
99022 ** then return TRUE.  If pIdList==NULL, then it is considered a
99023 ** wildcard that matches anything.  Likewise if pEList==NULL then
99024 ** it matches anything so always return true.  Return false only
99025 ** if there is no match.
99026 */
99027 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99028   int e;
99029   if( pIdList==0 || NEVER(pEList==0) ) return 1;
99030   for(e=0; e<pEList->nExpr; e++){
99031     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99032   }
99033   return 0; 
99034 }
99035
99036 /*
99037 ** Return a list of all triggers on table pTab if there exists at least
99038 ** one trigger that must be fired when an operation of type 'op' is 
99039 ** performed on the table, and, if that operation is an UPDATE, if at
99040 ** least one of the columns in pChanges is being modified.
99041 */
99042 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
99043   Parse *pParse,          /* Parse context */
99044   Table *pTab,            /* The table the contains the triggers */
99045   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99046   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99047   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99048 ){
99049   int mask = 0;
99050   Trigger *pList = 0;
99051   Trigger *p;
99052
99053   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
99054     pList = sqlite3TriggerList(pParse, pTab);
99055   }
99056   assert( pList==0 || IsVirtual(pTab)==0 );
99057   for(p=pList; p; p=p->pNext){
99058     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99059       mask |= p->tr_tm;
99060     }
99061   }
99062   if( pMask ){
99063     *pMask = mask;
99064   }
99065   return (mask ? pList : 0);
99066 }
99067
99068 /*
99069 ** Convert the pStep->target token into a SrcList and return a pointer
99070 ** to that SrcList.
99071 **
99072 ** This routine adds a specific database name, if needed, to the target when
99073 ** forming the SrcList.  This prevents a trigger in one database from
99074 ** referring to a target in another database.  An exception is when the
99075 ** trigger is in TEMP in which case it can refer to any other database it
99076 ** wants.
99077 */
99078 static SrcList *targetSrcList(
99079   Parse *pParse,       /* The parsing context */
99080   TriggerStep *pStep   /* The trigger containing the target token */
99081 ){
99082   int iDb;             /* Index of the database to use */
99083   SrcList *pSrc;       /* SrcList to be returned */
99084
99085   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
99086   if( pSrc ){
99087     assert( pSrc->nSrc>0 );
99088     assert( pSrc->a!=0 );
99089     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
99090     if( iDb==0 || iDb>=2 ){
99091       sqlite3 *db = pParse->db;
99092       assert( iDb<pParse->db->nDb );
99093       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
99094     }
99095   }
99096   return pSrc;
99097 }
99098
99099 /*
99100 ** Generate VDBE code for the statements inside the body of a single 
99101 ** trigger.
99102 */
99103 static int codeTriggerProgram(
99104   Parse *pParse,            /* The parser context */
99105   TriggerStep *pStepList,   /* List of statements inside the trigger body */
99106   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
99107 ){
99108   TriggerStep *pStep;
99109   Vdbe *v = pParse->pVdbe;
99110   sqlite3 *db = pParse->db;
99111
99112   assert( pParse->pTriggerTab && pParse->pToplevel );
99113   assert( pStepList );
99114   assert( v!=0 );
99115   for(pStep=pStepList; pStep; pStep=pStep->pNext){
99116     /* Figure out the ON CONFLICT policy that will be used for this step
99117     ** of the trigger program. If the statement that caused this trigger
99118     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
99119     ** the ON CONFLICT policy that was specified as part of the trigger
99120     ** step statement. Example:
99121     **
99122     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
99123     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
99124     **   END;
99125     **
99126     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
99127     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
99128     */
99129     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
99130
99131     switch( pStep->op ){
99132       case TK_UPDATE: {
99133         sqlite3Update(pParse, 
99134           targetSrcList(pParse, pStep),
99135           sqlite3ExprListDup(db, pStep->pExprList, 0), 
99136           sqlite3ExprDup(db, pStep->pWhere, 0), 
99137           pParse->eOrconf
99138         );
99139         break;
99140       }
99141       case TK_INSERT: {
99142         sqlite3Insert(pParse, 
99143           targetSrcList(pParse, pStep),
99144           sqlite3ExprListDup(db, pStep->pExprList, 0), 
99145           sqlite3SelectDup(db, pStep->pSelect, 0), 
99146           sqlite3IdListDup(db, pStep->pIdList), 
99147           pParse->eOrconf
99148         );
99149         break;
99150       }
99151       case TK_DELETE: {
99152         sqlite3DeleteFrom(pParse, 
99153           targetSrcList(pParse, pStep),
99154           sqlite3ExprDup(db, pStep->pWhere, 0)
99155         );
99156         break;
99157       }
99158       default: assert( pStep->op==TK_SELECT ); {
99159         SelectDest sDest;
99160         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
99161         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
99162         sqlite3Select(pParse, pSelect, &sDest);
99163         sqlite3SelectDelete(db, pSelect);
99164         break;
99165       }
99166     } 
99167     if( pStep->op!=TK_SELECT ){
99168       sqlite3VdbeAddOp0(v, OP_ResetCount);
99169     }
99170   }
99171
99172   return 0;
99173 }
99174
99175 #ifdef SQLITE_DEBUG
99176 /*
99177 ** This function is used to add VdbeComment() annotations to a VDBE
99178 ** program. It is not used in production code, only for debugging.
99179 */
99180 static const char *onErrorText(int onError){
99181   switch( onError ){
99182     case OE_Abort:    return "abort";
99183     case OE_Rollback: return "rollback";
99184     case OE_Fail:     return "fail";
99185     case OE_Replace:  return "replace";
99186     case OE_Ignore:   return "ignore";
99187     case OE_Default:  return "default";
99188   }
99189   return "n/a";
99190 }
99191 #endif
99192
99193 /*
99194 ** Parse context structure pFrom has just been used to create a sub-vdbe
99195 ** (trigger program). If an error has occurred, transfer error information
99196 ** from pFrom to pTo.
99197 */
99198 static void transferParseError(Parse *pTo, Parse *pFrom){
99199   assert( pFrom->zErrMsg==0 || pFrom->nErr );
99200   assert( pTo->zErrMsg==0 || pTo->nErr );
99201   if( pTo->nErr==0 ){
99202     pTo->zErrMsg = pFrom->zErrMsg;
99203     pTo->nErr = pFrom->nErr;
99204   }else{
99205     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
99206   }
99207 }
99208
99209 /*
99210 ** Create and populate a new TriggerPrg object with a sub-program 
99211 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
99212 */
99213 static TriggerPrg *codeRowTrigger(
99214   Parse *pParse,       /* Current parse context */
99215   Trigger *pTrigger,   /* Trigger to code */
99216   Table *pTab,         /* The table pTrigger is attached to */
99217   int orconf           /* ON CONFLICT policy to code trigger program with */
99218 ){
99219   Parse *pTop = sqlite3ParseToplevel(pParse);
99220   sqlite3 *db = pParse->db;   /* Database handle */
99221   TriggerPrg *pPrg;           /* Value to return */
99222   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
99223   Vdbe *v;                    /* Temporary VM */
99224   NameContext sNC;            /* Name context for sub-vdbe */
99225   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
99226   Parse *pSubParse;           /* Parse context for sub-vdbe */
99227   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
99228
99229   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99230   assert( pTop->pVdbe );
99231
99232   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
99233   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
99234   ** list of the top-level Parse object sooner rather than later.  */
99235   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
99236   if( !pPrg ) return 0;
99237   pPrg->pNext = pTop->pTriggerPrg;
99238   pTop->pTriggerPrg = pPrg;
99239   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
99240   if( !pProgram ) return 0;
99241   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
99242   pPrg->pTrigger = pTrigger;
99243   pPrg->orconf = orconf;
99244   pPrg->aColmask[0] = 0xffffffff;
99245   pPrg->aColmask[1] = 0xffffffff;
99246
99247   /* Allocate and populate a new Parse context to use for coding the 
99248   ** trigger sub-program.  */
99249   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
99250   if( !pSubParse ) return 0;
99251   memset(&sNC, 0, sizeof(sNC));
99252   sNC.pParse = pSubParse;
99253   pSubParse->db = db;
99254   pSubParse->pTriggerTab = pTab;
99255   pSubParse->pToplevel = pTop;
99256   pSubParse->zAuthContext = pTrigger->zName;
99257   pSubParse->eTriggerOp = pTrigger->op;
99258   pSubParse->nQueryLoop = pParse->nQueryLoop;
99259
99260   v = sqlite3GetVdbe(pSubParse);
99261   if( v ){
99262     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
99263       pTrigger->zName, onErrorText(orconf),
99264       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
99265         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
99266         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
99267         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
99268       pTab->zName
99269     ));
99270 #ifndef SQLITE_OMIT_TRACE
99271     sqlite3VdbeChangeP4(v, -1, 
99272       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
99273     );
99274 #endif
99275
99276     /* If one was specified, code the WHEN clause. If it evaluates to false
99277     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
99278     ** OP_Halt inserted at the end of the program.  */
99279     if( pTrigger->pWhen ){
99280       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
99281       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
99282        && db->mallocFailed==0 
99283       ){
99284         iEndTrigger = sqlite3VdbeMakeLabel(v);
99285         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
99286       }
99287       sqlite3ExprDelete(db, pWhen);
99288     }
99289
99290     /* Code the trigger program into the sub-vdbe. */
99291     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
99292
99293     /* Insert an OP_Halt at the end of the sub-program. */
99294     if( iEndTrigger ){
99295       sqlite3VdbeResolveLabel(v, iEndTrigger);
99296     }
99297     sqlite3VdbeAddOp0(v, OP_Halt);
99298     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
99299
99300     transferParseError(pParse, pSubParse);
99301     if( db->mallocFailed==0 ){
99302       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
99303     }
99304     pProgram->nMem = pSubParse->nMem;
99305     pProgram->nCsr = pSubParse->nTab;
99306     pProgram->nOnce = pSubParse->nOnce;
99307     pProgram->token = (void *)pTrigger;
99308     pPrg->aColmask[0] = pSubParse->oldmask;
99309     pPrg->aColmask[1] = pSubParse->newmask;
99310     sqlite3VdbeDelete(v);
99311   }
99312
99313   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
99314   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
99315   sqlite3StackFree(db, pSubParse);
99316
99317   return pPrg;
99318 }
99319     
99320 /*
99321 ** Return a pointer to a TriggerPrg object containing the sub-program for
99322 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
99323 ** TriggerPrg object exists, a new object is allocated and populated before
99324 ** being returned.
99325 */
99326 static TriggerPrg *getRowTrigger(
99327   Parse *pParse,       /* Current parse context */
99328   Trigger *pTrigger,   /* Trigger to code */
99329   Table *pTab,         /* The table trigger pTrigger is attached to */
99330   int orconf           /* ON CONFLICT algorithm. */
99331 ){
99332   Parse *pRoot = sqlite3ParseToplevel(pParse);
99333   TriggerPrg *pPrg;
99334
99335   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99336
99337   /* It may be that this trigger has already been coded (or is in the
99338   ** process of being coded). If this is the case, then an entry with
99339   ** a matching TriggerPrg.pTrigger field will be present somewhere
99340   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
99341   for(pPrg=pRoot->pTriggerPrg; 
99342       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
99343       pPrg=pPrg->pNext
99344   );
99345
99346   /* If an existing TriggerPrg could not be located, create a new one. */
99347   if( !pPrg ){
99348     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
99349   }
99350
99351   return pPrg;
99352 }
99353
99354 /*
99355 ** Generate code for the trigger program associated with trigger p on 
99356 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
99357 ** function are the same as those described in the header function for
99358 ** sqlite3CodeRowTrigger()
99359 */
99360 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
99361   Parse *pParse,       /* Parse context */
99362   Trigger *p,          /* Trigger to code */
99363   Table *pTab,         /* The table to code triggers from */
99364   int reg,             /* Reg array containing OLD.* and NEW.* values */
99365   int orconf,          /* ON CONFLICT policy */
99366   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
99367 ){
99368   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
99369   TriggerPrg *pPrg;
99370   pPrg = getRowTrigger(pParse, p, pTab, orconf);
99371   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
99372
99373   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
99374   ** is a pointer to the sub-vdbe containing the trigger program.  */
99375   if( pPrg ){
99376     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
99377
99378     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
99379     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
99380     VdbeComment(
99381         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
99382
99383     /* Set the P5 operand of the OP_Program instruction to non-zero if
99384     ** recursive invocation of this trigger program is disallowed. Recursive
99385     ** invocation is disallowed if (a) the sub-program is really a trigger,
99386     ** not a foreign key action, and (b) the flag to enable recursive triggers
99387     ** is clear.  */
99388     sqlite3VdbeChangeP5(v, (u8)bRecursive);
99389   }
99390 }
99391
99392 /*
99393 ** This is called to code the required FOR EACH ROW triggers for an operation
99394 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
99395 ** is given by the op paramater. The tr_tm parameter determines whether the
99396 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
99397 ** parameter pChanges is passed the list of columns being modified.
99398 **
99399 ** If there are no triggers that fire at the specified time for the specified
99400 ** operation on pTab, this function is a no-op.
99401 **
99402 ** The reg argument is the address of the first in an array of registers 
99403 ** that contain the values substituted for the new.* and old.* references
99404 ** in the trigger program. If N is the number of columns in table pTab
99405 ** (a copy of pTab->nCol), then registers are populated as follows:
99406 **
99407 **   Register       Contains
99408 **   ------------------------------------------------------
99409 **   reg+0          OLD.rowid
99410 **   reg+1          OLD.* value of left-most column of pTab
99411 **   ...            ...
99412 **   reg+N          OLD.* value of right-most column of pTab
99413 **   reg+N+1        NEW.rowid
99414 **   reg+N+2        OLD.* value of left-most column of pTab
99415 **   ...            ...
99416 **   reg+N+N+1      NEW.* value of right-most column of pTab
99417 **
99418 ** For ON DELETE triggers, the registers containing the NEW.* values will
99419 ** never be accessed by the trigger program, so they are not allocated or 
99420 ** populated by the caller (there is no data to populate them with anyway). 
99421 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
99422 ** are never accessed, and so are not allocated by the caller. So, for an
99423 ** ON INSERT trigger, the value passed to this function as parameter reg
99424 ** is not a readable register, although registers (reg+N) through 
99425 ** (reg+N+N+1) are.
99426 **
99427 ** Parameter orconf is the default conflict resolution algorithm for the
99428 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
99429 ** is the instruction that control should jump to if a trigger program
99430 ** raises an IGNORE exception.
99431 */
99432 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
99433   Parse *pParse,       /* Parse context */
99434   Trigger *pTrigger,   /* List of triggers on table pTab */
99435   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
99436   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
99437   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
99438   Table *pTab,         /* The table to code triggers from */
99439   int reg,             /* The first in an array of registers (see above) */
99440   int orconf,          /* ON CONFLICT policy */
99441   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
99442 ){
99443   Trigger *p;          /* Used to iterate through pTrigger list */
99444
99445   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
99446   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
99447   assert( (op==TK_UPDATE)==(pChanges!=0) );
99448
99449   for(p=pTrigger; p; p=p->pNext){
99450
99451     /* Sanity checking:  The schema for the trigger and for the table are
99452     ** always defined.  The trigger must be in the same schema as the table
99453     ** or else it must be a TEMP trigger. */
99454     assert( p->pSchema!=0 );
99455     assert( p->pTabSchema!=0 );
99456     assert( p->pSchema==p->pTabSchema 
99457          || p->pSchema==pParse->db->aDb[1].pSchema );
99458
99459     /* Determine whether we should code this trigger */
99460     if( p->op==op 
99461      && p->tr_tm==tr_tm 
99462      && checkColumnOverlap(p->pColumns, pChanges)
99463     ){
99464       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
99465     }
99466   }
99467 }
99468
99469 /*
99470 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
99471 ** This function returns a 32-bit bitmask indicating which columns of the 
99472 ** old.* or new.* tables actually are used by triggers. This information 
99473 ** may be used by the caller, for example, to avoid having to load the entire
99474 ** old.* record into memory when executing an UPDATE or DELETE command.
99475 **
99476 ** Bit 0 of the returned mask is set if the left-most column of the
99477 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
99478 ** the second leftmost column value is required, and so on. If there
99479 ** are more than 32 columns in the table, and at least one of the columns
99480 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
99481 **
99482 ** It is not possible to determine if the old.rowid or new.rowid column is 
99483 ** accessed by triggers. The caller must always assume that it is.
99484 **
99485 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
99486 ** applies to the old.* table. If 1, the new.* table.
99487 **
99488 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
99489 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
99490 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
99491 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
99492 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
99493 */
99494 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
99495   Parse *pParse,       /* Parse context */
99496   Trigger *pTrigger,   /* List of triggers on table pTab */
99497   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
99498   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
99499   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99500   Table *pTab,         /* The table to code triggers from */
99501   int orconf           /* Default ON CONFLICT policy for trigger steps */
99502 ){
99503   const int op = pChanges ? TK_UPDATE : TK_DELETE;
99504   u32 mask = 0;
99505   Trigger *p;
99506
99507   assert( isNew==1 || isNew==0 );
99508   for(p=pTrigger; p; p=p->pNext){
99509     if( p->op==op && (tr_tm&p->tr_tm)
99510      && checkColumnOverlap(p->pColumns,pChanges)
99511     ){
99512       TriggerPrg *pPrg;
99513       pPrg = getRowTrigger(pParse, p, pTab, orconf);
99514       if( pPrg ){
99515         mask |= pPrg->aColmask[isNew];
99516       }
99517     }
99518   }
99519
99520   return mask;
99521 }
99522
99523 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
99524
99525 /************** End of trigger.c *********************************************/
99526 /************** Begin file update.c ******************************************/
99527 /*
99528 ** 2001 September 15
99529 **
99530 ** The author disclaims copyright to this source code.  In place of
99531 ** a legal notice, here is a blessing:
99532 **
99533 **    May you do good and not evil.
99534 **    May you find forgiveness for yourself and forgive others.
99535 **    May you share freely, never taking more than you give.
99536 **
99537 *************************************************************************
99538 ** This file contains C code routines that are called by the parser
99539 ** to handle UPDATE statements.
99540 */
99541
99542 #ifndef SQLITE_OMIT_VIRTUALTABLE
99543 /* Forward declaration */
99544 static void updateVirtualTable(
99545   Parse *pParse,       /* The parsing context */
99546   SrcList *pSrc,       /* The virtual table to be modified */
99547   Table *pTab,         /* The virtual table */
99548   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
99549   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
99550   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
99551   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
99552   int onError          /* ON CONFLICT strategy */
99553 );
99554 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99555
99556 /*
99557 ** The most recently coded instruction was an OP_Column to retrieve the
99558 ** i-th column of table pTab. This routine sets the P4 parameter of the 
99559 ** OP_Column to the default value, if any.
99560 **
99561 ** The default value of a column is specified by a DEFAULT clause in the 
99562 ** column definition. This was either supplied by the user when the table
99563 ** was created, or added later to the table definition by an ALTER TABLE
99564 ** command. If the latter, then the row-records in the table btree on disk
99565 ** may not contain a value for the column and the default value, taken
99566 ** from the P4 parameter of the OP_Column instruction, is returned instead.
99567 ** If the former, then all row-records are guaranteed to include a value
99568 ** for the column and the P4 value is not required.
99569 **
99570 ** Column definitions created by an ALTER TABLE command may only have 
99571 ** literal default values specified: a number, null or a string. (If a more
99572 ** complicated default expression value was provided, it is evaluated 
99573 ** when the ALTER TABLE is executed and one of the literal values written
99574 ** into the sqlite_master table.)
99575 **
99576 ** Therefore, the P4 parameter is only required if the default value for
99577 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
99578 ** function is capable of transforming these types of expressions into
99579 ** sqlite3_value objects.
99580 **
99581 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
99582 ** on register iReg. This is used when an equivalent integer value is 
99583 ** stored in place of an 8-byte floating point value in order to save 
99584 ** space.
99585 */
99586 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
99587   assert( pTab!=0 );
99588   if( !pTab->pSelect ){
99589     sqlite3_value *pValue;
99590     u8 enc = ENC(sqlite3VdbeDb(v));
99591     Column *pCol = &pTab->aCol[i];
99592     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
99593     assert( i<pTab->nCol );
99594     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
99595                          pCol->affinity, &pValue);
99596     if( pValue ){
99597       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
99598     }
99599 #ifndef SQLITE_OMIT_FLOATING_POINT
99600     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
99601       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
99602     }
99603 #endif
99604   }
99605 }
99606
99607 /*
99608 ** Process an UPDATE statement.
99609 **
99610 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
99611 **          \_______/ \________/     \______/       \________________/
99612 *            onError   pTabList      pChanges             pWhere
99613 */
99614 SQLITE_PRIVATE void sqlite3Update(
99615   Parse *pParse,         /* The parser context */
99616   SrcList *pTabList,     /* The table in which we should change things */
99617   ExprList *pChanges,    /* Things to be changed */
99618   Expr *pWhere,          /* The WHERE clause.  May be null */
99619   int onError            /* How to handle constraint errors */
99620 ){
99621   int i, j;              /* Loop counters */
99622   Table *pTab;           /* The table to be updated */
99623   int addr = 0;          /* VDBE instruction address of the start of the loop */
99624   WhereInfo *pWInfo;     /* Information about the WHERE clause */
99625   Vdbe *v;               /* The virtual database engine */
99626   Index *pIdx;           /* For looping over indices */
99627   int nIdx;              /* Number of indices that need updating */
99628   int iCur;              /* VDBE Cursor number of pTab */
99629   sqlite3 *db;           /* The database structure */
99630   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
99631   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
99632                          ** an expression for the i-th column of the table.
99633                          ** aXRef[i]==-1 if the i-th column is not changed. */
99634   int chngRowid;         /* True if the record number is being changed */
99635   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
99636   int openAll = 0;       /* True if all indices need to be opened */
99637   AuthContext sContext;  /* The authorization context */
99638   NameContext sNC;       /* The name-context to resolve expressions in */
99639   int iDb;               /* Database containing the table being updated */
99640   int okOnePass;         /* True for one-pass algorithm without the FIFO */
99641   int hasFK;             /* True if foreign key processing is required */
99642
99643 #ifndef SQLITE_OMIT_TRIGGER
99644   int isView;            /* True when updating a view (INSTEAD OF trigger) */
99645   Trigger *pTrigger;     /* List of triggers on pTab, if required */
99646   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99647 #endif
99648   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
99649
99650   /* Register Allocations */
99651   int regRowCount = 0;   /* A count of rows changed */
99652   int regOldRowid;       /* The old rowid */
99653   int regNewRowid;       /* The new rowid */
99654   int regNew;            /* Content of the NEW.* table in triggers */
99655   int regOld = 0;        /* Content of OLD.* table in triggers */
99656   int regRowSet = 0;     /* Rowset of rows to be updated */
99657
99658   memset(&sContext, 0, sizeof(sContext));
99659   db = pParse->db;
99660   if( pParse->nErr || db->mallocFailed ){
99661     goto update_cleanup;
99662   }
99663   assert( pTabList->nSrc==1 );
99664
99665   /* Locate the table which we want to update. 
99666   */
99667   pTab = sqlite3SrcListLookup(pParse, pTabList);
99668   if( pTab==0 ) goto update_cleanup;
99669   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99670
99671   /* Figure out if we have any triggers and if the table being
99672   ** updated is a view.
99673   */
99674 #ifndef SQLITE_OMIT_TRIGGER
99675   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
99676   isView = pTab->pSelect!=0;
99677   assert( pTrigger || tmask==0 );
99678 #else
99679 # define pTrigger 0
99680 # define isView 0
99681 # define tmask 0
99682 #endif
99683 #ifdef SQLITE_OMIT_VIEW
99684 # undef isView
99685 # define isView 0
99686 #endif
99687
99688   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
99689     goto update_cleanup;
99690   }
99691   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
99692     goto update_cleanup;
99693   }
99694   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
99695   if( aXRef==0 ) goto update_cleanup;
99696   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
99697
99698   /* Allocate a cursors for the main database table and for all indices.
99699   ** The index cursors might not be used, but if they are used they
99700   ** need to occur right after the database cursor.  So go ahead and
99701   ** allocate enough space, just in case.
99702   */
99703   pTabList->a[0].iCursor = iCur = pParse->nTab++;
99704   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99705     pParse->nTab++;
99706   }
99707
99708   /* Initialize the name-context */
99709   memset(&sNC, 0, sizeof(sNC));
99710   sNC.pParse = pParse;
99711   sNC.pSrcList = pTabList;
99712
99713   /* Resolve the column names in all the expressions of the
99714   ** of the UPDATE statement.  Also find the column index
99715   ** for each column to be updated in the pChanges array.  For each
99716   ** column to be updated, make sure we have authorization to change
99717   ** that column.
99718   */
99719   chngRowid = 0;
99720   for(i=0; i<pChanges->nExpr; i++){
99721     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
99722       goto update_cleanup;
99723     }
99724     for(j=0; j<pTab->nCol; j++){
99725       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
99726         if( j==pTab->iPKey ){
99727           chngRowid = 1;
99728           pRowidExpr = pChanges->a[i].pExpr;
99729         }
99730         aXRef[j] = i;
99731         break;
99732       }
99733     }
99734     if( j>=pTab->nCol ){
99735       if( sqlite3IsRowid(pChanges->a[i].zName) ){
99736         chngRowid = 1;
99737         pRowidExpr = pChanges->a[i].pExpr;
99738       }else{
99739         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
99740         pParse->checkSchema = 1;
99741         goto update_cleanup;
99742       }
99743     }
99744 #ifndef SQLITE_OMIT_AUTHORIZATION
99745     {
99746       int rc;
99747       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
99748                            pTab->aCol[j].zName, db->aDb[iDb].zName);
99749       if( rc==SQLITE_DENY ){
99750         goto update_cleanup;
99751       }else if( rc==SQLITE_IGNORE ){
99752         aXRef[j] = -1;
99753       }
99754     }
99755 #endif
99756   }
99757
99758   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
99759
99760   /* Allocate memory for the array aRegIdx[].  There is one entry in the
99761   ** array for each index associated with table being updated.  Fill in
99762   ** the value with a register number for indices that are to be used
99763   ** and with zero for unused indices.
99764   */
99765   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
99766   if( nIdx>0 ){
99767     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
99768     if( aRegIdx==0 ) goto update_cleanup;
99769   }
99770   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
99771     int reg;
99772     if( hasFK || chngRowid ){
99773       reg = ++pParse->nMem;
99774     }else{
99775       reg = 0;
99776       for(i=0; i<pIdx->nColumn; i++){
99777         if( aXRef[pIdx->aiColumn[i]]>=0 ){
99778           reg = ++pParse->nMem;
99779           break;
99780         }
99781       }
99782     }
99783     aRegIdx[j] = reg;
99784   }
99785
99786   /* Begin generating code. */
99787   v = sqlite3GetVdbe(pParse);
99788   if( v==0 ) goto update_cleanup;
99789   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
99790   sqlite3BeginWriteOperation(pParse, 1, iDb);
99791
99792 #ifndef SQLITE_OMIT_VIRTUALTABLE
99793   /* Virtual tables must be handled separately */
99794   if( IsVirtual(pTab) ){
99795     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
99796                        pWhere, onError);
99797     pWhere = 0;
99798     pTabList = 0;
99799     goto update_cleanup;
99800   }
99801 #endif
99802
99803   /* Allocate required registers. */
99804   regRowSet = ++pParse->nMem;
99805   regOldRowid = regNewRowid = ++pParse->nMem;
99806   if( pTrigger || hasFK ){
99807     regOld = pParse->nMem + 1;
99808     pParse->nMem += pTab->nCol;
99809   }
99810   if( chngRowid || pTrigger || hasFK ){
99811     regNewRowid = ++pParse->nMem;
99812   }
99813   regNew = pParse->nMem + 1;
99814   pParse->nMem += pTab->nCol;
99815
99816   /* Start the view context. */
99817   if( isView ){
99818     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
99819   }
99820
99821   /* If we are trying to update a view, realize that view into
99822   ** a ephemeral table.
99823   */
99824 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
99825   if( isView ){
99826     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
99827   }
99828 #endif
99829
99830   /* Resolve the column names in all the expressions in the
99831   ** WHERE clause.
99832   */
99833   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
99834     goto update_cleanup;
99835   }
99836
99837   /* Begin the database scan
99838   */
99839   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
99840   pWInfo = sqlite3WhereBegin(
99841       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
99842   );
99843   if( pWInfo==0 ) goto update_cleanup;
99844   okOnePass = pWInfo->okOnePass;
99845
99846   /* Remember the rowid of every item to be updated.
99847   */
99848   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
99849   if( !okOnePass ){
99850     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
99851   }
99852
99853   /* End the database scan loop.
99854   */
99855   sqlite3WhereEnd(pWInfo);
99856
99857   /* Initialize the count of updated rows
99858   */
99859   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
99860     regRowCount = ++pParse->nMem;
99861     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
99862   }
99863
99864   if( !isView ){
99865     /* 
99866     ** Open every index that needs updating.  Note that if any
99867     ** index could potentially invoke a REPLACE conflict resolution 
99868     ** action, then we need to open all indices because we might need
99869     ** to be deleting some records.
99870     */
99871     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
99872     if( onError==OE_Replace ){
99873       openAll = 1;
99874     }else{
99875       openAll = 0;
99876       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99877         if( pIdx->onError==OE_Replace ){
99878           openAll = 1;
99879           break;
99880         }
99881       }
99882     }
99883     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99884       assert( aRegIdx );
99885       if( openAll || aRegIdx[i]>0 ){
99886         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
99887         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
99888                        (char*)pKey, P4_KEYINFO_HANDOFF);
99889         assert( pParse->nTab>iCur+i+1 );
99890       }
99891     }
99892   }
99893
99894   /* Top of the update loop */
99895   if( okOnePass ){
99896     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
99897     addr = sqlite3VdbeAddOp0(v, OP_Goto);
99898     sqlite3VdbeJumpHere(v, a1);
99899   }else{
99900     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
99901   }
99902
99903   /* Make cursor iCur point to the record that is being updated. If
99904   ** this record does not exist for some reason (deleted by a trigger,
99905   ** for example, then jump to the next iteration of the RowSet loop.  */
99906   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
99907
99908   /* If the record number will change, set register regNewRowid to
99909   ** contain the new value. If the record number is not being modified,
99910   ** then regNewRowid is the same register as regOldRowid, which is
99911   ** already populated.  */
99912   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
99913   if( chngRowid ){
99914     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
99915     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
99916   }
99917
99918   /* If there are triggers on this table, populate an array of registers 
99919   ** with the required old.* column data.  */
99920   if( hasFK || pTrigger ){
99921     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
99922     oldmask |= sqlite3TriggerColmask(pParse, 
99923         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
99924     );
99925     for(i=0; i<pTab->nCol; i++){
99926       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
99927         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
99928       }else{
99929         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
99930       }
99931     }
99932     if( chngRowid==0 ){
99933       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
99934     }
99935   }
99936
99937   /* Populate the array of registers beginning at regNew with the new
99938   ** row data. This array is used to check constaints, create the new
99939   ** table and index records, and as the values for any new.* references
99940   ** made by triggers.
99941   **
99942   ** If there are one or more BEFORE triggers, then do not populate the
99943   ** registers associated with columns that are (a) not modified by
99944   ** this UPDATE statement and (b) not accessed by new.* references. The
99945   ** values for registers not modified by the UPDATE must be reloaded from 
99946   ** the database after the BEFORE triggers are fired anyway (as the trigger 
99947   ** may have modified them). So not loading those that are not going to
99948   ** be used eliminates some redundant opcodes.
99949   */
99950   newmask = sqlite3TriggerColmask(
99951       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
99952   );
99953   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
99954   for(i=0; i<pTab->nCol; i++){
99955     if( i==pTab->iPKey ){
99956       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
99957     }else{
99958       j = aXRef[i];
99959       if( j>=0 ){
99960         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
99961       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
99962         /* This branch loads the value of a column that will not be changed 
99963         ** into a register. This is done if there are no BEFORE triggers, or
99964         ** if there are one or more BEFORE triggers that use this value via
99965         ** a new.* reference in a trigger program.
99966         */
99967         testcase( i==31 );
99968         testcase( i==32 );
99969         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
99970         sqlite3ColumnDefault(v, pTab, i, regNew+i);
99971       }
99972     }
99973   }
99974
99975   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
99976   ** verified. One could argue that this is wrong.
99977   */
99978   if( tmask&TRIGGER_BEFORE ){
99979     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
99980     sqlite3TableAffinityStr(v, pTab);
99981     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
99982         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
99983
99984     /* The row-trigger may have deleted the row being updated. In this
99985     ** case, jump to the next row. No updates or AFTER triggers are 
99986     ** required. This behaviour - what happens when the row being updated
99987     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
99988     ** documentation.
99989     */
99990     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
99991
99992     /* If it did not delete it, the row-trigger may still have modified 
99993     ** some of the columns of the row being updated. Load the values for 
99994     ** all columns not modified by the update statement into their 
99995     ** registers in case this has happened.
99996     */
99997     for(i=0; i<pTab->nCol; i++){
99998       if( aXRef[i]<0 && i!=pTab->iPKey ){
99999         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100000         sqlite3ColumnDefault(v, pTab, i, regNew+i);
100001       }
100002     }
100003   }
100004
100005   if( !isView ){
100006     int j1;                       /* Address of jump instruction */
100007
100008     /* Do constraint checks. */
100009     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100010         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100011
100012     /* Do FK constraint checks. */
100013     if( hasFK ){
100014       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
100015     }
100016
100017     /* Delete the index entries associated with the current record.  */
100018     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100019     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100020   
100021     /* If changing the record number, delete the old record.  */
100022     if( hasFK || chngRowid ){
100023       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
100024     }
100025     sqlite3VdbeJumpHere(v, j1);
100026
100027     if( hasFK ){
100028       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
100029     }
100030   
100031     /* Insert the new index entries and the new record. */
100032     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100033
100034     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100035     ** handle rows (possibly in other tables) that refer via a foreign key
100036     ** to the row just updated. */ 
100037     if( hasFK ){
100038       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
100039     }
100040   }
100041
100042   /* Increment the row counter 
100043   */
100044   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
100045     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100046   }
100047
100048   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100049       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100050
100051   /* Repeat the above with the next record to be updated, until
100052   ** all record selected by the WHERE clause have been updated.
100053   */
100054   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
100055   sqlite3VdbeJumpHere(v, addr);
100056
100057   /* Close all tables */
100058   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100059     assert( aRegIdx );
100060     if( openAll || aRegIdx[i]>0 ){
100061       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100062     }
100063   }
100064   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
100065
100066   /* Update the sqlite_sequence table by storing the content of the
100067   ** maximum rowid counter values recorded while inserting into
100068   ** autoincrement tables.
100069   */
100070   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100071     sqlite3AutoincrementEnd(pParse);
100072   }
100073
100074   /*
100075   ** Return the number of rows that were changed. If this routine is 
100076   ** generating code because of a call to sqlite3NestedParse(), do not
100077   ** invoke the callback function.
100078   */
100079   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
100080     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100081     sqlite3VdbeSetNumCols(v, 1);
100082     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
100083   }
100084
100085 update_cleanup:
100086   sqlite3AuthContextPop(&sContext);
100087   sqlite3DbFree(db, aRegIdx);
100088   sqlite3DbFree(db, aXRef);
100089   sqlite3SrcListDelete(db, pTabList);
100090   sqlite3ExprListDelete(db, pChanges);
100091   sqlite3ExprDelete(db, pWhere);
100092   return;
100093 }
100094 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100095 ** thely may interfere with compilation of other functions in this file
100096 ** (or in another file, if this file becomes part of the amalgamation).  */
100097 #ifdef isView
100098  #undef isView
100099 #endif
100100 #ifdef pTrigger
100101  #undef pTrigger
100102 #endif
100103
100104 #ifndef SQLITE_OMIT_VIRTUALTABLE
100105 /*
100106 ** Generate code for an UPDATE of a virtual table.
100107 **
100108 ** The strategy is that we create an ephemerial table that contains
100109 ** for each row to be changed:
100110 **
100111 **   (A)  The original rowid of that row.
100112 **   (B)  The revised rowid for the row. (note1)
100113 **   (C)  The content of every column in the row.
100114 **
100115 ** Then we loop over this ephemeral table and for each row in
100116 ** the ephermeral table call VUpdate.
100117 **
100118 ** When finished, drop the ephemeral table.
100119 **
100120 ** (note1) Actually, if we know in advance that (A) is always the same
100121 ** as (B) we only store (A), then duplicate (A) when pulling
100122 ** it out of the ephemeral table before calling VUpdate.
100123 */
100124 static void updateVirtualTable(
100125   Parse *pParse,       /* The parsing context */
100126   SrcList *pSrc,       /* The virtual table to be modified */
100127   Table *pTab,         /* The virtual table */
100128   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100129   Expr *pRowid,        /* Expression used to recompute the rowid */
100130   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100131   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100132   int onError          /* ON CONFLICT strategy */
100133 ){
100134   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
100135   ExprList *pEList = 0;     /* The result set of the SELECT statement */
100136   Select *pSelect = 0;      /* The SELECT statement */
100137   Expr *pExpr;              /* Temporary expression */
100138   int ephemTab;             /* Table holding the result of the SELECT */
100139   int i;                    /* Loop counter */
100140   int addr;                 /* Address of top of loop */
100141   int iReg;                 /* First register in set passed to OP_VUpdate */
100142   sqlite3 *db = pParse->db; /* Database connection */
100143   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
100144   SelectDest dest;
100145
100146   /* Construct the SELECT statement that will find the new values for
100147   ** all updated rows. 
100148   */
100149   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
100150   if( pRowid ){
100151     pEList = sqlite3ExprListAppend(pParse, pEList,
100152                                    sqlite3ExprDup(db, pRowid, 0));
100153   }
100154   assert( pTab->iPKey<0 );
100155   for(i=0; i<pTab->nCol; i++){
100156     if( aXRef[i]>=0 ){
100157       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
100158     }else{
100159       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
100160     }
100161     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
100162   }
100163   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
100164   
100165   /* Create the ephemeral table into which the update results will
100166   ** be stored.
100167   */
100168   assert( v );
100169   ephemTab = pParse->nTab++;
100170   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
100171   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100172
100173   /* fill the ephemeral table 
100174   */
100175   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
100176   sqlite3Select(pParse, pSelect, &dest);
100177
100178   /* Generate code to scan the ephemeral table and call VUpdate. */
100179   iReg = ++pParse->nMem;
100180   pParse->nMem += pTab->nCol+1;
100181   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
100182   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
100183   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
100184   for(i=0; i<pTab->nCol; i++){
100185     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
100186   }
100187   sqlite3VtabMakeWritable(pParse, pTab);
100188   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
100189   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100190   sqlite3MayAbort(pParse);
100191   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
100192   sqlite3VdbeJumpHere(v, addr);
100193   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
100194
100195   /* Cleanup */
100196   sqlite3SelectDelete(db, pSelect);  
100197 }
100198 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100199
100200 /************** End of update.c **********************************************/
100201 /************** Begin file vacuum.c ******************************************/
100202 /*
100203 ** 2003 April 6
100204 **
100205 ** The author disclaims copyright to this source code.  In place of
100206 ** a legal notice, here is a blessing:
100207 **
100208 **    May you do good and not evil.
100209 **    May you find forgiveness for yourself and forgive others.
100210 **    May you share freely, never taking more than you give.
100211 **
100212 *************************************************************************
100213 ** This file contains code used to implement the VACUUM command.
100214 **
100215 ** Most of the code in this file may be omitted by defining the
100216 ** SQLITE_OMIT_VACUUM macro.
100217 */
100218
100219 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
100220 /*
100221 ** Finalize a prepared statement.  If there was an error, store the
100222 ** text of the error message in *pzErrMsg.  Return the result code.
100223 */
100224 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
100225   int rc;
100226   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
100227   if( rc ){
100228     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
100229   }
100230   return rc;
100231 }
100232
100233 /*
100234 ** Execute zSql on database db. Return an error code.
100235 */
100236 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
100237   sqlite3_stmt *pStmt;
100238   VVA_ONLY( int rc; )
100239   if( !zSql ){
100240     return SQLITE_NOMEM;
100241   }
100242   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
100243     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
100244     return sqlite3_errcode(db);
100245   }
100246   VVA_ONLY( rc = ) sqlite3_step(pStmt);
100247   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
100248   return vacuumFinalize(db, pStmt, pzErrMsg);
100249 }
100250
100251 /*
100252 ** Execute zSql on database db. The statement returns exactly
100253 ** one column. Execute this as SQL on the same database.
100254 */
100255 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
100256   sqlite3_stmt *pStmt;
100257   int rc;
100258
100259   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
100260   if( rc!=SQLITE_OK ) return rc;
100261
100262   while( SQLITE_ROW==sqlite3_step(pStmt) ){
100263     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
100264     if( rc!=SQLITE_OK ){
100265       vacuumFinalize(db, pStmt, pzErrMsg);
100266       return rc;
100267     }
100268   }
100269
100270   return vacuumFinalize(db, pStmt, pzErrMsg);
100271 }
100272
100273 /*
100274 ** The non-standard VACUUM command is used to clean up the database,
100275 ** collapse free space, etc.  It is modelled after the VACUUM command
100276 ** in PostgreSQL.
100277 **
100278 ** In version 1.0.x of SQLite, the VACUUM command would call
100279 ** gdbm_reorganize() on all the database tables.  But beginning
100280 ** with 2.0.0, SQLite no longer uses GDBM so this command has
100281 ** become a no-op.
100282 */
100283 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
100284   Vdbe *v = sqlite3GetVdbe(pParse);
100285   if( v ){
100286     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
100287   }
100288   return;
100289 }
100290
100291 /*
100292 ** This routine implements the OP_Vacuum opcode of the VDBE.
100293 */
100294 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
100295   int rc = SQLITE_OK;     /* Return code from service routines */
100296   Btree *pMain;           /* The database being vacuumed */
100297   Btree *pTemp;           /* The temporary database we vacuum into */
100298   char *zSql = 0;         /* SQL statements */
100299   int saved_flags;        /* Saved value of the db->flags */
100300   int saved_nChange;      /* Saved value of db->nChange */
100301   int saved_nTotalChange; /* Saved value of db->nTotalChange */
100302   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
100303   Db *pDb = 0;            /* Database to detach at end of vacuum */
100304   int isMemDb;            /* True if vacuuming a :memory: database */
100305   int nRes;               /* Bytes of reserved space at the end of each page */
100306   int nDb;                /* Number of attached databases */
100307
100308   if( !db->autoCommit ){
100309     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
100310     return SQLITE_ERROR;
100311   }
100312   if( db->activeVdbeCnt>1 ){
100313     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
100314     return SQLITE_ERROR;
100315   }
100316
100317   /* Save the current value of the database flags so that it can be 
100318   ** restored before returning. Then set the writable-schema flag, and
100319   ** disable CHECK and foreign key constraints.  */
100320   saved_flags = db->flags;
100321   saved_nChange = db->nChange;
100322   saved_nTotalChange = db->nTotalChange;
100323   saved_xTrace = db->xTrace;
100324   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
100325   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
100326   db->xTrace = 0;
100327
100328   pMain = db->aDb[0].pBt;
100329   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
100330
100331   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
100332   ** can be set to 'off' for this file, as it is not recovered if a crash
100333   ** occurs anyway. The integrity of the database is maintained by a
100334   ** (possibly synchronous) transaction opened on the main database before
100335   ** sqlite3BtreeCopyFile() is called.
100336   **
100337   ** An optimisation would be to use a non-journaled pager.
100338   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
100339   ** that actually made the VACUUM run slower.  Very little journalling
100340   ** actually occurs when doing a vacuum since the vacuum_db is initially
100341   ** empty.  Only the journal header is written.  Apparently it takes more
100342   ** time to parse and run the PRAGMA to turn journalling off than it does
100343   ** to write the journal header file.
100344   */
100345   nDb = db->nDb;
100346   if( sqlite3TempInMemory(db) ){
100347     zSql = "ATTACH ':memory:' AS vacuum_db;";
100348   }else{
100349     zSql = "ATTACH '' AS vacuum_db;";
100350   }
100351   rc = execSql(db, pzErrMsg, zSql);
100352   if( db->nDb>nDb ){
100353     pDb = &db->aDb[db->nDb-1];
100354     assert( strcmp(pDb->zName,"vacuum_db")==0 );
100355   }
100356   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100357   pTemp = db->aDb[db->nDb-1].pBt;
100358
100359   /* The call to execSql() to attach the temp database has left the file
100360   ** locked (as there was more than one active statement when the transaction
100361   ** to read the schema was concluded. Unlock it here so that this doesn't
100362   ** cause problems for the call to BtreeSetPageSize() below.  */
100363   sqlite3BtreeCommit(pTemp);
100364
100365   nRes = sqlite3BtreeGetReserve(pMain);
100366
100367   /* A VACUUM cannot change the pagesize of an encrypted database. */
100368 #ifdef SQLITE_HAS_CODEC
100369   if( db->nextPagesize ){
100370     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
100371     int nKey;
100372     char *zKey;
100373     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
100374     if( nKey ) db->nextPagesize = 0;
100375   }
100376 #endif
100377
100378   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
100379   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100380
100381   /* Begin a transaction and take an exclusive lock on the main database
100382   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
100383   ** to ensure that we do not try to change the page-size on a WAL database.
100384   */
100385   rc = execSql(db, pzErrMsg, "BEGIN;");
100386   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100387   rc = sqlite3BtreeBeginTrans(pMain, 2);
100388   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100389
100390   /* Do not attempt to change the page size for a WAL database */
100391   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
100392                                                ==PAGER_JOURNALMODE_WAL ){
100393     db->nextPagesize = 0;
100394   }
100395
100396   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
100397    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
100398    || NEVER(db->mallocFailed)
100399   ){
100400     rc = SQLITE_NOMEM;
100401     goto end_of_vacuum;
100402   }
100403
100404 #ifndef SQLITE_OMIT_AUTOVACUUM
100405   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
100406                                            sqlite3BtreeGetAutoVacuum(pMain));
100407 #endif
100408
100409   /* Query the schema of the main database. Create a mirror schema
100410   ** in the temporary database.
100411   */
100412   rc = execExecSql(db, pzErrMsg,
100413       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
100414       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
100415       "   AND rootpage>0"
100416   );
100417   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100418   rc = execExecSql(db, pzErrMsg,
100419       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
100420       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
100421   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100422   rc = execExecSql(db, pzErrMsg,
100423       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
100424       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
100425   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100426
100427   /* Loop through the tables in the main database. For each, do
100428   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
100429   ** the contents to the temporary database.
100430   */
100431   rc = execExecSql(db, pzErrMsg,
100432       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
100433       "|| ' SELECT * FROM main.' || quote(name) || ';'"
100434       "FROM main.sqlite_master "
100435       "WHERE type = 'table' AND name!='sqlite_sequence' "
100436       "  AND rootpage>0"
100437   );
100438   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100439
100440   /* Copy over the sequence table
100441   */
100442   rc = execExecSql(db, pzErrMsg,
100443       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
100444       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
100445   );
100446   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100447   rc = execExecSql(db, pzErrMsg,
100448       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
100449       "|| ' SELECT * FROM main.' || quote(name) || ';' "
100450       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
100451   );
100452   if( rc!=SQLITE_OK ) goto end_of_vacuum;
100453
100454
100455   /* Copy the triggers, views, and virtual tables from the main database
100456   ** over to the temporary database.  None of these objects has any
100457   ** associated storage, so all we have to do is copy their entries
100458   ** from the SQLITE_MASTER table.
100459   */
100460   rc = execSql(db, pzErrMsg,
100461       "INSERT INTO vacuum_db.sqlite_master "
100462       "  SELECT type, name, tbl_name, rootpage, sql"
100463       "    FROM main.sqlite_master"
100464       "   WHERE type='view' OR type='trigger'"
100465       "      OR (type='table' AND rootpage=0)"
100466   );
100467   if( rc ) goto end_of_vacuum;
100468
100469   /* At this point, there is a write transaction open on both the 
100470   ** vacuum database and the main database. Assuming no error occurs,
100471   ** both transactions are closed by this block - the main database
100472   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
100473   ** call to sqlite3BtreeCommit().
100474   */
100475   {
100476     u32 meta;
100477     int i;
100478
100479     /* This array determines which meta meta values are preserved in the
100480     ** vacuum.  Even entries are the meta value number and odd entries
100481     ** are an increment to apply to the meta value after the vacuum.
100482     ** The increment is used to increase the schema cookie so that other
100483     ** connections to the same database will know to reread the schema.
100484     */
100485     static const unsigned char aCopy[] = {
100486        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
100487        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
100488        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
100489        BTREE_USER_VERSION,       0,  /* Preserve the user version */
100490     };
100491
100492     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
100493     assert( 1==sqlite3BtreeIsInTrans(pMain) );
100494
100495     /* Copy Btree meta values */
100496     for(i=0; i<ArraySize(aCopy); i+=2){
100497       /* GetMeta() and UpdateMeta() cannot fail in this context because
100498       ** we already have page 1 loaded into cache and marked dirty. */
100499       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
100500       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
100501       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
100502     }
100503
100504     rc = sqlite3BtreeCopyFile(pMain, pTemp);
100505     if( rc!=SQLITE_OK ) goto end_of_vacuum;
100506     rc = sqlite3BtreeCommit(pTemp);
100507     if( rc!=SQLITE_OK ) goto end_of_vacuum;
100508 #ifndef SQLITE_OMIT_AUTOVACUUM
100509     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
100510 #endif
100511   }
100512
100513   assert( rc==SQLITE_OK );
100514   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
100515
100516 end_of_vacuum:
100517   /* Restore the original value of db->flags */
100518   db->flags = saved_flags;
100519   db->nChange = saved_nChange;
100520   db->nTotalChange = saved_nTotalChange;
100521   db->xTrace = saved_xTrace;
100522   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
100523
100524   /* Currently there is an SQL level transaction open on the vacuum
100525   ** database. No locks are held on any other files (since the main file
100526   ** was committed at the btree level). So it safe to end the transaction
100527   ** by manually setting the autoCommit flag to true and detaching the
100528   ** vacuum database. The vacuum_db journal file is deleted when the pager
100529   ** is closed by the DETACH.
100530   */
100531   db->autoCommit = 1;
100532
100533   if( pDb ){
100534     sqlite3BtreeClose(pDb->pBt);
100535     pDb->pBt = 0;
100536     pDb->pSchema = 0;
100537   }
100538
100539   /* This both clears the schemas and reduces the size of the db->aDb[]
100540   ** array. */ 
100541   sqlite3ResetAllSchemasOfConnection(db);
100542
100543   return rc;
100544 }
100545
100546 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
100547
100548 /************** End of vacuum.c **********************************************/
100549 /************** Begin file vtab.c ********************************************/
100550 /*
100551 ** 2006 June 10
100552 **
100553 ** The author disclaims copyright to this source code.  In place of
100554 ** a legal notice, here is a blessing:
100555 **
100556 **    May you do good and not evil.
100557 **    May you find forgiveness for yourself and forgive others.
100558 **    May you share freely, never taking more than you give.
100559 **
100560 *************************************************************************
100561 ** This file contains code used to help implement virtual tables.
100562 */
100563 #ifndef SQLITE_OMIT_VIRTUALTABLE
100564
100565 /*
100566 ** Before a virtual table xCreate() or xConnect() method is invoked, the
100567 ** sqlite3.pVtabCtx member variable is set to point to an instance of
100568 ** this struct allocated on the stack. It is used by the implementation of 
100569 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
100570 ** are invoked only from within xCreate and xConnect methods.
100571 */
100572 struct VtabCtx {
100573   VTable *pVTable;    /* The virtual table being constructed */
100574   Table *pTab;        /* The Table object to which the virtual table belongs */
100575 };
100576
100577 /*
100578 ** The actual function that does the work of creating a new module.
100579 ** This function implements the sqlite3_create_module() and
100580 ** sqlite3_create_module_v2() interfaces.
100581 */
100582 static int createModule(
100583   sqlite3 *db,                    /* Database in which module is registered */
100584   const char *zName,              /* Name assigned to this module */
100585   const sqlite3_module *pModule,  /* The definition of the module */
100586   void *pAux,                     /* Context pointer for xCreate/xConnect */
100587   void (*xDestroy)(void *)        /* Module destructor function */
100588 ){
100589   int rc = SQLITE_OK;
100590   int nName;
100591
100592   sqlite3_mutex_enter(db->mutex);
100593   nName = sqlite3Strlen30(zName);
100594   if( sqlite3HashFind(&db->aModule, zName, nName) ){
100595     rc = SQLITE_MISUSE_BKPT;
100596   }else{
100597     Module *pMod;
100598     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
100599     if( pMod ){
100600       Module *pDel;
100601       char *zCopy = (char *)(&pMod[1]);
100602       memcpy(zCopy, zName, nName+1);
100603       pMod->zName = zCopy;
100604       pMod->pModule = pModule;
100605       pMod->pAux = pAux;
100606       pMod->xDestroy = xDestroy;
100607       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
100608       assert( pDel==0 || pDel==pMod );
100609       if( pDel ){
100610         db->mallocFailed = 1;
100611         sqlite3DbFree(db, pDel);
100612       }
100613     }
100614   }
100615   rc = sqlite3ApiExit(db, rc);
100616   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
100617
100618   sqlite3_mutex_leave(db->mutex);
100619   return rc;
100620 }
100621
100622
100623 /*
100624 ** External API function used to create a new virtual-table module.
100625 */
100626 SQLITE_API int sqlite3_create_module(
100627   sqlite3 *db,                    /* Database in which module is registered */
100628   const char *zName,              /* Name assigned to this module */
100629   const sqlite3_module *pModule,  /* The definition of the module */
100630   void *pAux                      /* Context pointer for xCreate/xConnect */
100631 ){
100632   return createModule(db, zName, pModule, pAux, 0);
100633 }
100634
100635 /*
100636 ** External API function used to create a new virtual-table module.
100637 */
100638 SQLITE_API int sqlite3_create_module_v2(
100639   sqlite3 *db,                    /* Database in which module is registered */
100640   const char *zName,              /* Name assigned to this module */
100641   const sqlite3_module *pModule,  /* The definition of the module */
100642   void *pAux,                     /* Context pointer for xCreate/xConnect */
100643   void (*xDestroy)(void *)        /* Module destructor function */
100644 ){
100645   return createModule(db, zName, pModule, pAux, xDestroy);
100646 }
100647
100648 /*
100649 ** Lock the virtual table so that it cannot be disconnected.
100650 ** Locks nest.  Every lock should have a corresponding unlock.
100651 ** If an unlock is omitted, resources leaks will occur.  
100652 **
100653 ** If a disconnect is attempted while a virtual table is locked,
100654 ** the disconnect is deferred until all locks have been removed.
100655 */
100656 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
100657   pVTab->nRef++;
100658 }
100659
100660
100661 /*
100662 ** pTab is a pointer to a Table structure representing a virtual-table.
100663 ** Return a pointer to the VTable object used by connection db to access 
100664 ** this virtual-table, if one has been created, or NULL otherwise.
100665 */
100666 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
100667   VTable *pVtab;
100668   assert( IsVirtual(pTab) );
100669   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
100670   return pVtab;
100671 }
100672
100673 /*
100674 ** Decrement the ref-count on a virtual table object. When the ref-count
100675 ** reaches zero, call the xDisconnect() method to delete the object.
100676 */
100677 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
100678   sqlite3 *db = pVTab->db;
100679
100680   assert( db );
100681   assert( pVTab->nRef>0 );
100682   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
100683
100684   pVTab->nRef--;
100685   if( pVTab->nRef==0 ){
100686     sqlite3_vtab *p = pVTab->pVtab;
100687     if( p ){
100688       p->pModule->xDisconnect(p);
100689     }
100690     sqlite3DbFree(db, pVTab);
100691   }
100692 }
100693
100694 /*
100695 ** Table p is a virtual table. This function moves all elements in the
100696 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
100697 ** database connections to be disconnected at the next opportunity. 
100698 ** Except, if argument db is not NULL, then the entry associated with
100699 ** connection db is left in the p->pVTable list.
100700 */
100701 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
100702   VTable *pRet = 0;
100703   VTable *pVTable = p->pVTable;
100704   p->pVTable = 0;
100705
100706   /* Assert that the mutex (if any) associated with the BtShared database 
100707   ** that contains table p is held by the caller. See header comments 
100708   ** above function sqlite3VtabUnlockList() for an explanation of why
100709   ** this makes it safe to access the sqlite3.pDisconnect list of any
100710   ** database connection that may have an entry in the p->pVTable list.
100711   */
100712   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
100713
100714   while( pVTable ){
100715     sqlite3 *db2 = pVTable->db;
100716     VTable *pNext = pVTable->pNext;
100717     assert( db2 );
100718     if( db2==db ){
100719       pRet = pVTable;
100720       p->pVTable = pRet;
100721       pRet->pNext = 0;
100722     }else{
100723       pVTable->pNext = db2->pDisconnect;
100724       db2->pDisconnect = pVTable;
100725     }
100726     pVTable = pNext;
100727   }
100728
100729   assert( !db || pRet );
100730   return pRet;
100731 }
100732
100733 /*
100734 ** Table *p is a virtual table. This function removes the VTable object
100735 ** for table *p associated with database connection db from the linked
100736 ** list in p->pVTab. It also decrements the VTable ref count. This is
100737 ** used when closing database connection db to free all of its VTable
100738 ** objects without disturbing the rest of the Schema object (which may
100739 ** be being used by other shared-cache connections).
100740 */
100741 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
100742   VTable **ppVTab;
100743
100744   assert( IsVirtual(p) );
100745   assert( sqlite3BtreeHoldsAllMutexes(db) );
100746   assert( sqlite3_mutex_held(db->mutex) );
100747
100748   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
100749     if( (*ppVTab)->db==db  ){
100750       VTable *pVTab = *ppVTab;
100751       *ppVTab = pVTab->pNext;
100752       sqlite3VtabUnlock(pVTab);
100753       break;
100754     }
100755   }
100756 }
100757
100758
100759 /*
100760 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
100761 **
100762 ** This function may only be called when the mutexes associated with all
100763 ** shared b-tree databases opened using connection db are held by the 
100764 ** caller. This is done to protect the sqlite3.pDisconnect list. The
100765 ** sqlite3.pDisconnect list is accessed only as follows:
100766 **
100767 **   1) By this function. In this case, all BtShared mutexes and the mutex
100768 **      associated with the database handle itself must be held.
100769 **
100770 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
100771 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
100772 **      associated with the database the virtual table is stored in is held
100773 **      or, if the virtual table is stored in a non-sharable database, then
100774 **      the database handle mutex is held.
100775 **
100776 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
100777 ** by multiple threads. It is thread-safe.
100778 */
100779 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
100780   VTable *p = db->pDisconnect;
100781   db->pDisconnect = 0;
100782
100783   assert( sqlite3BtreeHoldsAllMutexes(db) );
100784   assert( sqlite3_mutex_held(db->mutex) );
100785
100786   if( p ){
100787     sqlite3ExpirePreparedStatements(db);
100788     do {
100789       VTable *pNext = p->pNext;
100790       sqlite3VtabUnlock(p);
100791       p = pNext;
100792     }while( p );
100793   }
100794 }
100795
100796 /*
100797 ** Clear any and all virtual-table information from the Table record.
100798 ** This routine is called, for example, just before deleting the Table
100799 ** record.
100800 **
100801 ** Since it is a virtual-table, the Table structure contains a pointer
100802 ** to the head of a linked list of VTable structures. Each VTable 
100803 ** structure is associated with a single sqlite3* user of the schema.
100804 ** The reference count of the VTable structure associated with database 
100805 ** connection db is decremented immediately (which may lead to the 
100806 ** structure being xDisconnected and free). Any other VTable structures
100807 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
100808 ** database connection.
100809 */
100810 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
100811   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
100812   if( p->azModuleArg ){
100813     int i;
100814     for(i=0; i<p->nModuleArg; i++){
100815       sqlite3DbFree(db, p->azModuleArg[i]);
100816     }
100817     sqlite3DbFree(db, p->azModuleArg);
100818   }
100819 }
100820
100821 /*
100822 ** Add a new module argument to pTable->azModuleArg[].
100823 ** The string is not copied - the pointer is stored.  The
100824 ** string will be freed automatically when the table is
100825 ** deleted.
100826 */
100827 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
100828   int i = pTable->nModuleArg++;
100829   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
100830   char **azModuleArg;
100831   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
100832   if( azModuleArg==0 ){
100833     int j;
100834     for(j=0; j<i; j++){
100835       sqlite3DbFree(db, pTable->azModuleArg[j]);
100836     }
100837     sqlite3DbFree(db, zArg);
100838     sqlite3DbFree(db, pTable->azModuleArg);
100839     pTable->nModuleArg = 0;
100840   }else{
100841     azModuleArg[i] = zArg;
100842     azModuleArg[i+1] = 0;
100843   }
100844   pTable->azModuleArg = azModuleArg;
100845 }
100846
100847 /*
100848 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
100849 ** statement.  The module name has been parsed, but the optional list
100850 ** of parameters that follow the module name are still pending.
100851 */
100852 SQLITE_PRIVATE void sqlite3VtabBeginParse(
100853   Parse *pParse,        /* Parsing context */
100854   Token *pName1,        /* Name of new table, or database name */
100855   Token *pName2,        /* Name of new table or NULL */
100856   Token *pModuleName,   /* Name of the module for the virtual table */
100857   int ifNotExists       /* No error if the table already exists */
100858 ){
100859   int iDb;              /* The database the table is being created in */
100860   Table *pTable;        /* The new virtual table */
100861   sqlite3 *db;          /* Database connection */
100862
100863   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
100864   pTable = pParse->pNewTable;
100865   if( pTable==0 ) return;
100866   assert( 0==pTable->pIndex );
100867
100868   db = pParse->db;
100869   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
100870   assert( iDb>=0 );
100871
100872   pTable->tabFlags |= TF_Virtual;
100873   pTable->nModuleArg = 0;
100874   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
100875   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
100876   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
100877   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
100878
100879 #ifndef SQLITE_OMIT_AUTHORIZATION
100880   /* Creating a virtual table invokes the authorization callback twice.
100881   ** The first invocation, to obtain permission to INSERT a row into the
100882   ** sqlite_master table, has already been made by sqlite3StartTable().
100883   ** The second call, to obtain permission to create the table, is made now.
100884   */
100885   if( pTable->azModuleArg ){
100886     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
100887             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
100888   }
100889 #endif
100890 }
100891
100892 /*
100893 ** This routine takes the module argument that has been accumulating
100894 ** in pParse->zArg[] and appends it to the list of arguments on the
100895 ** virtual table currently under construction in pParse->pTable.
100896 */
100897 static void addArgumentToVtab(Parse *pParse){
100898   if( pParse->sArg.z && pParse->pNewTable ){
100899     const char *z = (const char*)pParse->sArg.z;
100900     int n = pParse->sArg.n;
100901     sqlite3 *db = pParse->db;
100902     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
100903   }
100904 }
100905
100906 /*
100907 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
100908 ** has been completely parsed.
100909 */
100910 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
100911   Table *pTab = pParse->pNewTable;  /* The table being constructed */
100912   sqlite3 *db = pParse->db;         /* The database connection */
100913
100914   if( pTab==0 ) return;
100915   addArgumentToVtab(pParse);
100916   pParse->sArg.z = 0;
100917   if( pTab->nModuleArg<1 ) return;
100918   
100919   /* If the CREATE VIRTUAL TABLE statement is being entered for the
100920   ** first time (in other words if the virtual table is actually being
100921   ** created now instead of just being read out of sqlite_master) then
100922   ** do additional initialization work and store the statement text
100923   ** in the sqlite_master table.
100924   */
100925   if( !db->init.busy ){
100926     char *zStmt;
100927     char *zWhere;
100928     int iDb;
100929     Vdbe *v;
100930
100931     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
100932     if( pEnd ){
100933       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
100934     }
100935     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
100936
100937     /* A slot for the record has already been allocated in the 
100938     ** SQLITE_MASTER table.  We just need to update that slot with all
100939     ** the information we've collected.  
100940     **
100941     ** The VM register number pParse->regRowid holds the rowid of an
100942     ** entry in the sqlite_master table tht was created for this vtab
100943     ** by sqlite3StartTable().
100944     */
100945     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100946     sqlite3NestedParse(pParse,
100947       "UPDATE %Q.%s "
100948          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
100949        "WHERE rowid=#%d",
100950       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100951       pTab->zName,
100952       pTab->zName,
100953       zStmt,
100954       pParse->regRowid
100955     );
100956     sqlite3DbFree(db, zStmt);
100957     v = sqlite3GetVdbe(pParse);
100958     sqlite3ChangeCookie(pParse, iDb);
100959
100960     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
100961     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
100962     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
100963     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
100964                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
100965   }
100966
100967   /* If we are rereading the sqlite_master table create the in-memory
100968   ** record of the table. The xConnect() method is not called until
100969   ** the first time the virtual table is used in an SQL statement. This
100970   ** allows a schema that contains virtual tables to be loaded before
100971   ** the required virtual table implementations are registered.  */
100972   else {
100973     Table *pOld;
100974     Schema *pSchema = pTab->pSchema;
100975     const char *zName = pTab->zName;
100976     int nName = sqlite3Strlen30(zName);
100977     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
100978     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
100979     if( pOld ){
100980       db->mallocFailed = 1;
100981       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
100982       return;
100983     }
100984     pParse->pNewTable = 0;
100985   }
100986 }
100987
100988 /*
100989 ** The parser calls this routine when it sees the first token
100990 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
100991 */
100992 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
100993   addArgumentToVtab(pParse);
100994   pParse->sArg.z = 0;
100995   pParse->sArg.n = 0;
100996 }
100997
100998 /*
100999 ** The parser calls this routine for each token after the first token
101000 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101001 */
101002 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
101003   Token *pArg = &pParse->sArg;
101004   if( pArg->z==0 ){
101005     pArg->z = p->z;
101006     pArg->n = p->n;
101007   }else{
101008     assert(pArg->z < p->z);
101009     pArg->n = (int)(&p->z[p->n] - pArg->z);
101010   }
101011 }
101012
101013 /*
101014 ** Invoke a virtual table constructor (either xCreate or xConnect). The
101015 ** pointer to the function to invoke is passed as the fourth parameter
101016 ** to this procedure.
101017 */
101018 static int vtabCallConstructor(
101019   sqlite3 *db, 
101020   Table *pTab,
101021   Module *pMod,
101022   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
101023   char **pzErr
101024 ){
101025   VtabCtx sCtx, *pPriorCtx;
101026   VTable *pVTable;
101027   int rc;
101028   const char *const*azArg = (const char *const*)pTab->azModuleArg;
101029   int nArg = pTab->nModuleArg;
101030   char *zErr = 0;
101031   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
101032
101033   if( !zModuleName ){
101034     return SQLITE_NOMEM;
101035   }
101036
101037   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
101038   if( !pVTable ){
101039     sqlite3DbFree(db, zModuleName);
101040     return SQLITE_NOMEM;
101041   }
101042   pVTable->db = db;
101043   pVTable->pMod = pMod;
101044
101045   /* Invoke the virtual table constructor */
101046   assert( &db->pVtabCtx );
101047   assert( xConstruct );
101048   sCtx.pTab = pTab;
101049   sCtx.pVTable = pVTable;
101050   pPriorCtx = db->pVtabCtx;
101051   db->pVtabCtx = &sCtx;
101052   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101053   db->pVtabCtx = pPriorCtx;
101054   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
101055
101056   if( SQLITE_OK!=rc ){
101057     if( zErr==0 ){
101058       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101059     }else {
101060       *pzErr = sqlite3MPrintf(db, "%s", zErr);
101061       sqlite3_free(zErr);
101062     }
101063     sqlite3DbFree(db, pVTable);
101064   }else if( ALWAYS(pVTable->pVtab) ){
101065     /* Justification of ALWAYS():  A correct vtab constructor must allocate
101066     ** the sqlite3_vtab object if successful.  */
101067     pVTable->pVtab->pModule = pMod->pModule;
101068     pVTable->nRef = 1;
101069     if( sCtx.pTab ){
101070       const char *zFormat = "vtable constructor did not declare schema: %s";
101071       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
101072       sqlite3VtabUnlock(pVTable);
101073       rc = SQLITE_ERROR;
101074     }else{
101075       int iCol;
101076       /* If everything went according to plan, link the new VTable structure
101077       ** into the linked list headed by pTab->pVTable. Then loop through the 
101078       ** columns of the table to see if any of them contain the token "hidden".
101079       ** If so, set the Column.isHidden flag and remove the token from
101080       ** the type string.  */
101081       pVTable->pNext = pTab->pVTable;
101082       pTab->pVTable = pVTable;
101083
101084       for(iCol=0; iCol<pTab->nCol; iCol++){
101085         char *zType = pTab->aCol[iCol].zType;
101086         int nType;
101087         int i = 0;
101088         if( !zType ) continue;
101089         nType = sqlite3Strlen30(zType);
101090         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101091           for(i=0; i<nType; i++){
101092             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
101093              && (zType[i+7]=='\0' || zType[i+7]==' ')
101094             ){
101095               i++;
101096               break;
101097             }
101098           }
101099         }
101100         if( i<nType ){
101101           int j;
101102           int nDel = 6 + (zType[i+6] ? 1 : 0);
101103           for(j=i; (j+nDel)<=nType; j++){
101104             zType[j] = zType[j+nDel];
101105           }
101106           if( zType[i]=='\0' && i>0 ){
101107             assert(zType[i-1]==' ');
101108             zType[i-1] = '\0';
101109           }
101110           pTab->aCol[iCol].isHidden = 1;
101111         }
101112       }
101113     }
101114   }
101115
101116   sqlite3DbFree(db, zModuleName);
101117   return rc;
101118 }
101119
101120 /*
101121 ** This function is invoked by the parser to call the xConnect() method
101122 ** of the virtual table pTab. If an error occurs, an error code is returned 
101123 ** and an error left in pParse.
101124 **
101125 ** This call is a no-op if table pTab is not a virtual table.
101126 */
101127 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
101128   sqlite3 *db = pParse->db;
101129   const char *zMod;
101130   Module *pMod;
101131   int rc;
101132
101133   assert( pTab );
101134   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
101135     return SQLITE_OK;
101136   }
101137
101138   /* Locate the required virtual table module */
101139   zMod = pTab->azModuleArg[0];
101140   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
101141
101142   if( !pMod ){
101143     const char *zModule = pTab->azModuleArg[0];
101144     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
101145     rc = SQLITE_ERROR;
101146   }else{
101147     char *zErr = 0;
101148     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
101149     if( rc!=SQLITE_OK ){
101150       sqlite3ErrorMsg(pParse, "%s", zErr);
101151     }
101152     sqlite3DbFree(db, zErr);
101153   }
101154
101155   return rc;
101156 }
101157 /*
101158 ** Grow the db->aVTrans[] array so that there is room for at least one
101159 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
101160 */
101161 static int growVTrans(sqlite3 *db){
101162   const int ARRAY_INCR = 5;
101163
101164   /* Grow the sqlite3.aVTrans array if required */
101165   if( (db->nVTrans%ARRAY_INCR)==0 ){
101166     VTable **aVTrans;
101167     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
101168     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
101169     if( !aVTrans ){
101170       return SQLITE_NOMEM;
101171     }
101172     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
101173     db->aVTrans = aVTrans;
101174   }
101175
101176   return SQLITE_OK;
101177 }
101178
101179 /*
101180 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
101181 ** have already been reserved using growVTrans().
101182 */
101183 static void addToVTrans(sqlite3 *db, VTable *pVTab){
101184   /* Add pVtab to the end of sqlite3.aVTrans */
101185   db->aVTrans[db->nVTrans++] = pVTab;
101186   sqlite3VtabLock(pVTab);
101187 }
101188
101189 /*
101190 ** This function is invoked by the vdbe to call the xCreate method
101191 ** of the virtual table named zTab in database iDb. 
101192 **
101193 ** If an error occurs, *pzErr is set to point an an English language
101194 ** description of the error and an SQLITE_XXX error code is returned.
101195 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
101196 */
101197 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
101198   int rc = SQLITE_OK;
101199   Table *pTab;
101200   Module *pMod;
101201   const char *zMod;
101202
101203   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
101204   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
101205
101206   /* Locate the required virtual table module */
101207   zMod = pTab->azModuleArg[0];
101208   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
101209
101210   /* If the module has been registered and includes a Create method, 
101211   ** invoke it now. If the module has not been registered, return an 
101212   ** error. Otherwise, do nothing.
101213   */
101214   if( !pMod ){
101215     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
101216     rc = SQLITE_ERROR;
101217   }else{
101218     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
101219   }
101220
101221   /* Justification of ALWAYS():  The xConstructor method is required to
101222   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
101223   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
101224     rc = growVTrans(db);
101225     if( rc==SQLITE_OK ){
101226       addToVTrans(db, sqlite3GetVTable(db, pTab));
101227     }
101228   }
101229
101230   return rc;
101231 }
101232
101233 /*
101234 ** This function is used to set the schema of a virtual table.  It is only
101235 ** valid to call this function from within the xCreate() or xConnect() of a
101236 ** virtual table module.
101237 */
101238 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
101239   Parse *pParse;
101240
101241   int rc = SQLITE_OK;
101242   Table *pTab;
101243   char *zErr = 0;
101244
101245   sqlite3_mutex_enter(db->mutex);
101246   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
101247     sqlite3Error(db, SQLITE_MISUSE, 0);
101248     sqlite3_mutex_leave(db->mutex);
101249     return SQLITE_MISUSE_BKPT;
101250   }
101251   assert( (pTab->tabFlags & TF_Virtual)!=0 );
101252
101253   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
101254   if( pParse==0 ){
101255     rc = SQLITE_NOMEM;
101256   }else{
101257     pParse->declareVtab = 1;
101258     pParse->db = db;
101259     pParse->nQueryLoop = 1;
101260   
101261     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
101262      && pParse->pNewTable
101263      && !db->mallocFailed
101264      && !pParse->pNewTable->pSelect
101265      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
101266     ){
101267       if( !pTab->aCol ){
101268         pTab->aCol = pParse->pNewTable->aCol;
101269         pTab->nCol = pParse->pNewTable->nCol;
101270         pParse->pNewTable->nCol = 0;
101271         pParse->pNewTable->aCol = 0;
101272       }
101273       db->pVtabCtx->pTab = 0;
101274     }else{
101275       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
101276       sqlite3DbFree(db, zErr);
101277       rc = SQLITE_ERROR;
101278     }
101279     pParse->declareVtab = 0;
101280   
101281     if( pParse->pVdbe ){
101282       sqlite3VdbeFinalize(pParse->pVdbe);
101283     }
101284     sqlite3DeleteTable(db, pParse->pNewTable);
101285     sqlite3StackFree(db, pParse);
101286   }
101287
101288   assert( (rc&0xff)==rc );
101289   rc = sqlite3ApiExit(db, rc);
101290   sqlite3_mutex_leave(db->mutex);
101291   return rc;
101292 }
101293
101294 /*
101295 ** This function is invoked by the vdbe to call the xDestroy method
101296 ** of the virtual table named zTab in database iDb. This occurs
101297 ** when a DROP TABLE is mentioned.
101298 **
101299 ** This call is a no-op if zTab is not a virtual table.
101300 */
101301 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
101302   int rc = SQLITE_OK;
101303   Table *pTab;
101304
101305   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
101306   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
101307     VTable *p = vtabDisconnectAll(db, pTab);
101308
101309     assert( rc==SQLITE_OK );
101310     rc = p->pMod->pModule->xDestroy(p->pVtab);
101311
101312     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
101313     if( rc==SQLITE_OK ){
101314       assert( pTab->pVTable==p && p->pNext==0 );
101315       p->pVtab = 0;
101316       pTab->pVTable = 0;
101317       sqlite3VtabUnlock(p);
101318     }
101319   }
101320
101321   return rc;
101322 }
101323
101324 /*
101325 ** This function invokes either the xRollback or xCommit method
101326 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
101327 ** called is identified by the second argument, "offset", which is
101328 ** the offset of the method to call in the sqlite3_module structure.
101329 **
101330 ** The array is cleared after invoking the callbacks. 
101331 */
101332 static void callFinaliser(sqlite3 *db, int offset){
101333   int i;
101334   if( db->aVTrans ){
101335     for(i=0; i<db->nVTrans; i++){
101336       VTable *pVTab = db->aVTrans[i];
101337       sqlite3_vtab *p = pVTab->pVtab;
101338       if( p ){
101339         int (*x)(sqlite3_vtab *);
101340         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
101341         if( x ) x(p);
101342       }
101343       pVTab->iSavepoint = 0;
101344       sqlite3VtabUnlock(pVTab);
101345     }
101346     sqlite3DbFree(db, db->aVTrans);
101347     db->nVTrans = 0;
101348     db->aVTrans = 0;
101349   }
101350 }
101351
101352 /*
101353 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
101354 ** array. Return the error code for the first error that occurs, or
101355 ** SQLITE_OK if all xSync operations are successful.
101356 **
101357 ** Set *pzErrmsg to point to a buffer that should be released using 
101358 ** sqlite3DbFree() containing an error message, if one is available.
101359 */
101360 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
101361   int i;
101362   int rc = SQLITE_OK;
101363   VTable **aVTrans = db->aVTrans;
101364
101365   db->aVTrans = 0;
101366   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
101367     int (*x)(sqlite3_vtab *);
101368     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
101369     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
101370       rc = x(pVtab);
101371       sqlite3DbFree(db, *pzErrmsg);
101372       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
101373       sqlite3_free(pVtab->zErrMsg);
101374     }
101375   }
101376   db->aVTrans = aVTrans;
101377   return rc;
101378 }
101379
101380 /*
101381 ** Invoke the xRollback method of all virtual tables in the 
101382 ** sqlite3.aVTrans array. Then clear the array itself.
101383 */
101384 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
101385   callFinaliser(db, offsetof(sqlite3_module,xRollback));
101386   return SQLITE_OK;
101387 }
101388
101389 /*
101390 ** Invoke the xCommit method of all virtual tables in the 
101391 ** sqlite3.aVTrans array. Then clear the array itself.
101392 */
101393 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
101394   callFinaliser(db, offsetof(sqlite3_module,xCommit));
101395   return SQLITE_OK;
101396 }
101397
101398 /*
101399 ** If the virtual table pVtab supports the transaction interface
101400 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
101401 ** not currently open, invoke the xBegin method now.
101402 **
101403 ** If the xBegin call is successful, place the sqlite3_vtab pointer
101404 ** in the sqlite3.aVTrans array.
101405 */
101406 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
101407   int rc = SQLITE_OK;
101408   const sqlite3_module *pModule;
101409
101410   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
101411   ** than zero, then this function is being called from within a
101412   ** virtual module xSync() callback. It is illegal to write to 
101413   ** virtual module tables in this case, so return SQLITE_LOCKED.
101414   */
101415   if( sqlite3VtabInSync(db) ){
101416     return SQLITE_LOCKED;
101417   }
101418   if( !pVTab ){
101419     return SQLITE_OK;
101420   } 
101421   pModule = pVTab->pVtab->pModule;
101422
101423   if( pModule->xBegin ){
101424     int i;
101425
101426     /* If pVtab is already in the aVTrans array, return early */
101427     for(i=0; i<db->nVTrans; i++){
101428       if( db->aVTrans[i]==pVTab ){
101429         return SQLITE_OK;
101430       }
101431     }
101432
101433     /* Invoke the xBegin method. If successful, add the vtab to the 
101434     ** sqlite3.aVTrans[] array. */
101435     rc = growVTrans(db);
101436     if( rc==SQLITE_OK ){
101437       rc = pModule->xBegin(pVTab->pVtab);
101438       if( rc==SQLITE_OK ){
101439         addToVTrans(db, pVTab);
101440       }
101441     }
101442   }
101443   return rc;
101444 }
101445
101446 /*
101447 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
101448 ** virtual tables that currently have an open transaction. Pass iSavepoint
101449 ** as the second argument to the virtual table method invoked.
101450 **
101451 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
101452 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
101453 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
101454 ** an open transaction is invoked.
101455 **
101456 ** If any virtual table method returns an error code other than SQLITE_OK, 
101457 ** processing is abandoned and the error returned to the caller of this
101458 ** function immediately. If all calls to virtual table methods are successful,
101459 ** SQLITE_OK is returned.
101460 */
101461 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
101462   int rc = SQLITE_OK;
101463
101464   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
101465   assert( iSavepoint>=0 );
101466   if( db->aVTrans ){
101467     int i;
101468     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
101469       VTable *pVTab = db->aVTrans[i];
101470       const sqlite3_module *pMod = pVTab->pMod->pModule;
101471       if( pVTab->pVtab && pMod->iVersion>=2 ){
101472         int (*xMethod)(sqlite3_vtab *, int);
101473         switch( op ){
101474           case SAVEPOINT_BEGIN:
101475             xMethod = pMod->xSavepoint;
101476             pVTab->iSavepoint = iSavepoint+1;
101477             break;
101478           case SAVEPOINT_ROLLBACK:
101479             xMethod = pMod->xRollbackTo;
101480             break;
101481           default:
101482             xMethod = pMod->xRelease;
101483             break;
101484         }
101485         if( xMethod && pVTab->iSavepoint>iSavepoint ){
101486           rc = xMethod(pVTab->pVtab, iSavepoint);
101487         }
101488       }
101489     }
101490   }
101491   return rc;
101492 }
101493
101494 /*
101495 ** The first parameter (pDef) is a function implementation.  The
101496 ** second parameter (pExpr) is the first argument to this function.
101497 ** If pExpr is a column in a virtual table, then let the virtual
101498 ** table implementation have an opportunity to overload the function.
101499 **
101500 ** This routine is used to allow virtual table implementations to
101501 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
101502 **
101503 ** Return either the pDef argument (indicating no change) or a 
101504 ** new FuncDef structure that is marked as ephemeral using the
101505 ** SQLITE_FUNC_EPHEM flag.
101506 */
101507 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
101508   sqlite3 *db,    /* Database connection for reporting malloc problems */
101509   FuncDef *pDef,  /* Function to possibly overload */
101510   int nArg,       /* Number of arguments to the function */
101511   Expr *pExpr     /* First argument to the function */
101512 ){
101513   Table *pTab;
101514   sqlite3_vtab *pVtab;
101515   sqlite3_module *pMod;
101516   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
101517   void *pArg = 0;
101518   FuncDef *pNew;
101519   int rc = 0;
101520   char *zLowerName;
101521   unsigned char *z;
101522
101523
101524   /* Check to see the left operand is a column in a virtual table */
101525   if( NEVER(pExpr==0) ) return pDef;
101526   if( pExpr->op!=TK_COLUMN ) return pDef;
101527   pTab = pExpr->pTab;
101528   if( NEVER(pTab==0) ) return pDef;
101529   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
101530   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
101531   assert( pVtab!=0 );
101532   assert( pVtab->pModule!=0 );
101533   pMod = (sqlite3_module *)pVtab->pModule;
101534   if( pMod->xFindFunction==0 ) return pDef;
101535  
101536   /* Call the xFindFunction method on the virtual table implementation
101537   ** to see if the implementation wants to overload this function 
101538   */
101539   zLowerName = sqlite3DbStrDup(db, pDef->zName);
101540   if( zLowerName ){
101541     for(z=(unsigned char*)zLowerName; *z; z++){
101542       *z = sqlite3UpperToLower[*z];
101543     }
101544     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
101545     sqlite3DbFree(db, zLowerName);
101546   }
101547   if( rc==0 ){
101548     return pDef;
101549   }
101550
101551   /* Create a new ephemeral function definition for the overloaded
101552   ** function */
101553   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
101554                              + sqlite3Strlen30(pDef->zName) + 1);
101555   if( pNew==0 ){
101556     return pDef;
101557   }
101558   *pNew = *pDef;
101559   pNew->zName = (char *)&pNew[1];
101560   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
101561   pNew->xFunc = xFunc;
101562   pNew->pUserData = pArg;
101563   pNew->flags |= SQLITE_FUNC_EPHEM;
101564   return pNew;
101565 }
101566
101567 /*
101568 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
101569 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
101570 ** array if it is missing.  If pTab is already in the array, this routine
101571 ** is a no-op.
101572 */
101573 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
101574   Parse *pToplevel = sqlite3ParseToplevel(pParse);
101575   int i, n;
101576   Table **apVtabLock;
101577
101578   assert( IsVirtual(pTab) );
101579   for(i=0; i<pToplevel->nVtabLock; i++){
101580     if( pTab==pToplevel->apVtabLock[i] ) return;
101581   }
101582   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
101583   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
101584   if( apVtabLock ){
101585     pToplevel->apVtabLock = apVtabLock;
101586     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
101587   }else{
101588     pToplevel->db->mallocFailed = 1;
101589   }
101590 }
101591
101592 /*
101593 ** Return the ON CONFLICT resolution mode in effect for the virtual
101594 ** table update operation currently in progress.
101595 **
101596 ** The results of this routine are undefined unless it is called from
101597 ** within an xUpdate method.
101598 */
101599 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
101600   static const unsigned char aMap[] = { 
101601     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
101602   };
101603   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
101604   assert( OE_Ignore==4 && OE_Replace==5 );
101605   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
101606   return (int)aMap[db->vtabOnConflict-1];
101607 }
101608
101609 /*
101610 ** Call from within the xCreate() or xConnect() methods to provide 
101611 ** the SQLite core with additional information about the behavior
101612 ** of the virtual table being implemented.
101613 */
101614 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
101615   va_list ap;
101616   int rc = SQLITE_OK;
101617
101618   sqlite3_mutex_enter(db->mutex);
101619
101620   va_start(ap, op);
101621   switch( op ){
101622     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
101623       VtabCtx *p = db->pVtabCtx;
101624       if( !p ){
101625         rc = SQLITE_MISUSE_BKPT;
101626       }else{
101627         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
101628         p->pVTable->bConstraint = (u8)va_arg(ap, int);
101629       }
101630       break;
101631     }
101632     default:
101633       rc = SQLITE_MISUSE_BKPT;
101634       break;
101635   }
101636   va_end(ap);
101637
101638   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
101639   sqlite3_mutex_leave(db->mutex);
101640   return rc;
101641 }
101642
101643 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101644
101645 /************** End of vtab.c ************************************************/
101646 /************** Begin file where.c *******************************************/
101647 /*
101648 ** 2001 September 15
101649 **
101650 ** The author disclaims copyright to this source code.  In place of
101651 ** a legal notice, here is a blessing:
101652 **
101653 **    May you do good and not evil.
101654 **    May you find forgiveness for yourself and forgive others.
101655 **    May you share freely, never taking more than you give.
101656 **
101657 *************************************************************************
101658 ** This module contains C code that generates VDBE code used to process
101659 ** the WHERE clause of SQL statements.  This module is responsible for
101660 ** generating the code that loops through a table looking for applicable
101661 ** rows.  Indices are selected and used to speed the search when doing
101662 ** so is applicable.  Because this module is responsible for selecting
101663 ** indices, you might also think of this module as the "query optimizer".
101664 */
101665
101666
101667 /*
101668 ** Trace output macros
101669 */
101670 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
101671 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
101672 #endif
101673 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
101674 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
101675 #else
101676 # define WHERETRACE(X)
101677 #endif
101678
101679 /* Forward reference
101680 */
101681 typedef struct WhereClause WhereClause;
101682 typedef struct WhereMaskSet WhereMaskSet;
101683 typedef struct WhereOrInfo WhereOrInfo;
101684 typedef struct WhereAndInfo WhereAndInfo;
101685 typedef struct WhereCost WhereCost;
101686
101687 /*
101688 ** The query generator uses an array of instances of this structure to
101689 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
101690 ** clause subexpression is separated from the others by AND operators,
101691 ** usually, or sometimes subexpressions separated by OR.
101692 **
101693 ** All WhereTerms are collected into a single WhereClause structure.  
101694 ** The following identity holds:
101695 **
101696 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
101697 **
101698 ** When a term is of the form:
101699 **
101700 **              X <op> <expr>
101701 **
101702 ** where X is a column name and <op> is one of certain operators,
101703 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
101704 ** cursor number and column number for X.  WhereTerm.eOperator records
101705 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
101706 ** use of a bitmask encoding for the operator allows us to search
101707 ** quickly for terms that match any of several different operators.
101708 **
101709 ** A WhereTerm might also be two or more subterms connected by OR:
101710 **
101711 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
101712 **
101713 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
101714 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
101715 ** is collected about the
101716 **
101717 ** If a term in the WHERE clause does not match either of the two previous
101718 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
101719 ** to the original subexpression content and wtFlags is set up appropriately
101720 ** but no other fields in the WhereTerm object are meaningful.
101721 **
101722 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
101723 ** but they do so indirectly.  A single WhereMaskSet structure translates
101724 ** cursor number into bits and the translated bit is stored in the prereq
101725 ** fields.  The translation is used in order to maximize the number of
101726 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
101727 ** spread out over the non-negative integers.  For example, the cursor
101728 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
101729 ** translates these sparse cursor numbers into consecutive integers
101730 ** beginning with 0 in order to make the best possible use of the available
101731 ** bits in the Bitmask.  So, in the example above, the cursor numbers
101732 ** would be mapped into integers 0 through 7.
101733 **
101734 ** The number of terms in a join is limited by the number of bits
101735 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
101736 ** is only able to process joins with 64 or fewer tables.
101737 */
101738 typedef struct WhereTerm WhereTerm;
101739 struct WhereTerm {
101740   Expr *pExpr;            /* Pointer to the subexpression that is this term */
101741   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
101742   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
101743   union {
101744     int leftColumn;         /* Column number of X in "X <op> <expr>" */
101745     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
101746     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
101747   } u;
101748   u16 eOperator;          /* A WO_xx value describing <op> */
101749   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
101750   u8 nChild;              /* Number of children that must disable us */
101751   WhereClause *pWC;       /* The clause this term is part of */
101752   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
101753   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
101754 };
101755
101756 /*
101757 ** Allowed values of WhereTerm.wtFlags
101758 */
101759 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
101760 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
101761 #define TERM_CODED      0x04   /* This term is already coded */
101762 #define TERM_COPIED     0x08   /* Has a child */
101763 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
101764 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
101765 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
101766 #ifdef SQLITE_ENABLE_STAT3
101767 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
101768 #else
101769 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
101770 #endif
101771
101772 /*
101773 ** An instance of the following structure holds all information about a
101774 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
101775 **
101776 ** Explanation of pOuter:  For a WHERE clause of the form
101777 **
101778 **           a AND ((b AND c) OR (d AND e)) AND f
101779 **
101780 ** There are separate WhereClause objects for the whole clause and for
101781 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
101782 ** subclauses points to the WhereClause object for the whole clause.
101783 */
101784 struct WhereClause {
101785   Parse *pParse;           /* The parser context */
101786   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
101787   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
101788   WhereClause *pOuter;     /* Outer conjunction */
101789   u8 op;                   /* Split operator.  TK_AND or TK_OR */
101790   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
101791   int nTerm;               /* Number of terms */
101792   int nSlot;               /* Number of entries in a[] */
101793   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
101794 #if defined(SQLITE_SMALL_STACK)
101795   WhereTerm aStatic[1];    /* Initial static space for a[] */
101796 #else
101797   WhereTerm aStatic[8];    /* Initial static space for a[] */
101798 #endif
101799 };
101800
101801 /*
101802 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
101803 ** a dynamically allocated instance of the following structure.
101804 */
101805 struct WhereOrInfo {
101806   WhereClause wc;          /* Decomposition into subterms */
101807   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
101808 };
101809
101810 /*
101811 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
101812 ** a dynamically allocated instance of the following structure.
101813 */
101814 struct WhereAndInfo {
101815   WhereClause wc;          /* The subexpression broken out */
101816 };
101817
101818 /*
101819 ** An instance of the following structure keeps track of a mapping
101820 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
101821 **
101822 ** The VDBE cursor numbers are small integers contained in 
101823 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
101824 ** clause, the cursor numbers might not begin with 0 and they might
101825 ** contain gaps in the numbering sequence.  But we want to make maximum
101826 ** use of the bits in our bitmasks.  This structure provides a mapping
101827 ** from the sparse cursor numbers into consecutive integers beginning
101828 ** with 0.
101829 **
101830 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
101831 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
101832 **
101833 ** For example, if the WHERE clause expression used these VDBE
101834 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
101835 ** would map those cursor numbers into bits 0 through 5.
101836 **
101837 ** Note that the mapping is not necessarily ordered.  In the example
101838 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
101839 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
101840 ** does not really matter.  What is important is that sparse cursor
101841 ** numbers all get mapped into bit numbers that begin with 0 and contain
101842 ** no gaps.
101843 */
101844 struct WhereMaskSet {
101845   int n;                        /* Number of assigned cursor values */
101846   int ix[BMS];                  /* Cursor assigned to each bit */
101847 };
101848
101849 /*
101850 ** A WhereCost object records a lookup strategy and the estimated
101851 ** cost of pursuing that strategy.
101852 */
101853 struct WhereCost {
101854   WherePlan plan;    /* The lookup strategy */
101855   double rCost;      /* Overall cost of pursuing this search strategy */
101856   Bitmask used;      /* Bitmask of cursors used by this plan */
101857 };
101858
101859 /*
101860 ** Bitmasks for the operators that indices are able to exploit.  An
101861 ** OR-ed combination of these values can be used when searching for
101862 ** terms in the where clause.
101863 */
101864 #define WO_IN     0x001
101865 #define WO_EQ     0x002
101866 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
101867 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
101868 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
101869 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
101870 #define WO_MATCH  0x040
101871 #define WO_ISNULL 0x080
101872 #define WO_OR     0x100       /* Two or more OR-connected terms */
101873 #define WO_AND    0x200       /* Two or more AND-connected terms */
101874 #define WO_NOOP   0x800       /* This term does not restrict search space */
101875
101876 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
101877 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
101878
101879 /*
101880 ** Value for wsFlags returned by bestIndex() and stored in
101881 ** WhereLevel.wsFlags.  These flags determine which search
101882 ** strategies are appropriate.
101883 **
101884 ** The least significant 12 bits is reserved as a mask for WO_ values above.
101885 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
101886 ** But if the table is the right table of a left join, WhereLevel.wsFlags
101887 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
101888 ** the "op" parameter to findTerm when we are resolving equality constraints.
101889 ** ISNULL constraints will then not be used on the right table of a left
101890 ** join.  Tickets #2177 and #2189.
101891 */
101892 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
101893 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
101894 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
101895 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
101896 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
101897 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
101898 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
101899 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
101900 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
101901 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
101902 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
101903 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
101904 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
101905 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
101906 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
101907 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
101908 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
101909 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
101910 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
101911 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
101912
101913 /*
101914 ** Initialize a preallocated WhereClause structure.
101915 */
101916 static void whereClauseInit(
101917   WhereClause *pWC,        /* The WhereClause to be initialized */
101918   Parse *pParse,           /* The parsing context */
101919   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
101920   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
101921 ){
101922   pWC->pParse = pParse;
101923   pWC->pMaskSet = pMaskSet;
101924   pWC->pOuter = 0;
101925   pWC->nTerm = 0;
101926   pWC->nSlot = ArraySize(pWC->aStatic);
101927   pWC->a = pWC->aStatic;
101928   pWC->vmask = 0;
101929   pWC->wctrlFlags = wctrlFlags;
101930 }
101931
101932 /* Forward reference */
101933 static void whereClauseClear(WhereClause*);
101934
101935 /*
101936 ** Deallocate all memory associated with a WhereOrInfo object.
101937 */
101938 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
101939   whereClauseClear(&p->wc);
101940   sqlite3DbFree(db, p);
101941 }
101942
101943 /*
101944 ** Deallocate all memory associated with a WhereAndInfo object.
101945 */
101946 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
101947   whereClauseClear(&p->wc);
101948   sqlite3DbFree(db, p);
101949 }
101950
101951 /*
101952 ** Deallocate a WhereClause structure.  The WhereClause structure
101953 ** itself is not freed.  This routine is the inverse of whereClauseInit().
101954 */
101955 static void whereClauseClear(WhereClause *pWC){
101956   int i;
101957   WhereTerm *a;
101958   sqlite3 *db = pWC->pParse->db;
101959   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
101960     if( a->wtFlags & TERM_DYNAMIC ){
101961       sqlite3ExprDelete(db, a->pExpr);
101962     }
101963     if( a->wtFlags & TERM_ORINFO ){
101964       whereOrInfoDelete(db, a->u.pOrInfo);
101965     }else if( a->wtFlags & TERM_ANDINFO ){
101966       whereAndInfoDelete(db, a->u.pAndInfo);
101967     }
101968   }
101969   if( pWC->a!=pWC->aStatic ){
101970     sqlite3DbFree(db, pWC->a);
101971   }
101972 }
101973
101974 /*
101975 ** Add a single new WhereTerm entry to the WhereClause object pWC.
101976 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
101977 ** The index in pWC->a[] of the new WhereTerm is returned on success.
101978 ** 0 is returned if the new WhereTerm could not be added due to a memory
101979 ** allocation error.  The memory allocation failure will be recorded in
101980 ** the db->mallocFailed flag so that higher-level functions can detect it.
101981 **
101982 ** This routine will increase the size of the pWC->a[] array as necessary.
101983 **
101984 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
101985 ** for freeing the expression p is assumed by the WhereClause object pWC.
101986 ** This is true even if this routine fails to allocate a new WhereTerm.
101987 **
101988 ** WARNING:  This routine might reallocate the space used to store
101989 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
101990 ** calling this routine.  Such pointers may be reinitialized by referencing
101991 ** the pWC->a[] array.
101992 */
101993 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
101994   WhereTerm *pTerm;
101995   int idx;
101996   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
101997   if( pWC->nTerm>=pWC->nSlot ){
101998     WhereTerm *pOld = pWC->a;
101999     sqlite3 *db = pWC->pParse->db;
102000     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102001     if( pWC->a==0 ){
102002       if( wtFlags & TERM_DYNAMIC ){
102003         sqlite3ExprDelete(db, p);
102004       }
102005       pWC->a = pOld;
102006       return 0;
102007     }
102008     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102009     if( pOld!=pWC->aStatic ){
102010       sqlite3DbFree(db, pOld);
102011     }
102012     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102013   }
102014   pTerm = &pWC->a[idx = pWC->nTerm++];
102015   pTerm->pExpr = p;
102016   pTerm->wtFlags = wtFlags;
102017   pTerm->pWC = pWC;
102018   pTerm->iParent = -1;
102019   return idx;
102020 }
102021
102022 /*
102023 ** This routine identifies subexpressions in the WHERE clause where
102024 ** each subexpression is separated by the AND operator or some other
102025 ** operator specified in the op parameter.  The WhereClause structure
102026 ** is filled with pointers to subexpressions.  For example:
102027 **
102028 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102029 **           \________/     \_______________/     \________________/
102030 **            slot[0]            slot[1]               slot[2]
102031 **
102032 ** The original WHERE clause in pExpr is unaltered.  All this routine
102033 ** does is make slot[] entries point to substructure within pExpr.
102034 **
102035 ** In the previous sentence and in the diagram, "slot[]" refers to
102036 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102037 ** all terms of the WHERE clause.
102038 */
102039 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102040   pWC->op = (u8)op;
102041   if( pExpr==0 ) return;
102042   if( pExpr->op!=op ){
102043     whereClauseInsert(pWC, pExpr, 0);
102044   }else{
102045     whereSplit(pWC, pExpr->pLeft, op);
102046     whereSplit(pWC, pExpr->pRight, op);
102047   }
102048 }
102049
102050 /*
102051 ** Initialize an expression mask set (a WhereMaskSet object)
102052 */
102053 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
102054
102055 /*
102056 ** Return the bitmask for the given cursor number.  Return 0 if
102057 ** iCursor is not in the set.
102058 */
102059 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102060   int i;
102061   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102062   for(i=0; i<pMaskSet->n; i++){
102063     if( pMaskSet->ix[i]==iCursor ){
102064       return ((Bitmask)1)<<i;
102065     }
102066   }
102067   return 0;
102068 }
102069
102070 /*
102071 ** Create a new mask for cursor iCursor.
102072 **
102073 ** There is one cursor per table in the FROM clause.  The number of
102074 ** tables in the FROM clause is limited by a test early in the
102075 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102076 ** array will never overflow.
102077 */
102078 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102079   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102080   pMaskSet->ix[pMaskSet->n++] = iCursor;
102081 }
102082
102083 /*
102084 ** This routine walks (recursively) an expression tree and generates
102085 ** a bitmask indicating which tables are used in that expression
102086 ** tree.
102087 **
102088 ** In order for this routine to work, the calling function must have
102089 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
102090 ** the header comment on that routine for additional information.
102091 ** The sqlite3ResolveExprNames() routines looks for column names and
102092 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102093 ** the VDBE cursor number of the table.  This routine just has to
102094 ** translate the cursor numbers into bitmask values and OR all
102095 ** the bitmasks together.
102096 */
102097 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102098 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102099 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
102100   Bitmask mask = 0;
102101   if( p==0 ) return 0;
102102   if( p->op==TK_COLUMN ){
102103     mask = getMask(pMaskSet, p->iTable);
102104     return mask;
102105   }
102106   mask = exprTableUsage(pMaskSet, p->pRight);
102107   mask |= exprTableUsage(pMaskSet, p->pLeft);
102108   if( ExprHasProperty(p, EP_xIsSelect) ){
102109     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
102110   }else{
102111     mask |= exprListTableUsage(pMaskSet, p->x.pList);
102112   }
102113   return mask;
102114 }
102115 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
102116   int i;
102117   Bitmask mask = 0;
102118   if( pList ){
102119     for(i=0; i<pList->nExpr; i++){
102120       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
102121     }
102122   }
102123   return mask;
102124 }
102125 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
102126   Bitmask mask = 0;
102127   while( pS ){
102128     SrcList *pSrc = pS->pSrc;
102129     mask |= exprListTableUsage(pMaskSet, pS->pEList);
102130     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
102131     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
102132     mask |= exprTableUsage(pMaskSet, pS->pWhere);
102133     mask |= exprTableUsage(pMaskSet, pS->pHaving);
102134     if( ALWAYS(pSrc!=0) ){
102135       int i;
102136       for(i=0; i<pSrc->nSrc; i++){
102137         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
102138         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
102139       }
102140     }
102141     pS = pS->pPrior;
102142   }
102143   return mask;
102144 }
102145
102146 /*
102147 ** Return TRUE if the given operator is one of the operators that is
102148 ** allowed for an indexable WHERE clause term.  The allowed operators are
102149 ** "=", "<", ">", "<=", ">=", and "IN".
102150 **
102151 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
102152 ** of one of the following forms: column = expression column > expression
102153 ** column >= expression column < expression column <= expression
102154 ** expression = column expression > column expression >= column
102155 ** expression < column expression <= column column IN
102156 ** (expression-list) column IN (subquery) column IS NULL
102157 */
102158 static int allowedOp(int op){
102159   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
102160   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
102161   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
102162   assert( TK_GE==TK_EQ+4 );
102163   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
102164 }
102165
102166 /*
102167 ** Swap two objects of type TYPE.
102168 */
102169 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
102170
102171 /*
102172 ** Commute a comparison operator.  Expressions of the form "X op Y"
102173 ** are converted into "Y op X".
102174 **
102175 ** If a collation sequence is associated with either the left or right
102176 ** side of the comparison, it remains associated with the same side after
102177 ** the commutation. So "Y collate NOCASE op X" becomes 
102178 ** "X collate NOCASE op Y". This is because any collation sequence on
102179 ** the left hand side of a comparison overrides any collation sequence 
102180 ** attached to the right. For the same reason the EP_ExpCollate flag
102181 ** is not commuted.
102182 */
102183 static void exprCommute(Parse *pParse, Expr *pExpr){
102184   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
102185   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
102186   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
102187   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
102188   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
102189   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
102190   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
102191   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
102192   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
102193   if( pExpr->op>=TK_GT ){
102194     assert( TK_LT==TK_GT+2 );
102195     assert( TK_GE==TK_LE+2 );
102196     assert( TK_GT>TK_EQ );
102197     assert( TK_GT<TK_LE );
102198     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
102199     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
102200   }
102201 }
102202
102203 /*
102204 ** Translate from TK_xx operator to WO_xx bitmask.
102205 */
102206 static u16 operatorMask(int op){
102207   u16 c;
102208   assert( allowedOp(op) );
102209   if( op==TK_IN ){
102210     c = WO_IN;
102211   }else if( op==TK_ISNULL ){
102212     c = WO_ISNULL;
102213   }else{
102214     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
102215     c = (u16)(WO_EQ<<(op-TK_EQ));
102216   }
102217   assert( op!=TK_ISNULL || c==WO_ISNULL );
102218   assert( op!=TK_IN || c==WO_IN );
102219   assert( op!=TK_EQ || c==WO_EQ );
102220   assert( op!=TK_LT || c==WO_LT );
102221   assert( op!=TK_LE || c==WO_LE );
102222   assert( op!=TK_GT || c==WO_GT );
102223   assert( op!=TK_GE || c==WO_GE );
102224   return c;
102225 }
102226
102227 /*
102228 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
102229 ** where X is a reference to the iColumn of table iCur and <op> is one of
102230 ** the WO_xx operator codes specified by the op parameter.
102231 ** Return a pointer to the term.  Return 0 if not found.
102232 */
102233 static WhereTerm *findTerm(
102234   WhereClause *pWC,     /* The WHERE clause to be searched */
102235   int iCur,             /* Cursor number of LHS */
102236   int iColumn,          /* Column number of LHS */
102237   Bitmask notReady,     /* RHS must not overlap with this mask */
102238   u32 op,               /* Mask of WO_xx values describing operator */
102239   Index *pIdx           /* Must be compatible with this index, if not NULL */
102240 ){
102241   WhereTerm *pTerm;
102242   int k;
102243   assert( iCur>=0 );
102244   op &= WO_ALL;
102245   for(; pWC; pWC=pWC->pOuter){
102246     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
102247       if( pTerm->leftCursor==iCur
102248          && (pTerm->prereqRight & notReady)==0
102249          && pTerm->u.leftColumn==iColumn
102250          && (pTerm->eOperator & op)!=0
102251       ){
102252         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
102253           Expr *pX = pTerm->pExpr;
102254           CollSeq *pColl;
102255           char idxaff;
102256           int j;
102257           Parse *pParse = pWC->pParse;
102258   
102259           idxaff = pIdx->pTable->aCol[iColumn].affinity;
102260           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
102261   
102262           /* Figure out the collation sequence required from an index for
102263           ** it to be useful for optimising expression pX. Store this
102264           ** value in variable pColl.
102265           */
102266           assert(pX->pLeft);
102267           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102268           assert(pColl || pParse->nErr);
102269   
102270           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
102271             if( NEVER(j>=pIdx->nColumn) ) return 0;
102272           }
102273           if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
102274         }
102275         return pTerm;
102276       }
102277     }
102278   }
102279   return 0;
102280 }
102281
102282 /* Forward reference */
102283 static void exprAnalyze(SrcList*, WhereClause*, int);
102284
102285 /*
102286 ** Call exprAnalyze on all terms in a WHERE clause.  
102287 **
102288 **
102289 */
102290 static void exprAnalyzeAll(
102291   SrcList *pTabList,       /* the FROM clause */
102292   WhereClause *pWC         /* the WHERE clause to be analyzed */
102293 ){
102294   int i;
102295   for(i=pWC->nTerm-1; i>=0; i--){
102296     exprAnalyze(pTabList, pWC, i);
102297   }
102298 }
102299
102300 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
102301 /*
102302 ** Check to see if the given expression is a LIKE or GLOB operator that
102303 ** can be optimized using inequality constraints.  Return TRUE if it is
102304 ** so and false if not.
102305 **
102306 ** In order for the operator to be optimizible, the RHS must be a string
102307 ** literal that does not begin with a wildcard.  
102308 */
102309 static int isLikeOrGlob(
102310   Parse *pParse,    /* Parsing and code generating context */
102311   Expr *pExpr,      /* Test this expression */
102312   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
102313   int *pisComplete, /* True if the only wildcard is % in the last character */
102314   int *pnoCase      /* True if uppercase is equivalent to lowercase */
102315 ){
102316   const char *z = 0;         /* String on RHS of LIKE operator */
102317   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
102318   ExprList *pList;           /* List of operands to the LIKE operator */
102319   int c;                     /* One character in z[] */
102320   int cnt;                   /* Number of non-wildcard prefix characters */
102321   char wc[3];                /* Wildcard characters */
102322   sqlite3 *db = pParse->db;  /* Database connection */
102323   sqlite3_value *pVal = 0;
102324   int op;                    /* Opcode of pRight */
102325
102326   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
102327     return 0;
102328   }
102329 #ifdef SQLITE_EBCDIC
102330   if( *pnoCase ) return 0;
102331 #endif
102332   pList = pExpr->x.pList;
102333   pLeft = pList->a[1].pExpr;
102334   if( pLeft->op!=TK_COLUMN 
102335    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
102336    || IsVirtual(pLeft->pTab)
102337   ){
102338     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
102339     ** be the name of an indexed column with TEXT affinity. */
102340     return 0;
102341   }
102342   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
102343
102344   pRight = pList->a[0].pExpr;
102345   op = pRight->op;
102346   if( op==TK_REGISTER ){
102347     op = pRight->op2;
102348   }
102349   if( op==TK_VARIABLE ){
102350     Vdbe *pReprepare = pParse->pReprepare;
102351     int iCol = pRight->iColumn;
102352     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
102353     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
102354       z = (char *)sqlite3_value_text(pVal);
102355     }
102356     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
102357     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
102358   }else if( op==TK_STRING ){
102359     z = pRight->u.zToken;
102360   }
102361   if( z ){
102362     cnt = 0;
102363     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
102364       cnt++;
102365     }
102366     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
102367       Expr *pPrefix;
102368       *pisComplete = c==wc[0] && z[cnt+1]==0;
102369       pPrefix = sqlite3Expr(db, TK_STRING, z);
102370       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
102371       *ppPrefix = pPrefix;
102372       if( op==TK_VARIABLE ){
102373         Vdbe *v = pParse->pVdbe;
102374         sqlite3VdbeSetVarmask(v, pRight->iColumn);
102375         if( *pisComplete && pRight->u.zToken[1] ){
102376           /* If the rhs of the LIKE expression is a variable, and the current
102377           ** value of the variable means there is no need to invoke the LIKE
102378           ** function, then no OP_Variable will be added to the program.
102379           ** This causes problems for the sqlite3_bind_parameter_name()
102380           ** API. To workaround them, add a dummy OP_Variable here.
102381           */ 
102382           int r1 = sqlite3GetTempReg(pParse);
102383           sqlite3ExprCodeTarget(pParse, pRight, r1);
102384           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
102385           sqlite3ReleaseTempReg(pParse, r1);
102386         }
102387       }
102388     }else{
102389       z = 0;
102390     }
102391   }
102392
102393   sqlite3ValueFree(pVal);
102394   return (z!=0);
102395 }
102396 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
102397
102398
102399 #ifndef SQLITE_OMIT_VIRTUALTABLE
102400 /*
102401 ** Check to see if the given expression is of the form
102402 **
102403 **         column MATCH expr
102404 **
102405 ** If it is then return TRUE.  If not, return FALSE.
102406 */
102407 static int isMatchOfColumn(
102408   Expr *pExpr      /* Test this expression */
102409 ){
102410   ExprList *pList;
102411
102412   if( pExpr->op!=TK_FUNCTION ){
102413     return 0;
102414   }
102415   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
102416     return 0;
102417   }
102418   pList = pExpr->x.pList;
102419   if( pList->nExpr!=2 ){
102420     return 0;
102421   }
102422   if( pList->a[1].pExpr->op != TK_COLUMN ){
102423     return 0;
102424   }
102425   return 1;
102426 }
102427 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102428
102429 /*
102430 ** If the pBase expression originated in the ON or USING clause of
102431 ** a join, then transfer the appropriate markings over to derived.
102432 */
102433 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
102434   pDerived->flags |= pBase->flags & EP_FromJoin;
102435   pDerived->iRightJoinTable = pBase->iRightJoinTable;
102436 }
102437
102438 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
102439 /*
102440 ** Analyze a term that consists of two or more OR-connected
102441 ** subterms.  So in:
102442 **
102443 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
102444 **                          ^^^^^^^^^^^^^^^^^^^^
102445 **
102446 ** This routine analyzes terms such as the middle term in the above example.
102447 ** A WhereOrTerm object is computed and attached to the term under
102448 ** analysis, regardless of the outcome of the analysis.  Hence:
102449 **
102450 **     WhereTerm.wtFlags   |=  TERM_ORINFO
102451 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
102452 **
102453 ** The term being analyzed must have two or more of OR-connected subterms.
102454 ** A single subterm might be a set of AND-connected sub-subterms.
102455 ** Examples of terms under analysis:
102456 **
102457 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
102458 **     (B)     x=expr1 OR expr2=x OR x=expr3
102459 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
102460 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
102461 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
102462 **
102463 ** CASE 1:
102464 **
102465 ** If all subterms are of the form T.C=expr for some single column of C
102466 ** a single table T (as shown in example B above) then create a new virtual
102467 ** term that is an equivalent IN expression.  In other words, if the term
102468 ** being analyzed is:
102469 **
102470 **      x = expr1  OR  expr2 = x  OR  x = expr3
102471 **
102472 ** then create a new virtual term like this:
102473 **
102474 **      x IN (expr1,expr2,expr3)
102475 **
102476 ** CASE 2:
102477 **
102478 ** If all subterms are indexable by a single table T, then set
102479 **
102480 **     WhereTerm.eOperator              =  WO_OR
102481 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
102482 **
102483 ** A subterm is "indexable" if it is of the form
102484 ** "T.C <op> <expr>" where C is any column of table T and 
102485 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
102486 ** A subterm is also indexable if it is an AND of two or more
102487 ** subsubterms at least one of which is indexable.  Indexable AND 
102488 ** subterms have their eOperator set to WO_AND and they have
102489 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
102490 **
102491 ** From another point of view, "indexable" means that the subterm could
102492 ** potentially be used with an index if an appropriate index exists.
102493 ** This analysis does not consider whether or not the index exists; that
102494 ** is something the bestIndex() routine will determine.  This analysis
102495 ** only looks at whether subterms appropriate for indexing exist.
102496 **
102497 ** All examples A through E above all satisfy case 2.  But if a term
102498 ** also statisfies case 1 (such as B) we know that the optimizer will
102499 ** always prefer case 1, so in that case we pretend that case 2 is not
102500 ** satisfied.
102501 **
102502 ** It might be the case that multiple tables are indexable.  For example,
102503 ** (E) above is indexable on tables P, Q, and R.
102504 **
102505 ** Terms that satisfy case 2 are candidates for lookup by using
102506 ** separate indices to find rowids for each subterm and composing
102507 ** the union of all rowids using a RowSet object.  This is similar
102508 ** to "bitmap indices" in other database engines.
102509 **
102510 ** OTHERWISE:
102511 **
102512 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
102513 ** zero.  This term is not useful for search.
102514 */
102515 static void exprAnalyzeOrTerm(
102516   SrcList *pSrc,            /* the FROM clause */
102517   WhereClause *pWC,         /* the complete WHERE clause */
102518   int idxTerm               /* Index of the OR-term to be analyzed */
102519 ){
102520   Parse *pParse = pWC->pParse;            /* Parser context */
102521   sqlite3 *db = pParse->db;               /* Database connection */
102522   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
102523   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
102524   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
102525   int i;                                  /* Loop counters */
102526   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
102527   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
102528   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
102529   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
102530   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
102531
102532   /*
102533   ** Break the OR clause into its separate subterms.  The subterms are
102534   ** stored in a WhereClause structure containing within the WhereOrInfo
102535   ** object that is attached to the original OR clause term.
102536   */
102537   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
102538   assert( pExpr->op==TK_OR );
102539   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
102540   if( pOrInfo==0 ) return;
102541   pTerm->wtFlags |= TERM_ORINFO;
102542   pOrWc = &pOrInfo->wc;
102543   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
102544   whereSplit(pOrWc, pExpr, TK_OR);
102545   exprAnalyzeAll(pSrc, pOrWc);
102546   if( db->mallocFailed ) return;
102547   assert( pOrWc->nTerm>=2 );
102548
102549   /*
102550   ** Compute the set of tables that might satisfy cases 1 or 2.
102551   */
102552   indexable = ~(Bitmask)0;
102553   chngToIN = ~(pWC->vmask);
102554   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
102555     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
102556       WhereAndInfo *pAndInfo;
102557       assert( pOrTerm->eOperator==0 );
102558       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
102559       chngToIN = 0;
102560       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
102561       if( pAndInfo ){
102562         WhereClause *pAndWC;
102563         WhereTerm *pAndTerm;
102564         int j;
102565         Bitmask b = 0;
102566         pOrTerm->u.pAndInfo = pAndInfo;
102567         pOrTerm->wtFlags |= TERM_ANDINFO;
102568         pOrTerm->eOperator = WO_AND;
102569         pAndWC = &pAndInfo->wc;
102570         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
102571         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
102572         exprAnalyzeAll(pSrc, pAndWC);
102573         pAndWC->pOuter = pWC;
102574         testcase( db->mallocFailed );
102575         if( !db->mallocFailed ){
102576           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
102577             assert( pAndTerm->pExpr );
102578             if( allowedOp(pAndTerm->pExpr->op) ){
102579               b |= getMask(pMaskSet, pAndTerm->leftCursor);
102580             }
102581           }
102582         }
102583         indexable &= b;
102584       }
102585     }else if( pOrTerm->wtFlags & TERM_COPIED ){
102586       /* Skip this term for now.  We revisit it when we process the
102587       ** corresponding TERM_VIRTUAL term */
102588     }else{
102589       Bitmask b;
102590       b = getMask(pMaskSet, pOrTerm->leftCursor);
102591       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
102592         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
102593         b |= getMask(pMaskSet, pOther->leftCursor);
102594       }
102595       indexable &= b;
102596       if( pOrTerm->eOperator!=WO_EQ ){
102597         chngToIN = 0;
102598       }else{
102599         chngToIN &= b;
102600       }
102601     }
102602   }
102603
102604   /*
102605   ** Record the set of tables that satisfy case 2.  The set might be
102606   ** empty.
102607   */
102608   pOrInfo->indexable = indexable;
102609   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
102610
102611   /*
102612   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
102613   ** we have to do some additional checking to see if case 1 really
102614   ** is satisfied.
102615   **
102616   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
102617   ** that there is no possibility of transforming the OR clause into an
102618   ** IN operator because one or more terms in the OR clause contain
102619   ** something other than == on a column in the single table.  The 1-bit
102620   ** case means that every term of the OR clause is of the form
102621   ** "table.column=expr" for some single table.  The one bit that is set
102622   ** will correspond to the common table.  We still need to check to make
102623   ** sure the same column is used on all terms.  The 2-bit case is when
102624   ** the all terms are of the form "table1.column=table2.column".  It
102625   ** might be possible to form an IN operator with either table1.column
102626   ** or table2.column as the LHS if either is common to every term of
102627   ** the OR clause.
102628   **
102629   ** Note that terms of the form "table.column1=table.column2" (the
102630   ** same table on both sizes of the ==) cannot be optimized.
102631   */
102632   if( chngToIN ){
102633     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
102634     int iColumn = -1;         /* Column index on lhs of IN operator */
102635     int iCursor = -1;         /* Table cursor common to all terms */
102636     int j = 0;                /* Loop counter */
102637
102638     /* Search for a table and column that appears on one side or the
102639     ** other of the == operator in every subterm.  That table and column
102640     ** will be recorded in iCursor and iColumn.  There might not be any
102641     ** such table and column.  Set okToChngToIN if an appropriate table
102642     ** and column is found but leave okToChngToIN false if not found.
102643     */
102644     for(j=0; j<2 && !okToChngToIN; j++){
102645       pOrTerm = pOrWc->a;
102646       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
102647         assert( pOrTerm->eOperator==WO_EQ );
102648         pOrTerm->wtFlags &= ~TERM_OR_OK;
102649         if( pOrTerm->leftCursor==iCursor ){
102650           /* This is the 2-bit case and we are on the second iteration and
102651           ** current term is from the first iteration.  So skip this term. */
102652           assert( j==1 );
102653           continue;
102654         }
102655         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
102656           /* This term must be of the form t1.a==t2.b where t2 is in the
102657           ** chngToIN set but t1 is not.  This term will be either preceeded
102658           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
102659           ** and use its inversion. */
102660           testcase( pOrTerm->wtFlags & TERM_COPIED );
102661           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
102662           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
102663           continue;
102664         }
102665         iColumn = pOrTerm->u.leftColumn;
102666         iCursor = pOrTerm->leftCursor;
102667         break;
102668       }
102669       if( i<0 ){
102670         /* No candidate table+column was found.  This can only occur
102671         ** on the second iteration */
102672         assert( j==1 );
102673         assert( (chngToIN&(chngToIN-1))==0 );
102674         assert( chngToIN==getMask(pMaskSet, iCursor) );
102675         break;
102676       }
102677       testcase( j==1 );
102678
102679       /* We have found a candidate table and column.  Check to see if that
102680       ** table and column is common to every term in the OR clause */
102681       okToChngToIN = 1;
102682       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
102683         assert( pOrTerm->eOperator==WO_EQ );
102684         if( pOrTerm->leftCursor!=iCursor ){
102685           pOrTerm->wtFlags &= ~TERM_OR_OK;
102686         }else if( pOrTerm->u.leftColumn!=iColumn ){
102687           okToChngToIN = 0;
102688         }else{
102689           int affLeft, affRight;
102690           /* If the right-hand side is also a column, then the affinities
102691           ** of both right and left sides must be such that no type
102692           ** conversions are required on the right.  (Ticket #2249)
102693           */
102694           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
102695           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
102696           if( affRight!=0 && affRight!=affLeft ){
102697             okToChngToIN = 0;
102698           }else{
102699             pOrTerm->wtFlags |= TERM_OR_OK;
102700           }
102701         }
102702       }
102703     }
102704
102705     /* At this point, okToChngToIN is true if original pTerm satisfies
102706     ** case 1.  In that case, construct a new virtual term that is 
102707     ** pTerm converted into an IN operator.
102708     **
102709     ** EV: R-00211-15100
102710     */
102711     if( okToChngToIN ){
102712       Expr *pDup;            /* A transient duplicate expression */
102713       ExprList *pList = 0;   /* The RHS of the IN operator */
102714       Expr *pLeft = 0;       /* The LHS of the IN operator */
102715       Expr *pNew;            /* The complete IN operator */
102716
102717       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
102718         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
102719         assert( pOrTerm->eOperator==WO_EQ );
102720         assert( pOrTerm->leftCursor==iCursor );
102721         assert( pOrTerm->u.leftColumn==iColumn );
102722         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
102723         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
102724         pLeft = pOrTerm->pExpr->pLeft;
102725       }
102726       assert( pLeft!=0 );
102727       pDup = sqlite3ExprDup(db, pLeft, 0);
102728       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
102729       if( pNew ){
102730         int idxNew;
102731         transferJoinMarkings(pNew, pExpr);
102732         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
102733         pNew->x.pList = pList;
102734         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
102735         testcase( idxNew==0 );
102736         exprAnalyze(pSrc, pWC, idxNew);
102737         pTerm = &pWC->a[idxTerm];
102738         pWC->a[idxNew].iParent = idxTerm;
102739         pTerm->nChild = 1;
102740       }else{
102741         sqlite3ExprListDelete(db, pList);
102742       }
102743       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
102744     }
102745   }
102746 }
102747 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
102748
102749
102750 /*
102751 ** The input to this routine is an WhereTerm structure with only the
102752 ** "pExpr" field filled in.  The job of this routine is to analyze the
102753 ** subexpression and populate all the other fields of the WhereTerm
102754 ** structure.
102755 **
102756 ** If the expression is of the form "<expr> <op> X" it gets commuted
102757 ** to the standard form of "X <op> <expr>".
102758 **
102759 ** If the expression is of the form "X <op> Y" where both X and Y are
102760 ** columns, then the original expression is unchanged and a new virtual
102761 ** term of the form "Y <op> X" is added to the WHERE clause and
102762 ** analyzed separately.  The original term is marked with TERM_COPIED
102763 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
102764 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
102765 ** is a commuted copy of a prior term.)  The original term has nChild=1
102766 ** and the copy has idxParent set to the index of the original term.
102767 */
102768 static void exprAnalyze(
102769   SrcList *pSrc,            /* the FROM clause */
102770   WhereClause *pWC,         /* the WHERE clause */
102771   int idxTerm               /* Index of the term to be analyzed */
102772 ){
102773   WhereTerm *pTerm;                /* The term to be analyzed */
102774   WhereMaskSet *pMaskSet;          /* Set of table index masks */
102775   Expr *pExpr;                     /* The expression to be analyzed */
102776   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
102777   Bitmask prereqAll;               /* Prerequesites of pExpr */
102778   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
102779   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
102780   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
102781   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
102782   int op;                          /* Top-level operator.  pExpr->op */
102783   Parse *pParse = pWC->pParse;     /* Parsing context */
102784   sqlite3 *db = pParse->db;        /* Database connection */
102785
102786   if( db->mallocFailed ){
102787     return;
102788   }
102789   pTerm = &pWC->a[idxTerm];
102790   pMaskSet = pWC->pMaskSet;
102791   pExpr = pTerm->pExpr;
102792   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
102793   op = pExpr->op;
102794   if( op==TK_IN ){
102795     assert( pExpr->pRight==0 );
102796     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
102797       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
102798     }else{
102799       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
102800     }
102801   }else if( op==TK_ISNULL ){
102802     pTerm->prereqRight = 0;
102803   }else{
102804     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
102805   }
102806   prereqAll = exprTableUsage(pMaskSet, pExpr);
102807   if( ExprHasProperty(pExpr, EP_FromJoin) ){
102808     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
102809     prereqAll |= x;
102810     extraRight = x-1;  /* ON clause terms may not be used with an index
102811                        ** on left table of a LEFT JOIN.  Ticket #3015 */
102812   }
102813   pTerm->prereqAll = prereqAll;
102814   pTerm->leftCursor = -1;
102815   pTerm->iParent = -1;
102816   pTerm->eOperator = 0;
102817   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
102818     Expr *pLeft = pExpr->pLeft;
102819     Expr *pRight = pExpr->pRight;
102820     if( pLeft->op==TK_COLUMN ){
102821       pTerm->leftCursor = pLeft->iTable;
102822       pTerm->u.leftColumn = pLeft->iColumn;
102823       pTerm->eOperator = operatorMask(op);
102824     }
102825     if( pRight && pRight->op==TK_COLUMN ){
102826       WhereTerm *pNew;
102827       Expr *pDup;
102828       if( pTerm->leftCursor>=0 ){
102829         int idxNew;
102830         pDup = sqlite3ExprDup(db, pExpr, 0);
102831         if( db->mallocFailed ){
102832           sqlite3ExprDelete(db, pDup);
102833           return;
102834         }
102835         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
102836         if( idxNew==0 ) return;
102837         pNew = &pWC->a[idxNew];
102838         pNew->iParent = idxTerm;
102839         pTerm = &pWC->a[idxTerm];
102840         pTerm->nChild = 1;
102841         pTerm->wtFlags |= TERM_COPIED;
102842       }else{
102843         pDup = pExpr;
102844         pNew = pTerm;
102845       }
102846       exprCommute(pParse, pDup);
102847       pLeft = pDup->pLeft;
102848       pNew->leftCursor = pLeft->iTable;
102849       pNew->u.leftColumn = pLeft->iColumn;
102850       testcase( (prereqLeft | extraRight) != prereqLeft );
102851       pNew->prereqRight = prereqLeft | extraRight;
102852       pNew->prereqAll = prereqAll;
102853       pNew->eOperator = operatorMask(pDup->op);
102854     }
102855   }
102856
102857 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
102858   /* If a term is the BETWEEN operator, create two new virtual terms
102859   ** that define the range that the BETWEEN implements.  For example:
102860   **
102861   **      a BETWEEN b AND c
102862   **
102863   ** is converted into:
102864   **
102865   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
102866   **
102867   ** The two new terms are added onto the end of the WhereClause object.
102868   ** The new terms are "dynamic" and are children of the original BETWEEN
102869   ** term.  That means that if the BETWEEN term is coded, the children are
102870   ** skipped.  Or, if the children are satisfied by an index, the original
102871   ** BETWEEN term is skipped.
102872   */
102873   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
102874     ExprList *pList = pExpr->x.pList;
102875     int i;
102876     static const u8 ops[] = {TK_GE, TK_LE};
102877     assert( pList!=0 );
102878     assert( pList->nExpr==2 );
102879     for(i=0; i<2; i++){
102880       Expr *pNewExpr;
102881       int idxNew;
102882       pNewExpr = sqlite3PExpr(pParse, ops[i], 
102883                              sqlite3ExprDup(db, pExpr->pLeft, 0),
102884                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
102885       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
102886       testcase( idxNew==0 );
102887       exprAnalyze(pSrc, pWC, idxNew);
102888       pTerm = &pWC->a[idxTerm];
102889       pWC->a[idxNew].iParent = idxTerm;
102890     }
102891     pTerm->nChild = 2;
102892   }
102893 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
102894
102895 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
102896   /* Analyze a term that is composed of two or more subterms connected by
102897   ** an OR operator.
102898   */
102899   else if( pExpr->op==TK_OR ){
102900     assert( pWC->op==TK_AND );
102901     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
102902     pTerm = &pWC->a[idxTerm];
102903   }
102904 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
102905
102906 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
102907   /* Add constraints to reduce the search space on a LIKE or GLOB
102908   ** operator.
102909   **
102910   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
102911   **
102912   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
102913   **
102914   ** The last character of the prefix "abc" is incremented to form the
102915   ** termination condition "abd".
102916   */
102917   if( pWC->op==TK_AND 
102918    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
102919   ){
102920     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
102921     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
102922     Expr *pNewExpr1;
102923     Expr *pNewExpr2;
102924     int idxNew1;
102925     int idxNew2;
102926     CollSeq *pColl;    /* Collating sequence to use */
102927
102928     pLeft = pExpr->x.pList->a[1].pExpr;
102929     pStr2 = sqlite3ExprDup(db, pStr1, 0);
102930     if( !db->mallocFailed ){
102931       u8 c, *pC;       /* Last character before the first wildcard */
102932       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
102933       c = *pC;
102934       if( noCase ){
102935         /* The point is to increment the last character before the first
102936         ** wildcard.  But if we increment '@', that will push it into the
102937         ** alphabetic range where case conversions will mess up the 
102938         ** inequality.  To avoid this, make sure to also run the full
102939         ** LIKE on all candidate expressions by clearing the isComplete flag
102940         */
102941         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
102942
102943
102944         c = sqlite3UpperToLower[c];
102945       }
102946       *pC = c + 1;
102947     }
102948     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
102949     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
102950                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
102951                      pStr1, 0);
102952     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
102953     testcase( idxNew1==0 );
102954     exprAnalyze(pSrc, pWC, idxNew1);
102955     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
102956                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
102957                      pStr2, 0);
102958     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
102959     testcase( idxNew2==0 );
102960     exprAnalyze(pSrc, pWC, idxNew2);
102961     pTerm = &pWC->a[idxTerm];
102962     if( isComplete ){
102963       pWC->a[idxNew1].iParent = idxTerm;
102964       pWC->a[idxNew2].iParent = idxTerm;
102965       pTerm->nChild = 2;
102966     }
102967   }
102968 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
102969
102970 #ifndef SQLITE_OMIT_VIRTUALTABLE
102971   /* Add a WO_MATCH auxiliary term to the constraint set if the
102972   ** current expression is of the form:  column MATCH expr.
102973   ** This information is used by the xBestIndex methods of
102974   ** virtual tables.  The native query optimizer does not attempt
102975   ** to do anything with MATCH functions.
102976   */
102977   if( isMatchOfColumn(pExpr) ){
102978     int idxNew;
102979     Expr *pRight, *pLeft;
102980     WhereTerm *pNewTerm;
102981     Bitmask prereqColumn, prereqExpr;
102982
102983     pRight = pExpr->x.pList->a[0].pExpr;
102984     pLeft = pExpr->x.pList->a[1].pExpr;
102985     prereqExpr = exprTableUsage(pMaskSet, pRight);
102986     prereqColumn = exprTableUsage(pMaskSet, pLeft);
102987     if( (prereqExpr & prereqColumn)==0 ){
102988       Expr *pNewExpr;
102989       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
102990                               0, sqlite3ExprDup(db, pRight, 0), 0);
102991       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
102992       testcase( idxNew==0 );
102993       pNewTerm = &pWC->a[idxNew];
102994       pNewTerm->prereqRight = prereqExpr;
102995       pNewTerm->leftCursor = pLeft->iTable;
102996       pNewTerm->u.leftColumn = pLeft->iColumn;
102997       pNewTerm->eOperator = WO_MATCH;
102998       pNewTerm->iParent = idxTerm;
102999       pTerm = &pWC->a[idxTerm];
103000       pTerm->nChild = 1;
103001       pTerm->wtFlags |= TERM_COPIED;
103002       pNewTerm->prereqAll = pTerm->prereqAll;
103003     }
103004   }
103005 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103006
103007 #ifdef SQLITE_ENABLE_STAT3
103008   /* When sqlite_stat3 histogram data is available an operator of the
103009   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103010   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103011   ** virtual term of that form.
103012   **
103013   ** Note that the virtual term must be tagged with TERM_VNULL.  This
103014   ** TERM_VNULL tag will suppress the not-null check at the beginning
103015   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103016   ** the start of the loop will prevent any results from being returned.
103017   */
103018   if( pExpr->op==TK_NOTNULL
103019    && pExpr->pLeft->op==TK_COLUMN
103020    && pExpr->pLeft->iColumn>=0
103021   ){
103022     Expr *pNewExpr;
103023     Expr *pLeft = pExpr->pLeft;
103024     int idxNew;
103025     WhereTerm *pNewTerm;
103026
103027     pNewExpr = sqlite3PExpr(pParse, TK_GT,
103028                             sqlite3ExprDup(db, pLeft, 0),
103029                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103030
103031     idxNew = whereClauseInsert(pWC, pNewExpr,
103032                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103033     if( idxNew ){
103034       pNewTerm = &pWC->a[idxNew];
103035       pNewTerm->prereqRight = 0;
103036       pNewTerm->leftCursor = pLeft->iTable;
103037       pNewTerm->u.leftColumn = pLeft->iColumn;
103038       pNewTerm->eOperator = WO_GT;
103039       pNewTerm->iParent = idxTerm;
103040       pTerm = &pWC->a[idxTerm];
103041       pTerm->nChild = 1;
103042       pTerm->wtFlags |= TERM_COPIED;
103043       pNewTerm->prereqAll = pTerm->prereqAll;
103044     }
103045   }
103046 #endif /* SQLITE_ENABLE_STAT */
103047
103048   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103049   ** an index for tables to the left of the join.
103050   */
103051   pTerm->prereqRight |= extraRight;
103052 }
103053
103054 /*
103055 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
103056 ** a reference to any table other than the iBase table.
103057 */
103058 static int referencesOtherTables(
103059   ExprList *pList,          /* Search expressions in ths list */
103060   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
103061   int iFirst,               /* Be searching with the iFirst-th expression */
103062   int iBase                 /* Ignore references to this table */
103063 ){
103064   Bitmask allowed = ~getMask(pMaskSet, iBase);
103065   while( iFirst<pList->nExpr ){
103066     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
103067       return 1;
103068     }
103069   }
103070   return 0;
103071 }
103072
103073 /*
103074 ** This function searches the expression list passed as the second argument
103075 ** for an expression of type TK_COLUMN that refers to the same column and
103076 ** uses the same collation sequence as the iCol'th column of index pIdx.
103077 ** Argument iBase is the cursor number used for the table that pIdx refers
103078 ** to.
103079 **
103080 ** If such an expression is found, its index in pList->a[] is returned. If
103081 ** no expression is found, -1 is returned.
103082 */
103083 static int findIndexCol(
103084   Parse *pParse,                  /* Parse context */
103085   ExprList *pList,                /* Expression list to search */
103086   int iBase,                      /* Cursor for table associated with pIdx */
103087   Index *pIdx,                    /* Index to match column of */
103088   int iCol                        /* Column of index to match */
103089 ){
103090   int i;
103091   const char *zColl = pIdx->azColl[iCol];
103092
103093   for(i=0; i<pList->nExpr; i++){
103094     Expr *p = pList->a[i].pExpr;
103095     if( p->op==TK_COLUMN
103096      && p->iColumn==pIdx->aiColumn[iCol]
103097      && p->iTable==iBase
103098     ){
103099       CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
103100       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
103101         return i;
103102       }
103103     }
103104   }
103105
103106   return -1;
103107 }
103108
103109 /*
103110 ** This routine determines if pIdx can be used to assist in processing a
103111 ** DISTINCT qualifier. In other words, it tests whether or not using this
103112 ** index for the outer loop guarantees that rows with equal values for
103113 ** all expressions in the pDistinct list are delivered grouped together.
103114 **
103115 ** For example, the query 
103116 **
103117 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
103118 **
103119 ** can benefit from any index on columns "b" and "c".
103120 */
103121 static int isDistinctIndex(
103122   Parse *pParse,                  /* Parsing context */
103123   WhereClause *pWC,               /* The WHERE clause */
103124   Index *pIdx,                    /* The index being considered */
103125   int base,                       /* Cursor number for the table pIdx is on */
103126   ExprList *pDistinct,            /* The DISTINCT expressions */
103127   int nEqCol                      /* Number of index columns with == */
103128 ){
103129   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
103130   int i;                          /* Iterator variable */
103131
103132   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
103133   testcase( pDistinct->nExpr==BMS-1 );
103134
103135   /* Loop through all the expressions in the distinct list. If any of them
103136   ** are not simple column references, return early. Otherwise, test if the
103137   ** WHERE clause contains a "col=X" clause. If it does, the expression
103138   ** can be ignored. If it does not, and the column does not belong to the
103139   ** same table as index pIdx, return early. Finally, if there is no
103140   ** matching "col=X" expression and the column is on the same table as pIdx,
103141   ** set the corresponding bit in variable mask.
103142   */
103143   for(i=0; i<pDistinct->nExpr; i++){
103144     WhereTerm *pTerm;
103145     Expr *p = pDistinct->a[i].pExpr;
103146     if( p->op!=TK_COLUMN ) return 0;
103147     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
103148     if( pTerm ){
103149       Expr *pX = pTerm->pExpr;
103150       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103151       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
103152       if( p1==p2 ) continue;
103153     }
103154     if( p->iTable!=base ) return 0;
103155     mask |= (((Bitmask)1) << i);
103156   }
103157
103158   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
103159     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
103160     if( iExpr<0 ) break;
103161     mask &= ~(((Bitmask)1) << iExpr);
103162   }
103163
103164   return (mask==0);
103165 }
103166
103167
103168 /*
103169 ** Return true if the DISTINCT expression-list passed as the third argument
103170 ** is redundant. A DISTINCT list is redundant if the database contains a
103171 ** UNIQUE index that guarantees that the result of the query will be distinct
103172 ** anyway.
103173 */
103174 static int isDistinctRedundant(
103175   Parse *pParse,
103176   SrcList *pTabList,
103177   WhereClause *pWC,
103178   ExprList *pDistinct
103179 ){
103180   Table *pTab;
103181   Index *pIdx;
103182   int i;                          
103183   int iBase;
103184
103185   /* If there is more than one table or sub-select in the FROM clause of
103186   ** this query, then it will not be possible to show that the DISTINCT 
103187   ** clause is redundant. */
103188   if( pTabList->nSrc!=1 ) return 0;
103189   iBase = pTabList->a[0].iCursor;
103190   pTab = pTabList->a[0].pTab;
103191
103192   /* If any of the expressions is an IPK column on table iBase, then return 
103193   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
103194   ** current SELECT is a correlated sub-query.
103195   */
103196   for(i=0; i<pDistinct->nExpr; i++){
103197     Expr *p = pDistinct->a[i].pExpr;
103198     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
103199   }
103200
103201   /* Loop through all indices on the table, checking each to see if it makes
103202   ** the DISTINCT qualifier redundant. It does so if:
103203   **
103204   **   1. The index is itself UNIQUE, and
103205   **
103206   **   2. All of the columns in the index are either part of the pDistinct
103207   **      list, or else the WHERE clause contains a term of the form "col=X",
103208   **      where X is a constant value. The collation sequences of the
103209   **      comparison and select-list expressions must match those of the index.
103210   **
103211   **   3. All of those index columns for which the WHERE clause does not
103212   **      contain a "col=X" term are subject to a NOT NULL constraint.
103213   */
103214   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103215     if( pIdx->onError==OE_None ) continue;
103216     for(i=0; i<pIdx->nColumn; i++){
103217       int iCol = pIdx->aiColumn[i];
103218       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
103219         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
103220         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
103221           break;
103222         }
103223       }
103224     }
103225     if( i==pIdx->nColumn ){
103226       /* This index implies that the DISTINCT qualifier is redundant. */
103227       return 1;
103228     }
103229   }
103230
103231   return 0;
103232 }
103233
103234 /*
103235 ** This routine decides if pIdx can be used to satisfy the ORDER BY
103236 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
103237 ** ORDER BY clause, this routine returns 0.
103238 **
103239 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
103240 ** left-most table in the FROM clause of that same SELECT statement and
103241 ** the table has a cursor number of "base".  pIdx is an index on pTab.
103242 **
103243 ** nEqCol is the number of columns of pIdx that are used as equality
103244 ** constraints.  Any of these columns may be missing from the ORDER BY
103245 ** clause and the match can still be a success.
103246 **
103247 ** All terms of the ORDER BY that match against the index must be either
103248 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
103249 ** index do not need to satisfy this constraint.)  The *pbRev value is
103250 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
103251 ** the ORDER BY clause is all ASC.
103252 */
103253 static int isSortingIndex(
103254   Parse *pParse,          /* Parsing context */
103255   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
103256   Index *pIdx,            /* The index we are testing */
103257   int base,               /* Cursor number for the table to be sorted */
103258   ExprList *pOrderBy,     /* The ORDER BY clause */
103259   int nEqCol,             /* Number of index columns with == constraints */
103260   int wsFlags,            /* Index usages flags */
103261   int *pbRev              /* Set to 1 if ORDER BY is DESC */
103262 ){
103263   int i, j;                       /* Loop counters */
103264   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
103265   int nTerm;                      /* Number of ORDER BY terms */
103266   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
103267   sqlite3 *db = pParse->db;
103268
103269   if( !pOrderBy ) return 0;
103270   if( wsFlags & WHERE_COLUMN_IN ) return 0;
103271   if( pIdx->bUnordered ) return 0;
103272
103273   nTerm = pOrderBy->nExpr;
103274   assert( nTerm>0 );
103275
103276   /* Argument pIdx must either point to a 'real' named index structure, 
103277   ** or an index structure allocated on the stack by bestBtreeIndex() to
103278   ** represent the rowid index that is part of every table.  */
103279   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
103280
103281   /* Match terms of the ORDER BY clause against columns of
103282   ** the index.
103283   **
103284   ** Note that indices have pIdx->nColumn regular columns plus
103285   ** one additional column containing the rowid.  The rowid column
103286   ** of the index is also allowed to match against the ORDER BY
103287   ** clause.
103288   */
103289   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
103290     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
103291     CollSeq *pColl;    /* The collating sequence of pExpr */
103292     int termSortOrder; /* Sort order for this term */
103293     int iColumn;       /* The i-th column of the index.  -1 for rowid */
103294     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
103295     const char *zColl; /* Name of the collating sequence for i-th index term */
103296
103297     pExpr = pTerm->pExpr;
103298     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
103299       /* Can not use an index sort on anything that is not a column in the
103300       ** left-most table of the FROM clause */
103301       break;
103302     }
103303     pColl = sqlite3ExprCollSeq(pParse, pExpr);
103304     if( !pColl ){
103305       pColl = db->pDfltColl;
103306     }
103307     if( pIdx->zName && i<pIdx->nColumn ){
103308       iColumn = pIdx->aiColumn[i];
103309       if( iColumn==pIdx->pTable->iPKey ){
103310         iColumn = -1;
103311       }
103312       iSortOrder = pIdx->aSortOrder[i];
103313       zColl = pIdx->azColl[i];
103314     }else{
103315       iColumn = -1;
103316       iSortOrder = 0;
103317       zColl = pColl->zName;
103318     }
103319     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
103320       /* Term j of the ORDER BY clause does not match column i of the index */
103321       if( i<nEqCol ){
103322         /* If an index column that is constrained by == fails to match an
103323         ** ORDER BY term, that is OK.  Just ignore that column of the index
103324         */
103325         continue;
103326       }else if( i==pIdx->nColumn ){
103327         /* Index column i is the rowid.  All other terms match. */
103328         break;
103329       }else{
103330         /* If an index column fails to match and is not constrained by ==
103331         ** then the index cannot satisfy the ORDER BY constraint.
103332         */
103333         return 0;
103334       }
103335     }
103336     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
103337     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
103338     assert( iSortOrder==0 || iSortOrder==1 );
103339     termSortOrder = iSortOrder ^ pTerm->sortOrder;
103340     if( i>nEqCol ){
103341       if( termSortOrder!=sortOrder ){
103342         /* Indices can only be used if all ORDER BY terms past the
103343         ** equality constraints are all either DESC or ASC. */
103344         return 0;
103345       }
103346     }else{
103347       sortOrder = termSortOrder;
103348     }
103349     j++;
103350     pTerm++;
103351     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
103352       /* If the indexed column is the primary key and everything matches
103353       ** so far and none of the ORDER BY terms to the right reference other
103354       ** tables in the join, then we are assured that the index can be used 
103355       ** to sort because the primary key is unique and so none of the other
103356       ** columns will make any difference
103357       */
103358       j = nTerm;
103359     }
103360   }
103361
103362   *pbRev = sortOrder!=0;
103363   if( j>=nTerm ){
103364     /* All terms of the ORDER BY clause are covered by this index so
103365     ** this index can be used for sorting. */
103366     return 1;
103367   }
103368   if( pIdx->onError!=OE_None && i==pIdx->nColumn
103369       && (wsFlags & WHERE_COLUMN_NULL)==0
103370       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) 
103371   ){
103372     Column *aCol = pIdx->pTable->aCol;
103373
103374     /* All terms of this index match some prefix of the ORDER BY clause,
103375     ** the index is UNIQUE, and no terms on the tail of the ORDER BY
103376     ** refer to other tables in a join. So, assuming that the index entries
103377     ** visited contain no NULL values, then this index delivers rows in
103378     ** the required order.
103379     **
103380     ** It is not possible for any of the first nEqCol index fields to be
103381     ** NULL (since the corresponding "=" operator in the WHERE clause would 
103382     ** not be true). So if all remaining index columns have NOT NULL 
103383     ** constaints attached to them, we can be confident that the visited
103384     ** index entries are free of NULLs.  */
103385     for(i=nEqCol; i<pIdx->nColumn; i++){
103386       if( aCol[pIdx->aiColumn[i]].notNull==0 ) break;
103387     }
103388     return (i==pIdx->nColumn);
103389   }
103390   return 0;
103391 }
103392
103393 /*
103394 ** Prepare a crude estimate of the logarithm of the input value.
103395 ** The results need not be exact.  This is only used for estimating
103396 ** the total cost of performing operations with O(logN) or O(NlogN)
103397 ** complexity.  Because N is just a guess, it is no great tragedy if
103398 ** logN is a little off.
103399 */
103400 static double estLog(double N){
103401   double logN = 1;
103402   double x = 10;
103403   while( N>x ){
103404     logN += 1;
103405     x *= 10;
103406   }
103407   return logN;
103408 }
103409
103410 /*
103411 ** Two routines for printing the content of an sqlite3_index_info
103412 ** structure.  Used for testing and debugging only.  If neither
103413 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
103414 ** are no-ops.
103415 */
103416 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
103417 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
103418   int i;
103419   if( !sqlite3WhereTrace ) return;
103420   for(i=0; i<p->nConstraint; i++){
103421     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
103422        i,
103423        p->aConstraint[i].iColumn,
103424        p->aConstraint[i].iTermOffset,
103425        p->aConstraint[i].op,
103426        p->aConstraint[i].usable);
103427   }
103428   for(i=0; i<p->nOrderBy; i++){
103429     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
103430        i,
103431        p->aOrderBy[i].iColumn,
103432        p->aOrderBy[i].desc);
103433   }
103434 }
103435 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
103436   int i;
103437   if( !sqlite3WhereTrace ) return;
103438   for(i=0; i<p->nConstraint; i++){
103439     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
103440        i,
103441        p->aConstraintUsage[i].argvIndex,
103442        p->aConstraintUsage[i].omit);
103443   }
103444   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
103445   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
103446   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
103447   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
103448 }
103449 #else
103450 #define TRACE_IDX_INPUTS(A)
103451 #define TRACE_IDX_OUTPUTS(A)
103452 #endif
103453
103454 /* 
103455 ** Required because bestIndex() is called by bestOrClauseIndex() 
103456 */
103457 static void bestIndex(
103458     Parse*, WhereClause*, struct SrcList_item*,
103459     Bitmask, Bitmask, ExprList*, WhereCost*);
103460
103461 /*
103462 ** This routine attempts to find an scanning strategy that can be used 
103463 ** to optimize an 'OR' expression that is part of a WHERE clause. 
103464 **
103465 ** The table associated with FROM clause term pSrc may be either a
103466 ** regular B-Tree table or a virtual table.
103467 */
103468 static void bestOrClauseIndex(
103469   Parse *pParse,              /* The parsing context */
103470   WhereClause *pWC,           /* The WHERE clause */
103471   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103472   Bitmask notReady,           /* Mask of cursors not available for indexing */
103473   Bitmask notValid,           /* Cursors not available for any purpose */
103474   ExprList *pOrderBy,         /* The ORDER BY clause */
103475   WhereCost *pCost            /* Lowest cost query plan */
103476 ){
103477 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
103478   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
103479   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
103480   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
103481   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
103482
103483   /* The OR-clause optimization is disallowed if the INDEXED BY or
103484   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
103485   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
103486     return;
103487   }
103488   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
103489     return;
103490   }
103491
103492   /* Search the WHERE clause terms for a usable WO_OR term. */
103493   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
103494     if( pTerm->eOperator==WO_OR 
103495      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
103496      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
103497     ){
103498       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
103499       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
103500       WhereTerm *pOrTerm;
103501       int flags = WHERE_MULTI_OR;
103502       double rTotal = 0;
103503       double nRow = 0;
103504       Bitmask used = 0;
103505
103506       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
103507         WhereCost sTermCost;
103508         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
103509           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
103510         ));
103511         if( pOrTerm->eOperator==WO_AND ){
103512           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
103513           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
103514         }else if( pOrTerm->leftCursor==iCur ){
103515           WhereClause tempWC;
103516           tempWC.pParse = pWC->pParse;
103517           tempWC.pMaskSet = pWC->pMaskSet;
103518           tempWC.pOuter = pWC;
103519           tempWC.op = TK_AND;
103520           tempWC.a = pOrTerm;
103521           tempWC.wctrlFlags = 0;
103522           tempWC.nTerm = 1;
103523           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
103524         }else{
103525           continue;
103526         }
103527         rTotal += sTermCost.rCost;
103528         nRow += sTermCost.plan.nRow;
103529         used |= sTermCost.used;
103530         if( rTotal>=pCost->rCost ) break;
103531       }
103532
103533       /* If there is an ORDER BY clause, increase the scan cost to account 
103534       ** for the cost of the sort. */
103535       if( pOrderBy!=0 ){
103536         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
103537                     rTotal, rTotal+nRow*estLog(nRow)));
103538         rTotal += nRow*estLog(nRow);
103539       }
103540
103541       /* If the cost of scanning using this OR term for optimization is
103542       ** less than the current cost stored in pCost, replace the contents
103543       ** of pCost. */
103544       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
103545       if( rTotal<pCost->rCost ){
103546         pCost->rCost = rTotal;
103547         pCost->used = used;
103548         pCost->plan.nRow = nRow;
103549         pCost->plan.wsFlags = flags;
103550         pCost->plan.u.pTerm = pTerm;
103551       }
103552     }
103553   }
103554 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
103555 }
103556
103557 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
103558 /*
103559 ** Return TRUE if the WHERE clause term pTerm is of a form where it
103560 ** could be used with an index to access pSrc, assuming an appropriate
103561 ** index existed.
103562 */
103563 static int termCanDriveIndex(
103564   WhereTerm *pTerm,              /* WHERE clause term to check */
103565   struct SrcList_item *pSrc,     /* Table we are trying to access */
103566   Bitmask notReady               /* Tables in outer loops of the join */
103567 ){
103568   char aff;
103569   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
103570   if( pTerm->eOperator!=WO_EQ ) return 0;
103571   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
103572   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
103573   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
103574   return 1;
103575 }
103576 #endif
103577
103578 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
103579 /*
103580 ** If the query plan for pSrc specified in pCost is a full table scan
103581 ** and indexing is allows (if there is no NOT INDEXED clause) and it
103582 ** possible to construct a transient index that would perform better
103583 ** than a full table scan even when the cost of constructing the index
103584 ** is taken into account, then alter the query plan to use the
103585 ** transient index.
103586 */
103587 static void bestAutomaticIndex(
103588   Parse *pParse,              /* The parsing context */
103589   WhereClause *pWC,           /* The WHERE clause */
103590   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103591   Bitmask notReady,           /* Mask of cursors that are not available */
103592   WhereCost *pCost            /* Lowest cost query plan */
103593 ){
103594   double nTableRow;           /* Rows in the input table */
103595   double logN;                /* log(nTableRow) */
103596   double costTempIdx;         /* per-query cost of the transient index */
103597   WhereTerm *pTerm;           /* A single term of the WHERE clause */
103598   WhereTerm *pWCEnd;          /* End of pWC->a[] */
103599   Table *pTable;              /* Table tht might be indexed */
103600
103601   if( pParse->nQueryLoop<=(double)1 ){
103602     /* There is no point in building an automatic index for a single scan */
103603     return;
103604   }
103605   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
103606     /* Automatic indices are disabled at run-time */
103607     return;
103608   }
103609   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
103610     /* We already have some kind of index in use for this query. */
103611     return;
103612   }
103613   if( pSrc->notIndexed ){
103614     /* The NOT INDEXED clause appears in the SQL. */
103615     return;
103616   }
103617   if( pSrc->isCorrelated ){
103618     /* The source is a correlated sub-query. No point in indexing it. */
103619     return;
103620   }
103621
103622   assert( pParse->nQueryLoop >= (double)1 );
103623   pTable = pSrc->pTab;
103624   nTableRow = pTable->nRowEst;
103625   logN = estLog(nTableRow);
103626   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
103627   if( costTempIdx>=pCost->rCost ){
103628     /* The cost of creating the transient table would be greater than
103629     ** doing the full table scan */
103630     return;
103631   }
103632
103633   /* Search for any equality comparison term */
103634   pWCEnd = &pWC->a[pWC->nTerm];
103635   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
103636     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
103637       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
103638                     pCost->rCost, costTempIdx));
103639       pCost->rCost = costTempIdx;
103640       pCost->plan.nRow = logN + 1;
103641       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
103642       pCost->used = pTerm->prereqRight;
103643       break;
103644     }
103645   }
103646 }
103647 #else
103648 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
103649 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
103650
103651
103652 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
103653 /*
103654 ** Generate code to construct the Index object for an automatic index
103655 ** and to set up the WhereLevel object pLevel so that the code generator
103656 ** makes use of the automatic index.
103657 */
103658 static void constructAutomaticIndex(
103659   Parse *pParse,              /* The parsing context */
103660   WhereClause *pWC,           /* The WHERE clause */
103661   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
103662   Bitmask notReady,           /* Mask of cursors that are not available */
103663   WhereLevel *pLevel          /* Write new index here */
103664 ){
103665   int nColumn;                /* Number of columns in the constructed index */
103666   WhereTerm *pTerm;           /* A single term of the WHERE clause */
103667   WhereTerm *pWCEnd;          /* End of pWC->a[] */
103668   int nByte;                  /* Byte of memory needed for pIdx */
103669   Index *pIdx;                /* Object describing the transient index */
103670   Vdbe *v;                    /* Prepared statement under construction */
103671   int addrInit;               /* Address of the initialization bypass jump */
103672   Table *pTable;              /* The table being indexed */
103673   KeyInfo *pKeyinfo;          /* Key information for the index */   
103674   int addrTop;                /* Top of the index fill loop */
103675   int regRecord;              /* Register holding an index record */
103676   int n;                      /* Column counter */
103677   int i;                      /* Loop counter */
103678   int mxBitCol;               /* Maximum column in pSrc->colUsed */
103679   CollSeq *pColl;             /* Collating sequence to on a column */
103680   Bitmask idxCols;            /* Bitmap of columns used for indexing */
103681   Bitmask extraCols;          /* Bitmap of additional columns */
103682
103683   /* Generate code to skip over the creation and initialization of the
103684   ** transient index on 2nd and subsequent iterations of the loop. */
103685   v = pParse->pVdbe;
103686   assert( v!=0 );
103687   addrInit = sqlite3CodeOnce(pParse);
103688
103689   /* Count the number of columns that will be added to the index
103690   ** and used to match WHERE clause constraints */
103691   nColumn = 0;
103692   pTable = pSrc->pTab;
103693   pWCEnd = &pWC->a[pWC->nTerm];
103694   idxCols = 0;
103695   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
103696     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
103697       int iCol = pTerm->u.leftColumn;
103698       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
103699       testcase( iCol==BMS );
103700       testcase( iCol==BMS-1 );
103701       if( (idxCols & cMask)==0 ){
103702         nColumn++;
103703         idxCols |= cMask;
103704       }
103705     }
103706   }
103707   assert( nColumn>0 );
103708   pLevel->plan.nEq = nColumn;
103709
103710   /* Count the number of additional columns needed to create a
103711   ** covering index.  A "covering index" is an index that contains all
103712   ** columns that are needed by the query.  With a covering index, the
103713   ** original table never needs to be accessed.  Automatic indices must
103714   ** be a covering index because the index will not be updated if the
103715   ** original table changes and the index and table cannot both be used
103716   ** if they go out of sync.
103717   */
103718   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
103719   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
103720   testcase( pTable->nCol==BMS-1 );
103721   testcase( pTable->nCol==BMS-2 );
103722   for(i=0; i<mxBitCol; i++){
103723     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
103724   }
103725   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
103726     nColumn += pTable->nCol - BMS + 1;
103727   }
103728   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
103729
103730   /* Construct the Index object to describe this index */
103731   nByte = sizeof(Index);
103732   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
103733   nByte += nColumn*sizeof(char*);   /* Index.azColl */
103734   nByte += nColumn;                 /* Index.aSortOrder */
103735   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
103736   if( pIdx==0 ) return;
103737   pLevel->plan.u.pIdx = pIdx;
103738   pIdx->azColl = (char**)&pIdx[1];
103739   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
103740   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
103741   pIdx->zName = "auto-index";
103742   pIdx->nColumn = nColumn;
103743   pIdx->pTable = pTable;
103744   n = 0;
103745   idxCols = 0;
103746   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
103747     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
103748       int iCol = pTerm->u.leftColumn;
103749       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
103750       if( (idxCols & cMask)==0 ){
103751         Expr *pX = pTerm->pExpr;
103752         idxCols |= cMask;
103753         pIdx->aiColumn[n] = pTerm->u.leftColumn;
103754         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103755         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
103756         n++;
103757       }
103758     }
103759   }
103760   assert( (u32)n==pLevel->plan.nEq );
103761
103762   /* Add additional columns needed to make the automatic index into
103763   ** a covering index */
103764   for(i=0; i<mxBitCol; i++){
103765     if( extraCols & (((Bitmask)1)<<i) ){
103766       pIdx->aiColumn[n] = i;
103767       pIdx->azColl[n] = "BINARY";
103768       n++;
103769     }
103770   }
103771   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
103772     for(i=BMS-1; i<pTable->nCol; i++){
103773       pIdx->aiColumn[n] = i;
103774       pIdx->azColl[n] = "BINARY";
103775       n++;
103776     }
103777   }
103778   assert( n==nColumn );
103779
103780   /* Create the automatic index */
103781   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
103782   assert( pLevel->iIdxCur>=0 );
103783   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
103784                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
103785   VdbeComment((v, "for %s", pTable->zName));
103786
103787   /* Fill the automatic index with content */
103788   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
103789   regRecord = sqlite3GetTempReg(pParse);
103790   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
103791   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
103792   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
103793   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
103794   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
103795   sqlite3VdbeJumpHere(v, addrTop);
103796   sqlite3ReleaseTempReg(pParse, regRecord);
103797   
103798   /* Jump here when skipping the initialization */
103799   sqlite3VdbeJumpHere(v, addrInit);
103800 }
103801 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
103802
103803 #ifndef SQLITE_OMIT_VIRTUALTABLE
103804 /*
103805 ** Allocate and populate an sqlite3_index_info structure. It is the 
103806 ** responsibility of the caller to eventually release the structure
103807 ** by passing the pointer returned by this function to sqlite3_free().
103808 */
103809 static sqlite3_index_info *allocateIndexInfo(
103810   Parse *pParse, 
103811   WhereClause *pWC,
103812   struct SrcList_item *pSrc,
103813   ExprList *pOrderBy
103814 ){
103815   int i, j;
103816   int nTerm;
103817   struct sqlite3_index_constraint *pIdxCons;
103818   struct sqlite3_index_orderby *pIdxOrderBy;
103819   struct sqlite3_index_constraint_usage *pUsage;
103820   WhereTerm *pTerm;
103821   int nOrderBy;
103822   sqlite3_index_info *pIdxInfo;
103823
103824   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
103825
103826   /* Count the number of possible WHERE clause constraints referring
103827   ** to this virtual table */
103828   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
103829     if( pTerm->leftCursor != pSrc->iCursor ) continue;
103830     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
103831     testcase( pTerm->eOperator==WO_IN );
103832     testcase( pTerm->eOperator==WO_ISNULL );
103833     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
103834     if( pTerm->wtFlags & TERM_VNULL ) continue;
103835     nTerm++;
103836   }
103837
103838   /* If the ORDER BY clause contains only columns in the current 
103839   ** virtual table then allocate space for the aOrderBy part of
103840   ** the sqlite3_index_info structure.
103841   */
103842   nOrderBy = 0;
103843   if( pOrderBy ){
103844     for(i=0; i<pOrderBy->nExpr; i++){
103845       Expr *pExpr = pOrderBy->a[i].pExpr;
103846       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
103847     }
103848     if( i==pOrderBy->nExpr ){
103849       nOrderBy = pOrderBy->nExpr;
103850     }
103851   }
103852
103853   /* Allocate the sqlite3_index_info structure
103854   */
103855   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
103856                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
103857                            + sizeof(*pIdxOrderBy)*nOrderBy );
103858   if( pIdxInfo==0 ){
103859     sqlite3ErrorMsg(pParse, "out of memory");
103860     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
103861     return 0;
103862   }
103863
103864   /* Initialize the structure.  The sqlite3_index_info structure contains
103865   ** many fields that are declared "const" to prevent xBestIndex from
103866   ** changing them.  We have to do some funky casting in order to
103867   ** initialize those fields.
103868   */
103869   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
103870   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
103871   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
103872   *(int*)&pIdxInfo->nConstraint = nTerm;
103873   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
103874   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
103875   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
103876   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
103877                                                                    pUsage;
103878
103879   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
103880     if( pTerm->leftCursor != pSrc->iCursor ) continue;
103881     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
103882     testcase( pTerm->eOperator==WO_IN );
103883     testcase( pTerm->eOperator==WO_ISNULL );
103884     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
103885     if( pTerm->wtFlags & TERM_VNULL ) continue;
103886     pIdxCons[j].iColumn = pTerm->u.leftColumn;
103887     pIdxCons[j].iTermOffset = i;
103888     pIdxCons[j].op = (u8)pTerm->eOperator;
103889     /* The direct assignment in the previous line is possible only because
103890     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
103891     ** following asserts verify this fact. */
103892     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
103893     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
103894     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
103895     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
103896     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
103897     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
103898     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
103899     j++;
103900   }
103901   for(i=0; i<nOrderBy; i++){
103902     Expr *pExpr = pOrderBy->a[i].pExpr;
103903     pIdxOrderBy[i].iColumn = pExpr->iColumn;
103904     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
103905   }
103906
103907   return pIdxInfo;
103908 }
103909
103910 /*
103911 ** The table object reference passed as the second argument to this function
103912 ** must represent a virtual table. This function invokes the xBestIndex()
103913 ** method of the virtual table with the sqlite3_index_info pointer passed
103914 ** as the argument.
103915 **
103916 ** If an error occurs, pParse is populated with an error message and a
103917 ** non-zero value is returned. Otherwise, 0 is returned and the output
103918 ** part of the sqlite3_index_info structure is left populated.
103919 **
103920 ** Whether or not an error is returned, it is the responsibility of the
103921 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
103922 ** that this is required.
103923 */
103924 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
103925   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
103926   int i;
103927   int rc;
103928
103929   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
103930   TRACE_IDX_INPUTS(p);
103931   rc = pVtab->pModule->xBestIndex(pVtab, p);
103932   TRACE_IDX_OUTPUTS(p);
103933
103934   if( rc!=SQLITE_OK ){
103935     if( rc==SQLITE_NOMEM ){
103936       pParse->db->mallocFailed = 1;
103937     }else if( !pVtab->zErrMsg ){
103938       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
103939     }else{
103940       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
103941     }
103942   }
103943   sqlite3_free(pVtab->zErrMsg);
103944   pVtab->zErrMsg = 0;
103945
103946   for(i=0; i<p->nConstraint; i++){
103947     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
103948       sqlite3ErrorMsg(pParse, 
103949           "table %s: xBestIndex returned an invalid plan", pTab->zName);
103950     }
103951   }
103952
103953   return pParse->nErr;
103954 }
103955
103956
103957 /*
103958 ** Compute the best index for a virtual table.
103959 **
103960 ** The best index is computed by the xBestIndex method of the virtual
103961 ** table module.  This routine is really just a wrapper that sets up
103962 ** the sqlite3_index_info structure that is used to communicate with
103963 ** xBestIndex.
103964 **
103965 ** In a join, this routine might be called multiple times for the
103966 ** same virtual table.  The sqlite3_index_info structure is created
103967 ** and initialized on the first invocation and reused on all subsequent
103968 ** invocations.  The sqlite3_index_info structure is also used when
103969 ** code is generated to access the virtual table.  The whereInfoDelete() 
103970 ** routine takes care of freeing the sqlite3_index_info structure after
103971 ** everybody has finished with it.
103972 */
103973 static void bestVirtualIndex(
103974   Parse *pParse,                  /* The parsing context */
103975   WhereClause *pWC,               /* The WHERE clause */
103976   struct SrcList_item *pSrc,      /* The FROM clause term to search */
103977   Bitmask notReady,               /* Mask of cursors not available for index */
103978   Bitmask notValid,               /* Cursors not valid for any purpose */
103979   ExprList *pOrderBy,             /* The order by clause */
103980   WhereCost *pCost,               /* Lowest cost query plan */
103981   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
103982 ){
103983   Table *pTab = pSrc->pTab;
103984   sqlite3_index_info *pIdxInfo;
103985   struct sqlite3_index_constraint *pIdxCons;
103986   struct sqlite3_index_constraint_usage *pUsage;
103987   WhereTerm *pTerm;
103988   int i, j;
103989   int nOrderBy;
103990   double rCost;
103991
103992   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
103993   ** malloc in allocateIndexInfo() fails and this function returns leaving
103994   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
103995   */
103996   memset(pCost, 0, sizeof(*pCost));
103997   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
103998
103999   /* If the sqlite3_index_info structure has not been previously
104000   ** allocated and initialized, then allocate and initialize it now.
104001   */
104002   pIdxInfo = *ppIdxInfo;
104003   if( pIdxInfo==0 ){
104004     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
104005   }
104006   if( pIdxInfo==0 ){
104007     return;
104008   }
104009
104010   /* At this point, the sqlite3_index_info structure that pIdxInfo points
104011   ** to will have been initialized, either during the current invocation or
104012   ** during some prior invocation.  Now we just have to customize the
104013   ** details of pIdxInfo for the current invocation and pass it to
104014   ** xBestIndex.
104015   */
104016
104017   /* The module name must be defined. Also, by this point there must
104018   ** be a pointer to an sqlite3_vtab structure. Otherwise
104019   ** sqlite3ViewGetColumnNames() would have picked up the error. 
104020   */
104021   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104022   assert( sqlite3GetVTable(pParse->db, pTab) );
104023
104024   /* Set the aConstraint[].usable fields and initialize all 
104025   ** output variables to zero.
104026   **
104027   ** aConstraint[].usable is true for constraints where the right-hand
104028   ** side contains only references to tables to the left of the current
104029   ** table.  In other words, if the constraint is of the form:
104030   **
104031   **           column = expr
104032   **
104033   ** and we are evaluating a join, then the constraint on column is 
104034   ** only valid if all tables referenced in expr occur to the left
104035   ** of the table containing column.
104036   **
104037   ** The aConstraints[] array contains entries for all constraints
104038   ** on the current table.  That way we only have to compute it once
104039   ** even though we might try to pick the best index multiple times.
104040   ** For each attempt at picking an index, the order of tables in the
104041   ** join might be different so we have to recompute the usable flag
104042   ** each time.
104043   */
104044   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104045   pUsage = pIdxInfo->aConstraintUsage;
104046   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104047     j = pIdxCons->iTermOffset;
104048     pTerm = &pWC->a[j];
104049     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
104050   }
104051   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104052   if( pIdxInfo->needToFreeIdxStr ){
104053     sqlite3_free(pIdxInfo->idxStr);
104054   }
104055   pIdxInfo->idxStr = 0;
104056   pIdxInfo->idxNum = 0;
104057   pIdxInfo->needToFreeIdxStr = 0;
104058   pIdxInfo->orderByConsumed = 0;
104059   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
104060   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
104061   nOrderBy = pIdxInfo->nOrderBy;
104062   if( !pOrderBy ){
104063     pIdxInfo->nOrderBy = 0;
104064   }
104065
104066   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104067     return;
104068   }
104069
104070   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104071   for(i=0; i<pIdxInfo->nConstraint; i++){
104072     if( pUsage[i].argvIndex>0 ){
104073       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104074     }
104075   }
104076
104077   /* If there is an ORDER BY clause, and the selected virtual table index
104078   ** does not satisfy it, increase the cost of the scan accordingly. This
104079   ** matches the processing for non-virtual tables in bestBtreeIndex().
104080   */
104081   rCost = pIdxInfo->estimatedCost;
104082   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
104083     rCost += estLog(rCost)*rCost;
104084   }
104085
104086   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
104087   ** inital value of lowestCost in this loop. If it is, then the
104088   ** (cost<lowestCost) test below will never be true.
104089   ** 
104090   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
104091   ** is defined.
104092   */
104093   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
104094     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
104095   }else{
104096     pCost->rCost = rCost;
104097   }
104098   pCost->plan.u.pVtabIdx = pIdxInfo;
104099   if( pIdxInfo->orderByConsumed ){
104100     pCost->plan.wsFlags |= WHERE_ORDERBY;
104101   }
104102   pCost->plan.nEq = 0;
104103   pIdxInfo->nOrderBy = nOrderBy;
104104
104105   /* Try to find a more efficient access pattern by using multiple indexes
104106   ** to optimize an OR expression within the WHERE clause. 
104107   */
104108   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104109 }
104110 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104111
104112 #ifdef SQLITE_ENABLE_STAT3
104113 /*
104114 ** Estimate the location of a particular key among all keys in an
104115 ** index.  Store the results in aStat as follows:
104116 **
104117 **    aStat[0]      Est. number of rows less than pVal
104118 **    aStat[1]      Est. number of rows equal to pVal
104119 **
104120 ** Return SQLITE_OK on success.
104121 */
104122 static int whereKeyStats(
104123   Parse *pParse,              /* Database connection */
104124   Index *pIdx,                /* Index to consider domain of */
104125   sqlite3_value *pVal,        /* Value to consider */
104126   int roundUp,                /* Round up if true.  Round down if false */
104127   tRowcnt *aStat              /* OUT: stats written here */
104128 ){
104129   tRowcnt n;
104130   IndexSample *aSample;
104131   int i, eType;
104132   int isEq = 0;
104133   i64 v;
104134   double r, rS;
104135
104136   assert( roundUp==0 || roundUp==1 );
104137   assert( pIdx->nSample>0 );
104138   if( pVal==0 ) return SQLITE_ERROR;
104139   n = pIdx->aiRowEst[0];
104140   aSample = pIdx->aSample;
104141   eType = sqlite3_value_type(pVal);
104142
104143   if( eType==SQLITE_INTEGER ){
104144     v = sqlite3_value_int64(pVal);
104145     r = (i64)v;
104146     for(i=0; i<pIdx->nSample; i++){
104147       if( aSample[i].eType==SQLITE_NULL ) continue;
104148       if( aSample[i].eType>=SQLITE_TEXT ) break;
104149       if( aSample[i].eType==SQLITE_INTEGER ){
104150         if( aSample[i].u.i>=v ){
104151           isEq = aSample[i].u.i==v;
104152           break;
104153         }
104154       }else{
104155         assert( aSample[i].eType==SQLITE_FLOAT );
104156         if( aSample[i].u.r>=r ){
104157           isEq = aSample[i].u.r==r;
104158           break;
104159         }
104160       }
104161     }
104162   }else if( eType==SQLITE_FLOAT ){
104163     r = sqlite3_value_double(pVal);
104164     for(i=0; i<pIdx->nSample; i++){
104165       if( aSample[i].eType==SQLITE_NULL ) continue;
104166       if( aSample[i].eType>=SQLITE_TEXT ) break;
104167       if( aSample[i].eType==SQLITE_FLOAT ){
104168         rS = aSample[i].u.r;
104169       }else{
104170         rS = aSample[i].u.i;
104171       }
104172       if( rS>=r ){
104173         isEq = rS==r;
104174         break;
104175       }
104176     }
104177   }else if( eType==SQLITE_NULL ){
104178     i = 0;
104179     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
104180   }else{
104181     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
104182     for(i=0; i<pIdx->nSample; i++){
104183       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
104184         break;
104185       }
104186     }
104187     if( i<pIdx->nSample ){      
104188       sqlite3 *db = pParse->db;
104189       CollSeq *pColl;
104190       const u8 *z;
104191       if( eType==SQLITE_BLOB ){
104192         z = (const u8 *)sqlite3_value_blob(pVal);
104193         pColl = db->pDfltColl;
104194         assert( pColl->enc==SQLITE_UTF8 );
104195       }else{
104196         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
104197         if( pColl==0 ){
104198           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
104199                           *pIdx->azColl);
104200           return SQLITE_ERROR;
104201         }
104202         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
104203         if( !z ){
104204           return SQLITE_NOMEM;
104205         }
104206         assert( z && pColl && pColl->xCmp );
104207       }
104208       n = sqlite3ValueBytes(pVal, pColl->enc);
104209   
104210       for(; i<pIdx->nSample; i++){
104211         int c;
104212         int eSampletype = aSample[i].eType;
104213         if( eSampletype<eType ) continue;
104214         if( eSampletype!=eType ) break;
104215 #ifndef SQLITE_OMIT_UTF16
104216         if( pColl->enc!=SQLITE_UTF8 ){
104217           int nSample;
104218           char *zSample = sqlite3Utf8to16(
104219               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
104220           );
104221           if( !zSample ){
104222             assert( db->mallocFailed );
104223             return SQLITE_NOMEM;
104224           }
104225           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
104226           sqlite3DbFree(db, zSample);
104227         }else
104228 #endif
104229         {
104230           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
104231         }
104232         if( c>=0 ){
104233           if( c==0 ) isEq = 1;
104234           break;
104235         }
104236       }
104237     }
104238   }
104239
104240   /* At this point, aSample[i] is the first sample that is greater than
104241   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
104242   ** than pVal.  If aSample[i]==pVal, then isEq==1.
104243   */
104244   if( isEq ){
104245     assert( i<pIdx->nSample );
104246     aStat[0] = aSample[i].nLt;
104247     aStat[1] = aSample[i].nEq;
104248   }else{
104249     tRowcnt iLower, iUpper, iGap;
104250     if( i==0 ){
104251       iLower = 0;
104252       iUpper = aSample[0].nLt;
104253     }else{
104254       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
104255       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
104256     }
104257     aStat[1] = pIdx->avgEq;
104258     if( iLower>=iUpper ){
104259       iGap = 0;
104260     }else{
104261       iGap = iUpper - iLower;
104262     }
104263     if( roundUp ){
104264       iGap = (iGap*2)/3;
104265     }else{
104266       iGap = iGap/3;
104267     }
104268     aStat[0] = iLower + iGap;
104269   }
104270   return SQLITE_OK;
104271 }
104272 #endif /* SQLITE_ENABLE_STAT3 */
104273
104274 /*
104275 ** If expression pExpr represents a literal value, set *pp to point to
104276 ** an sqlite3_value structure containing the same value, with affinity
104277 ** aff applied to it, before returning. It is the responsibility of the 
104278 ** caller to eventually release this structure by passing it to 
104279 ** sqlite3ValueFree().
104280 **
104281 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
104282 ** is an SQL variable that currently has a non-NULL value bound to it,
104283 ** create an sqlite3_value structure containing this value, again with
104284 ** affinity aff applied to it, instead.
104285 **
104286 ** If neither of the above apply, set *pp to NULL.
104287 **
104288 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
104289 */
104290 #ifdef SQLITE_ENABLE_STAT3
104291 static int valueFromExpr(
104292   Parse *pParse, 
104293   Expr *pExpr, 
104294   u8 aff, 
104295   sqlite3_value **pp
104296 ){
104297   if( pExpr->op==TK_VARIABLE
104298    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
104299   ){
104300     int iVar = pExpr->iColumn;
104301     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
104302     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
104303     return SQLITE_OK;
104304   }
104305   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
104306 }
104307 #endif
104308
104309 /*
104310 ** This function is used to estimate the number of rows that will be visited
104311 ** by scanning an index for a range of values. The range may have an upper
104312 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
104313 ** and lower bounds are represented by pLower and pUpper respectively. For
104314 ** example, assuming that index p is on t1(a):
104315 **
104316 **   ... FROM t1 WHERE a > ? AND a < ? ...
104317 **                    |_____|   |_____|
104318 **                       |         |
104319 **                     pLower    pUpper
104320 **
104321 ** If either of the upper or lower bound is not present, then NULL is passed in
104322 ** place of the corresponding WhereTerm.
104323 **
104324 ** The nEq parameter is passed the index of the index column subject to the
104325 ** range constraint. Or, equivalently, the number of equality constraints
104326 ** optimized by the proposed index scan. For example, assuming index p is
104327 ** on t1(a, b), and the SQL query is:
104328 **
104329 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
104330 **
104331 ** then nEq should be passed the value 1 (as the range restricted column,
104332 ** b, is the second left-most column of the index). Or, if the query is:
104333 **
104334 **   ... FROM t1 WHERE a > ? AND a < ? ...
104335 **
104336 ** then nEq should be passed 0.
104337 **
104338 ** The returned value is an integer divisor to reduce the estimated
104339 ** search space.  A return value of 1 means that range constraints are
104340 ** no help at all.  A return value of 2 means range constraints are
104341 ** expected to reduce the search space by half.  And so forth...
104342 **
104343 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
104344 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
104345 ** results in a return of 4 and a range constraint (x>? AND x<?) results
104346 ** in a return of 16.
104347 */
104348 static int whereRangeScanEst(
104349   Parse *pParse,       /* Parsing & code generating context */
104350   Index *p,            /* The index containing the range-compared column; "x" */
104351   int nEq,             /* index into p->aCol[] of the range-compared column */
104352   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
104353   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
104354   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
104355 ){
104356   int rc = SQLITE_OK;
104357
104358 #ifdef SQLITE_ENABLE_STAT3
104359
104360   if( nEq==0 && p->nSample ){
104361     sqlite3_value *pRangeVal;
104362     tRowcnt iLower = 0;
104363     tRowcnt iUpper = p->aiRowEst[0];
104364     tRowcnt a[2];
104365     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104366
104367     if( pLower ){
104368       Expr *pExpr = pLower->pExpr->pRight;
104369       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104370       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
104371       if( rc==SQLITE_OK
104372        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
104373       ){
104374         iLower = a[0];
104375         if( pLower->eOperator==WO_GT ) iLower += a[1];
104376       }
104377       sqlite3ValueFree(pRangeVal);
104378     }
104379     if( rc==SQLITE_OK && pUpper ){
104380       Expr *pExpr = pUpper->pExpr->pRight;
104381       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104382       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
104383       if( rc==SQLITE_OK
104384        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
104385       ){
104386         iUpper = a[0];
104387         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
104388       }
104389       sqlite3ValueFree(pRangeVal);
104390     }
104391     if( rc==SQLITE_OK ){
104392       if( iUpper<=iLower ){
104393         *pRangeDiv = (double)p->aiRowEst[0];
104394       }else{
104395         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
104396       }
104397       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
104398                   (u32)iLower, (u32)iUpper, *pRangeDiv));
104399       return SQLITE_OK;
104400     }
104401   }
104402 #else
104403   UNUSED_PARAMETER(pParse);
104404   UNUSED_PARAMETER(p);
104405   UNUSED_PARAMETER(nEq);
104406 #endif
104407   assert( pLower || pUpper );
104408   *pRangeDiv = (double)1;
104409   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
104410   if( pUpper ) *pRangeDiv *= (double)4;
104411   return rc;
104412 }
104413
104414 #ifdef SQLITE_ENABLE_STAT3
104415 /*
104416 ** Estimate the number of rows that will be returned based on
104417 ** an equality constraint x=VALUE and where that VALUE occurs in
104418 ** the histogram data.  This only works when x is the left-most
104419 ** column of an index and sqlite_stat3 histogram data is available
104420 ** for that index.  When pExpr==NULL that means the constraint is
104421 ** "x IS NULL" instead of "x=VALUE".
104422 **
104423 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
104424 ** If unable to make an estimate, leave *pnRow unchanged and return
104425 ** non-zero.
104426 **
104427 ** This routine can fail if it is unable to load a collating sequence
104428 ** required for string comparison, or if unable to allocate memory
104429 ** for a UTF conversion required for comparison.  The error is stored
104430 ** in the pParse structure.
104431 */
104432 static int whereEqualScanEst(
104433   Parse *pParse,       /* Parsing & code generating context */
104434   Index *p,            /* The index whose left-most column is pTerm */
104435   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
104436   double *pnRow        /* Write the revised row estimate here */
104437 ){
104438   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
104439   u8 aff;                   /* Column affinity */
104440   int rc;                   /* Subfunction return code */
104441   tRowcnt a[2];             /* Statistics */
104442
104443   assert( p->aSample!=0 );
104444   assert( p->nSample>0 );
104445   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104446   if( pExpr ){
104447     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
104448     if( rc ) goto whereEqualScanEst_cancel;
104449   }else{
104450     pRhs = sqlite3ValueNew(pParse->db);
104451   }
104452   if( pRhs==0 ) return SQLITE_NOTFOUND;
104453   rc = whereKeyStats(pParse, p, pRhs, 0, a);
104454   if( rc==SQLITE_OK ){
104455     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
104456     *pnRow = a[1];
104457   }
104458 whereEqualScanEst_cancel:
104459   sqlite3ValueFree(pRhs);
104460   return rc;
104461 }
104462 #endif /* defined(SQLITE_ENABLE_STAT3) */
104463
104464 #ifdef SQLITE_ENABLE_STAT3
104465 /*
104466 ** Estimate the number of rows that will be returned based on
104467 ** an IN constraint where the right-hand side of the IN operator
104468 ** is a list of values.  Example:
104469 **
104470 **        WHERE x IN (1,2,3,4)
104471 **
104472 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
104473 ** If unable to make an estimate, leave *pnRow unchanged and return
104474 ** non-zero.
104475 **
104476 ** This routine can fail if it is unable to load a collating sequence
104477 ** required for string comparison, or if unable to allocate memory
104478 ** for a UTF conversion required for comparison.  The error is stored
104479 ** in the pParse structure.
104480 */
104481 static int whereInScanEst(
104482   Parse *pParse,       /* Parsing & code generating context */
104483   Index *p,            /* The index whose left-most column is pTerm */
104484   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
104485   double *pnRow        /* Write the revised row estimate here */
104486 ){
104487   int rc = SQLITE_OK;         /* Subfunction return code */
104488   double nEst;                /* Number of rows for a single term */
104489   double nRowEst = (double)0; /* New estimate of the number of rows */
104490   int i;                      /* Loop counter */
104491
104492   assert( p->aSample!=0 );
104493   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
104494     nEst = p->aiRowEst[0];
104495     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
104496     nRowEst += nEst;
104497   }
104498   if( rc==SQLITE_OK ){
104499     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
104500     *pnRow = nRowEst;
104501     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
104502   }
104503   return rc;
104504 }
104505 #endif /* defined(SQLITE_ENABLE_STAT3) */
104506
104507
104508 /*
104509 ** Find the best query plan for accessing a particular table.  Write the
104510 ** best query plan and its cost into the WhereCost object supplied as the
104511 ** last parameter.
104512 **
104513 ** The lowest cost plan wins.  The cost is an estimate of the amount of
104514 ** CPU and disk I/O needed to process the requested result.
104515 ** Factors that influence cost include:
104516 **
104517 **    *  The estimated number of rows that will be retrieved.  (The
104518 **       fewer the better.)
104519 **
104520 **    *  Whether or not sorting must occur.
104521 **
104522 **    *  Whether or not there must be separate lookups in the
104523 **       index and in the main table.
104524 **
104525 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
104526 ** the SQL statement, then this function only considers plans using the 
104527 ** named index. If no such plan is found, then the returned cost is
104528 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
104529 ** then the cost is calculated in the usual way.
104530 **
104531 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
104532 ** in the SELECT statement, then no indexes are considered. However, the 
104533 ** selected plan may still take advantage of the built-in rowid primary key
104534 ** index.
104535 */
104536 static void bestBtreeIndex(
104537   Parse *pParse,              /* The parsing context */
104538   WhereClause *pWC,           /* The WHERE clause */
104539   struct SrcList_item *pSrc,  /* The FROM clause term to search */
104540   Bitmask notReady,           /* Mask of cursors not available for indexing */
104541   Bitmask notValid,           /* Cursors not available for any purpose */
104542   ExprList *pOrderBy,         /* The ORDER BY clause */
104543   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
104544   WhereCost *pCost            /* Lowest cost query plan */
104545 ){
104546   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
104547   Index *pProbe;              /* An index we are evaluating */
104548   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
104549   int eqTermMask;             /* Current mask of valid equality operators */
104550   int idxEqTermMask;          /* Index mask of valid equality operators */
104551   Index sPk;                  /* A fake index object for the primary key */
104552   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
104553   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
104554   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
104555
104556   /* Initialize the cost to a worst-case value */
104557   memset(pCost, 0, sizeof(*pCost));
104558   pCost->rCost = SQLITE_BIG_DBL;
104559
104560   /* If the pSrc table is the right table of a LEFT JOIN then we may not
104561   ** use an index to satisfy IS NULL constraints on that table.  This is
104562   ** because columns might end up being NULL if the table does not match -
104563   ** a circumstance which the index cannot help us discover.  Ticket #2177.
104564   */
104565   if( pSrc->jointype & JT_LEFT ){
104566     idxEqTermMask = WO_EQ|WO_IN;
104567   }else{
104568     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
104569   }
104570
104571   if( pSrc->pIndex ){
104572     /* An INDEXED BY clause specifies a particular index to use */
104573     pIdx = pProbe = pSrc->pIndex;
104574     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
104575     eqTermMask = idxEqTermMask;
104576   }else{
104577     /* There is no INDEXED BY clause.  Create a fake Index object in local
104578     ** variable sPk to represent the rowid primary key index.  Make this
104579     ** fake index the first in a chain of Index objects with all of the real
104580     ** indices to follow */
104581     Index *pFirst;                  /* First of real indices on the table */
104582     memset(&sPk, 0, sizeof(Index));
104583     sPk.nColumn = 1;
104584     sPk.aiColumn = &aiColumnPk;
104585     sPk.aiRowEst = aiRowEstPk;
104586     sPk.onError = OE_Replace;
104587     sPk.pTable = pSrc->pTab;
104588     aiRowEstPk[0] = pSrc->pTab->nRowEst;
104589     aiRowEstPk[1] = 1;
104590     pFirst = pSrc->pTab->pIndex;
104591     if( pSrc->notIndexed==0 ){
104592       /* The real indices of the table are only considered if the
104593       ** NOT INDEXED qualifier is omitted from the FROM clause */
104594       sPk.pNext = pFirst;
104595     }
104596     pProbe = &sPk;
104597     wsFlagMask = ~(
104598         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
104599     );
104600     eqTermMask = WO_EQ|WO_IN;
104601     pIdx = 0;
104602   }
104603
104604   /* Loop over all indices looking for the best one to use
104605   */
104606   for(; pProbe; pIdx=pProbe=pProbe->pNext){
104607     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
104608     double cost;                /* Cost of using pProbe */
104609     double nRow;                /* Estimated number of rows in result set */
104610     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
104611     int rev;                    /* True to scan in reverse order */
104612     int wsFlags = 0;
104613     Bitmask used = 0;
104614
104615     /* The following variables are populated based on the properties of
104616     ** index being evaluated. They are then used to determine the expected
104617     ** cost and number of rows returned.
104618     **
104619     **  nEq: 
104620     **    Number of equality terms that can be implemented using the index.
104621     **    In other words, the number of initial fields in the index that
104622     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
104623     **
104624     **  nInMul:  
104625     **    The "in-multiplier". This is an estimate of how many seek operations 
104626     **    SQLite must perform on the index in question. For example, if the 
104627     **    WHERE clause is:
104628     **
104629     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
104630     **
104631     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
104632     **    set to 9. Given the same schema and either of the following WHERE 
104633     **    clauses:
104634     **
104635     **      WHERE a =  1
104636     **      WHERE a >= 2
104637     **
104638     **    nInMul is set to 1.
104639     **
104640     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
104641     **    the sub-select is assumed to return 25 rows for the purposes of 
104642     **    determining nInMul.
104643     **
104644     **  bInEst:  
104645     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
104646     **    in determining the value of nInMul.  Note that the RHS of the
104647     **    IN operator must be a SELECT, not a value list, for this variable
104648     **    to be true.
104649     **
104650     **  rangeDiv:
104651     **    An estimate of a divisor by which to reduce the search space due
104652     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
104653     **    data, a single inequality reduces the search space to 1/4rd its
104654     **    original size (rangeDiv==4).  Two inequalities reduce the search
104655     **    space to 1/16th of its original size (rangeDiv==16).
104656     **
104657     **  bSort:   
104658     **    Boolean. True if there is an ORDER BY clause that will require an 
104659     **    external sort (i.e. scanning the index being evaluated will not 
104660     **    correctly order records).
104661     **
104662     **  bLookup: 
104663     **    Boolean. True if a table lookup is required for each index entry
104664     **    visited.  In other words, true if this is not a covering index.
104665     **    This is always false for the rowid primary key index of a table.
104666     **    For other indexes, it is true unless all the columns of the table
104667     **    used by the SELECT statement are present in the index (such an
104668     **    index is sometimes described as a covering index).
104669     **    For example, given the index on (a, b), the second of the following 
104670     **    two queries requires table b-tree lookups in order to find the value
104671     **    of column c, but the first does not because columns a and b are
104672     **    both available in the index.
104673     **
104674     **             SELECT a, b    FROM tbl WHERE a = 1;
104675     **             SELECT a, b, c FROM tbl WHERE a = 1;
104676     */
104677     int nEq;                      /* Number of == or IN terms matching index */
104678     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
104679     int nInMul = 1;               /* Number of distinct equalities to lookup */
104680     double rangeDiv = (double)1;  /* Estimated reduction in search space */
104681     int nBound = 0;               /* Number of range constraints seen */
104682     int bSort = !!pOrderBy;       /* True if external sort required */
104683     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
104684     int bLookup = 0;              /* True if not a covering index */
104685     WhereTerm *pTerm;             /* A single term of the WHERE clause */
104686 #ifdef SQLITE_ENABLE_STAT3
104687     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
104688 #endif
104689
104690     /* Determine the values of nEq and nInMul */
104691     for(nEq=0; nEq<pProbe->nColumn; nEq++){
104692       int j = pProbe->aiColumn[nEq];
104693       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
104694       if( pTerm==0 ) break;
104695       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
104696       testcase( pTerm->pWC!=pWC );
104697       if( pTerm->eOperator & WO_IN ){
104698         Expr *pExpr = pTerm->pExpr;
104699         wsFlags |= WHERE_COLUMN_IN;
104700         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104701           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
104702           nInMul *= 25;
104703           bInEst = 1;
104704         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
104705           /* "x IN (value, value, ...)" */
104706           nInMul *= pExpr->x.pList->nExpr;
104707         }
104708       }else if( pTerm->eOperator & WO_ISNULL ){
104709         wsFlags |= WHERE_COLUMN_NULL;
104710       }
104711 #ifdef SQLITE_ENABLE_STAT3
104712       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
104713 #endif
104714       used |= pTerm->prereqRight;
104715     }
104716  
104717     /* If the index being considered is UNIQUE, and there is an equality 
104718     ** constraint for all columns in the index, then this search will find
104719     ** at most a single row. In this case set the WHERE_UNIQUE flag to 
104720     ** indicate this to the caller.
104721     **
104722     ** Otherwise, if the search may find more than one row, test to see if
104723     ** there is a range constraint on indexed column (nEq+1) that can be 
104724     ** optimized using the index. 
104725     */
104726     if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
104727       testcase( wsFlags & WHERE_COLUMN_IN );
104728       testcase( wsFlags & WHERE_COLUMN_NULL );
104729       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
104730         wsFlags |= WHERE_UNIQUE;
104731       }
104732     }else if( pProbe->bUnordered==0 ){
104733       int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
104734       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
104735         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
104736         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
104737         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
104738         if( pTop ){
104739           nBound = 1;
104740           wsFlags |= WHERE_TOP_LIMIT;
104741           used |= pTop->prereqRight;
104742           testcase( pTop->pWC!=pWC );
104743         }
104744         if( pBtm ){
104745           nBound++;
104746           wsFlags |= WHERE_BTM_LIMIT;
104747           used |= pBtm->prereqRight;
104748           testcase( pBtm->pWC!=pWC );
104749         }
104750         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
104751       }
104752     }
104753
104754     /* If there is an ORDER BY clause and the index being considered will
104755     ** naturally scan rows in the required order, set the appropriate flags
104756     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
104757     ** will scan rows in a different order, set the bSort variable.  */
104758     if( isSortingIndex(
104759           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
104760     ){
104761       bSort = 0;
104762       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
104763       wsFlags |= (rev ? WHERE_REVERSE : 0);
104764     }
104765
104766     /* If there is a DISTINCT qualifier and this index will scan rows in
104767     ** order of the DISTINCT expressions, clear bDist and set the appropriate
104768     ** flags in wsFlags. */
104769     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
104770      && (wsFlags & WHERE_COLUMN_IN)==0
104771     ){
104772       bDist = 0;
104773       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
104774     }
104775
104776     /* If currently calculating the cost of using an index (not the IPK
104777     ** index), determine if all required column data may be obtained without 
104778     ** using the main table (i.e. if the index is a covering
104779     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
104780     ** wsFlags. Otherwise, set the bLookup variable to true.  */
104781     if( pIdx && wsFlags ){
104782       Bitmask m = pSrc->colUsed;
104783       int j;
104784       for(j=0; j<pIdx->nColumn; j++){
104785         int x = pIdx->aiColumn[j];
104786         if( x<BMS-1 ){
104787           m &= ~(((Bitmask)1)<<x);
104788         }
104789       }
104790       if( m==0 ){
104791         wsFlags |= WHERE_IDX_ONLY;
104792       }else{
104793         bLookup = 1;
104794       }
104795     }
104796
104797     /*
104798     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
104799     ** constraint, do not let the estimate exceed half the rows in the table.
104800     */
104801     nRow = (double)(aiRowEst[nEq] * nInMul);
104802     if( bInEst && nRow*2>aiRowEst[0] ){
104803       nRow = aiRowEst[0]/2;
104804       nInMul = (int)(nRow / aiRowEst[nEq]);
104805     }
104806
104807 #ifdef SQLITE_ENABLE_STAT3
104808     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
104809     ** and we do not think that values of x are unique and if histogram
104810     ** data is available for column x, then it might be possible
104811     ** to get a better estimate on the number of rows based on
104812     ** VALUE and how common that value is according to the histogram.
104813     */
104814     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
104815       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
104816       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
104817         testcase( pFirstTerm->eOperator==WO_EQ );
104818         testcase( pFirstTerm->eOperator==WO_ISNULL );
104819         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
104820       }else if( bInEst==0 ){
104821         assert( pFirstTerm->eOperator==WO_IN );
104822         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
104823       }
104824     }
104825 #endif /* SQLITE_ENABLE_STAT3 */
104826
104827     /* Adjust the number of output rows and downward to reflect rows
104828     ** that are excluded by range constraints.
104829     */
104830     nRow = nRow/rangeDiv;
104831     if( nRow<1 ) nRow = 1;
104832
104833     /* Experiments run on real SQLite databases show that the time needed
104834     ** to do a binary search to locate a row in a table or index is roughly
104835     ** log10(N) times the time to move from one row to the next row within
104836     ** a table or index.  The actual times can vary, with the size of
104837     ** records being an important factor.  Both moves and searches are
104838     ** slower with larger records, presumably because fewer records fit
104839     ** on one page and hence more pages have to be fetched.
104840     **
104841     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
104842     ** not give us data on the relative sizes of table and index records.
104843     ** So this computation assumes table records are about twice as big
104844     ** as index records
104845     */
104846     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
104847       /* The cost of a full table scan is a number of move operations equal
104848       ** to the number of rows in the table.
104849       **
104850       ** We add an additional 4x penalty to full table scans.  This causes
104851       ** the cost function to err on the side of choosing an index over
104852       ** choosing a full scan.  This 4x full-scan penalty is an arguable
104853       ** decision and one which we expect to revisit in the future.  But
104854       ** it seems to be working well enough at the moment.
104855       */
104856       cost = aiRowEst[0]*4;
104857     }else{
104858       log10N = estLog(aiRowEst[0]);
104859       cost = nRow;
104860       if( pIdx ){
104861         if( bLookup ){
104862           /* For an index lookup followed by a table lookup:
104863           **    nInMul index searches to find the start of each index range
104864           **  + nRow steps through the index
104865           **  + nRow table searches to lookup the table entry using the rowid
104866           */
104867           cost += (nInMul + nRow)*log10N;
104868         }else{
104869           /* For a covering index:
104870           **     nInMul index searches to find the initial entry 
104871           **   + nRow steps through the index
104872           */
104873           cost += nInMul*log10N;
104874         }
104875       }else{
104876         /* For a rowid primary key lookup:
104877         **    nInMult table searches to find the initial entry for each range
104878         **  + nRow steps through the table
104879         */
104880         cost += nInMul*log10N;
104881       }
104882     }
104883
104884     /* Add in the estimated cost of sorting the result.  Actual experimental
104885     ** measurements of sorting performance in SQLite show that sorting time
104886     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
104887     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
104888     ** difference and select C of 3.0.
104889     */
104890     if( bSort ){
104891       cost += nRow*estLog(nRow)*3;
104892     }
104893     if( bDist ){
104894       cost += nRow*estLog(nRow)*3;
104895     }
104896
104897     /**** Cost of using this index has now been computed ****/
104898
104899     /* If there are additional constraints on this table that cannot
104900     ** be used with the current index, but which might lower the number
104901     ** of output rows, adjust the nRow value accordingly.  This only 
104902     ** matters if the current index is the least costly, so do not bother
104903     ** with this step if we already know this index will not be chosen.
104904     ** Also, never reduce the output row count below 2 using this step.
104905     **
104906     ** It is critical that the notValid mask be used here instead of
104907     ** the notReady mask.  When computing an "optimal" index, the notReady
104908     ** mask will only have one bit set - the bit for the current table.
104909     ** The notValid mask, on the other hand, always has all bits set for
104910     ** tables that are not in outer loops.  If notReady is used here instead
104911     ** of notValid, then a optimal index that depends on inner joins loops
104912     ** might be selected even when there exists an optimal index that has
104913     ** no such dependency.
104914     */
104915     if( nRow>2 && cost<=pCost->rCost ){
104916       int k;                       /* Loop counter */
104917       int nSkipEq = nEq;           /* Number of == constraints to skip */
104918       int nSkipRange = nBound;     /* Number of < constraints to skip */
104919       Bitmask thisTab;             /* Bitmap for pSrc */
104920
104921       thisTab = getMask(pWC->pMaskSet, iCur);
104922       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
104923         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
104924         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
104925         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
104926           if( nSkipEq ){
104927             /* Ignore the first nEq equality matches since the index
104928             ** has already accounted for these */
104929             nSkipEq--;
104930           }else{
104931             /* Assume each additional equality match reduces the result
104932             ** set size by a factor of 10 */
104933             nRow /= 10;
104934           }
104935         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
104936           if( nSkipRange ){
104937             /* Ignore the first nSkipRange range constraints since the index
104938             ** has already accounted for these */
104939             nSkipRange--;
104940           }else{
104941             /* Assume each additional range constraint reduces the result
104942             ** set size by a factor of 3.  Indexed range constraints reduce
104943             ** the search space by a larger factor: 4.  We make indexed range
104944             ** more selective intentionally because of the subjective 
104945             ** observation that indexed range constraints really are more
104946             ** selective in practice, on average. */
104947             nRow /= 3;
104948           }
104949         }else if( pTerm->eOperator!=WO_NOOP ){
104950           /* Any other expression lowers the output row count by half */
104951           nRow /= 2;
104952         }
104953       }
104954       if( nRow<2 ) nRow = 2;
104955     }
104956
104957
104958     WHERETRACE((
104959       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
104960       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
104961       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
104962       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
104963       notReady, log10N, nRow, cost, used
104964     ));
104965
104966     /* If this index is the best we have seen so far, then record this
104967     ** index and its cost in the pCost structure.
104968     */
104969     if( (!pIdx || wsFlags)
104970      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
104971     ){
104972       pCost->rCost = cost;
104973       pCost->used = used;
104974       pCost->plan.nRow = nRow;
104975       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
104976       pCost->plan.nEq = nEq;
104977       pCost->plan.u.pIdx = pIdx;
104978     }
104979
104980     /* If there was an INDEXED BY clause, then only that one index is
104981     ** considered. */
104982     if( pSrc->pIndex ) break;
104983
104984     /* Reset masks for the next index in the loop */
104985     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
104986     eqTermMask = idxEqTermMask;
104987   }
104988
104989   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
104990   ** is set, then reverse the order that the index will be scanned
104991   ** in. This is used for application testing, to help find cases
104992   ** where application behaviour depends on the (undefined) order that
104993   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
104994   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
104995     pCost->plan.wsFlags |= WHERE_REVERSE;
104996   }
104997
104998   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
104999   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
105000   assert( pSrc->pIndex==0 
105001        || pCost->plan.u.pIdx==0 
105002        || pCost->plan.u.pIdx==pSrc->pIndex 
105003   );
105004
105005   WHERETRACE(("best index is: %s\n", 
105006     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
105007          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
105008   ));
105009   
105010   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
105011   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
105012   pCost->plan.wsFlags |= eqTermMask;
105013 }
105014
105015 /*
105016 ** Find the query plan for accessing table pSrc->pTab. Write the
105017 ** best query plan and its cost into the WhereCost object supplied 
105018 ** as the last parameter. This function may calculate the cost of
105019 ** both real and virtual table scans.
105020 */
105021 static void bestIndex(
105022   Parse *pParse,              /* The parsing context */
105023   WhereClause *pWC,           /* The WHERE clause */
105024   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105025   Bitmask notReady,           /* Mask of cursors not available for indexing */
105026   Bitmask notValid,           /* Cursors not available for any purpose */
105027   ExprList *pOrderBy,         /* The ORDER BY clause */
105028   WhereCost *pCost            /* Lowest cost query plan */
105029 ){
105030 #ifndef SQLITE_OMIT_VIRTUALTABLE
105031   if( IsVirtual(pSrc->pTab) ){
105032     sqlite3_index_info *p = 0;
105033     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
105034     if( p->needToFreeIdxStr ){
105035       sqlite3_free(p->idxStr);
105036     }
105037     sqlite3DbFree(pParse->db, p);
105038   }else
105039 #endif
105040   {
105041     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
105042   }
105043 }
105044
105045 /*
105046 ** Disable a term in the WHERE clause.  Except, do not disable the term
105047 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
105048 ** or USING clause of that join.
105049 **
105050 ** Consider the term t2.z='ok' in the following queries:
105051 **
105052 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
105053 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
105054 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
105055 **
105056 ** The t2.z='ok' is disabled in the in (2) because it originates
105057 ** in the ON clause.  The term is disabled in (3) because it is not part
105058 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
105059 **
105060 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
105061 ** completely satisfied by indices.
105062 **
105063 ** Disabling a term causes that term to not be tested in the inner loop
105064 ** of the join.  Disabling is an optimization.  When terms are satisfied
105065 ** by indices, we disable them to prevent redundant tests in the inner
105066 ** loop.  We would get the correct results if nothing were ever disabled,
105067 ** but joins might run a little slower.  The trick is to disable as much
105068 ** as we can without disabling too much.  If we disabled in (1), we'd get
105069 ** the wrong answer.  See ticket #813.
105070 */
105071 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
105072   if( pTerm
105073       && (pTerm->wtFlags & TERM_CODED)==0
105074       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
105075   ){
105076     pTerm->wtFlags |= TERM_CODED;
105077     if( pTerm->iParent>=0 ){
105078       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
105079       if( (--pOther->nChild)==0 ){
105080         disableTerm(pLevel, pOther);
105081       }
105082     }
105083   }
105084 }
105085
105086 /*
105087 ** Code an OP_Affinity opcode to apply the column affinity string zAff
105088 ** to the n registers starting at base. 
105089 **
105090 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
105091 ** beginning and end of zAff are ignored.  If all entries in zAff are
105092 ** SQLITE_AFF_NONE, then no code gets generated.
105093 **
105094 ** This routine makes its own copy of zAff so that the caller is free
105095 ** to modify zAff after this routine returns.
105096 */
105097 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
105098   Vdbe *v = pParse->pVdbe;
105099   if( zAff==0 ){
105100     assert( pParse->db->mallocFailed );
105101     return;
105102   }
105103   assert( v!=0 );
105104
105105   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
105106   ** and end of the affinity string.
105107   */
105108   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
105109     n--;
105110     base++;
105111     zAff++;
105112   }
105113   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
105114     n--;
105115   }
105116
105117   /* Code the OP_Affinity opcode if there is anything left to do. */
105118   if( n>0 ){
105119     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
105120     sqlite3VdbeChangeP4(v, -1, zAff, n);
105121     sqlite3ExprCacheAffinityChange(pParse, base, n);
105122   }
105123 }
105124
105125
105126 /*
105127 ** Generate code for a single equality term of the WHERE clause.  An equality
105128 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
105129 ** coded.
105130 **
105131 ** The current value for the constraint is left in register iReg.
105132 **
105133 ** For a constraint of the form X=expr, the expression is evaluated and its
105134 ** result is left on the stack.  For constraints of the form X IN (...)
105135 ** this routine sets up a loop that will iterate over all values of X.
105136 */
105137 static int codeEqualityTerm(
105138   Parse *pParse,      /* The parsing context */
105139   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
105140   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
105141   int iTarget         /* Attempt to leave results in this register */
105142 ){
105143   Expr *pX = pTerm->pExpr;
105144   Vdbe *v = pParse->pVdbe;
105145   int iReg;                  /* Register holding results */
105146
105147   assert( iTarget>0 );
105148   if( pX->op==TK_EQ ){
105149     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
105150   }else if( pX->op==TK_ISNULL ){
105151     iReg = iTarget;
105152     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
105153 #ifndef SQLITE_OMIT_SUBQUERY
105154   }else{
105155     int eType;
105156     int iTab;
105157     struct InLoop *pIn;
105158
105159     assert( pX->op==TK_IN );
105160     iReg = iTarget;
105161     eType = sqlite3FindInIndex(pParse, pX, 0);
105162     iTab = pX->iTable;
105163     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
105164     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
105165     if( pLevel->u.in.nIn==0 ){
105166       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
105167     }
105168     pLevel->u.in.nIn++;
105169     pLevel->u.in.aInLoop =
105170        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
105171                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
105172     pIn = pLevel->u.in.aInLoop;
105173     if( pIn ){
105174       pIn += pLevel->u.in.nIn - 1;
105175       pIn->iCur = iTab;
105176       if( eType==IN_INDEX_ROWID ){
105177         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
105178       }else{
105179         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
105180       }
105181       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
105182     }else{
105183       pLevel->u.in.nIn = 0;
105184     }
105185 #endif
105186   }
105187   disableTerm(pLevel, pTerm);
105188   return iReg;
105189 }
105190
105191 /*
105192 ** Generate code that will evaluate all == and IN constraints for an
105193 ** index.
105194 **
105195 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
105196 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
105197 ** The index has as many as three equality constraints, but in this
105198 ** example, the third "c" value is an inequality.  So only two 
105199 ** constraints are coded.  This routine will generate code to evaluate
105200 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
105201 ** in consecutive registers and the index of the first register is returned.
105202 **
105203 ** In the example above nEq==2.  But this subroutine works for any value
105204 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
105205 ** The only thing it does is allocate the pLevel->iMem memory cell and
105206 ** compute the affinity string.
105207 **
105208 ** This routine always allocates at least one memory cell and returns
105209 ** the index of that memory cell. The code that
105210 ** calls this routine will use that memory cell to store the termination
105211 ** key value of the loop.  If one or more IN operators appear, then
105212 ** this routine allocates an additional nEq memory cells for internal
105213 ** use.
105214 **
105215 ** Before returning, *pzAff is set to point to a buffer containing a
105216 ** copy of the column affinity string of the index allocated using
105217 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
105218 ** with equality constraints that use NONE affinity are set to
105219 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
105220 **
105221 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
105222 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
105223 **
105224 ** In the example above, the index on t1(a) has TEXT affinity. But since
105225 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
105226 ** no conversion should be attempted before using a t2.b value as part of
105227 ** a key to search the index. Hence the first byte in the returned affinity
105228 ** string in this example would be set to SQLITE_AFF_NONE.
105229 */
105230 static int codeAllEqualityTerms(
105231   Parse *pParse,        /* Parsing context */
105232   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
105233   WhereClause *pWC,     /* The WHERE clause */
105234   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
105235   int nExtraReg,        /* Number of extra registers to allocate */
105236   char **pzAff          /* OUT: Set to point to affinity string */
105237 ){
105238   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
105239   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
105240   Index *pIdx;                  /* The index being used for this loop */
105241   int iCur = pLevel->iTabCur;   /* The cursor of the table */
105242   WhereTerm *pTerm;             /* A single constraint term */
105243   int j;                        /* Loop counter */
105244   int regBase;                  /* Base register */
105245   int nReg;                     /* Number of registers to allocate */
105246   char *zAff;                   /* Affinity string to return */
105247
105248   /* This module is only called on query plans that use an index. */
105249   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
105250   pIdx = pLevel->plan.u.pIdx;
105251
105252   /* Figure out how many memory cells we will need then allocate them.
105253   */
105254   regBase = pParse->nMem + 1;
105255   nReg = pLevel->plan.nEq + nExtraReg;
105256   pParse->nMem += nReg;
105257
105258   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
105259   if( !zAff ){
105260     pParse->db->mallocFailed = 1;
105261   }
105262
105263   /* Evaluate the equality constraints
105264   */
105265   assert( pIdx->nColumn>=nEq );
105266   for(j=0; j<nEq; j++){
105267     int r1;
105268     int k = pIdx->aiColumn[j];
105269     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
105270     if( pTerm==0 ) break;
105271     /* The following true for indices with redundant columns. 
105272     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
105273     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
105274     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105275     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
105276     if( r1!=regBase+j ){
105277       if( nReg==1 ){
105278         sqlite3ReleaseTempReg(pParse, regBase);
105279         regBase = r1;
105280       }else{
105281         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
105282       }
105283     }
105284     testcase( pTerm->eOperator & WO_ISNULL );
105285     testcase( pTerm->eOperator & WO_IN );
105286     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
105287       Expr *pRight = pTerm->pExpr->pRight;
105288       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
105289       if( zAff ){
105290         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
105291           zAff[j] = SQLITE_AFF_NONE;
105292         }
105293         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
105294           zAff[j] = SQLITE_AFF_NONE;
105295         }
105296       }
105297     }
105298   }
105299   *pzAff = zAff;
105300   return regBase;
105301 }
105302
105303 #ifndef SQLITE_OMIT_EXPLAIN
105304 /*
105305 ** This routine is a helper for explainIndexRange() below
105306 **
105307 ** pStr holds the text of an expression that we are building up one term
105308 ** at a time.  This routine adds a new term to the end of the expression.
105309 ** Terms are separated by AND so add the "AND" text for second and subsequent
105310 ** terms only.
105311 */
105312 static void explainAppendTerm(
105313   StrAccum *pStr,             /* The text expression being built */
105314   int iTerm,                  /* Index of this term.  First is zero */
105315   const char *zColumn,        /* Name of the column */
105316   const char *zOp             /* Name of the operator */
105317 ){
105318   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
105319   sqlite3StrAccumAppend(pStr, zColumn, -1);
105320   sqlite3StrAccumAppend(pStr, zOp, 1);
105321   sqlite3StrAccumAppend(pStr, "?", 1);
105322 }
105323
105324 /*
105325 ** Argument pLevel describes a strategy for scanning table pTab. This 
105326 ** function returns a pointer to a string buffer containing a description
105327 ** of the subset of table rows scanned by the strategy in the form of an
105328 ** SQL expression. Or, if all rows are scanned, NULL is returned.
105329 **
105330 ** For example, if the query:
105331 **
105332 **   SELECT * FROM t1 WHERE a=1 AND b>2;
105333 **
105334 ** is run and there is an index on (a, b), then this function returns a
105335 ** string similar to:
105336 **
105337 **   "a=? AND b>?"
105338 **
105339 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
105340 ** It is the responsibility of the caller to free the buffer when it is
105341 ** no longer required.
105342 */
105343 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
105344   WherePlan *pPlan = &pLevel->plan;
105345   Index *pIndex = pPlan->u.pIdx;
105346   int nEq = pPlan->nEq;
105347   int i, j;
105348   Column *aCol = pTab->aCol;
105349   int *aiColumn = pIndex->aiColumn;
105350   StrAccum txt;
105351
105352   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
105353     return 0;
105354   }
105355   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
105356   txt.db = db;
105357   sqlite3StrAccumAppend(&txt, " (", 2);
105358   for(i=0; i<nEq; i++){
105359     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
105360   }
105361
105362   j = i;
105363   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
105364     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
105365     explainAppendTerm(&txt, i++, z, ">");
105366   }
105367   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
105368     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
105369     explainAppendTerm(&txt, i, z, "<");
105370   }
105371   sqlite3StrAccumAppend(&txt, ")", 1);
105372   return sqlite3StrAccumFinish(&txt);
105373 }
105374
105375 /*
105376 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
105377 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
105378 ** record is added to the output to describe the table scan strategy in 
105379 ** pLevel.
105380 */
105381 static void explainOneScan(
105382   Parse *pParse,                  /* Parse context */
105383   SrcList *pTabList,              /* Table list this loop refers to */
105384   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
105385   int iLevel,                     /* Value for "level" column of output */
105386   int iFrom,                      /* Value for "from" column of output */
105387   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
105388 ){
105389   if( pParse->explain==2 ){
105390     u32 flags = pLevel->plan.wsFlags;
105391     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
105392     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
105393     sqlite3 *db = pParse->db;     /* Database handle */
105394     char *zMsg;                   /* Text to add to EQP output */
105395     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
105396     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
105397     int isSearch;                 /* True for a SEARCH. False for SCAN. */
105398
105399     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
105400
105401     isSearch = (pLevel->plan.nEq>0)
105402              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
105403              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
105404
105405     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
105406     if( pItem->pSelect ){
105407       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
105408     }else{
105409       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
105410     }
105411
105412     if( pItem->zAlias ){
105413       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
105414     }
105415     if( (flags & WHERE_INDEXED)!=0 ){
105416       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
105417       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
105418           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
105419           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
105420           ((flags & WHERE_TEMP_INDEX)?"":" "),
105421           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
105422           zWhere
105423       );
105424       sqlite3DbFree(db, zWhere);
105425     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
105426       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
105427
105428       if( flags&WHERE_ROWID_EQ ){
105429         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
105430       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
105431         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
105432       }else if( flags&WHERE_BTM_LIMIT ){
105433         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
105434       }else if( flags&WHERE_TOP_LIMIT ){
105435         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
105436       }
105437     }
105438 #ifndef SQLITE_OMIT_VIRTUALTABLE
105439     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
105440       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
105441       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
105442                   pVtabIdx->idxNum, pVtabIdx->idxStr);
105443     }
105444 #endif
105445     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
105446       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
105447       nRow = 1;
105448     }else{
105449       nRow = (sqlite3_int64)pLevel->plan.nRow;
105450     }
105451     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
105452     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
105453   }
105454 }
105455 #else
105456 # define explainOneScan(u,v,w,x,y,z)
105457 #endif /* SQLITE_OMIT_EXPLAIN */
105458
105459
105460 /*
105461 ** Generate code for the start of the iLevel-th loop in the WHERE clause
105462 ** implementation described by pWInfo.
105463 */
105464 static Bitmask codeOneLoopStart(
105465   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
105466   int iLevel,          /* Which level of pWInfo->a[] should be coded */
105467   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
105468   Bitmask notReady     /* Which tables are currently available */
105469 ){
105470   int j, k;            /* Loop counters */
105471   int iCur;            /* The VDBE cursor for the table */
105472   int addrNxt;         /* Where to jump to continue with the next IN case */
105473   int omitTable;       /* True if we use the index only */
105474   int bRev;            /* True if we need to scan in reverse order */
105475   WhereLevel *pLevel;  /* The where level to be coded */
105476   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
105477   WhereTerm *pTerm;               /* A WHERE clause term */
105478   Parse *pParse;                  /* Parsing context */
105479   Vdbe *v;                        /* The prepared stmt under constructions */
105480   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
105481   int addrBrk;                    /* Jump here to break out of the loop */
105482   int addrCont;                   /* Jump here to continue with next cycle */
105483   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
105484   int iReleaseReg = 0;      /* Temp register to free before returning */
105485
105486   pParse = pWInfo->pParse;
105487   v = pParse->pVdbe;
105488   pWC = pWInfo->pWC;
105489   pLevel = &pWInfo->a[iLevel];
105490   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
105491   iCur = pTabItem->iCursor;
105492   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
105493   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
105494            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
105495
105496   /* Create labels for the "break" and "continue" instructions
105497   ** for the current loop.  Jump to addrBrk to break out of a loop.
105498   ** Jump to cont to go immediately to the next iteration of the
105499   ** loop.
105500   **
105501   ** When there is an IN operator, we also have a "addrNxt" label that
105502   ** means to continue with the next IN value combination.  When
105503   ** there are no IN operators in the constraints, the "addrNxt" label
105504   ** is the same as "addrBrk".
105505   */
105506   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
105507   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
105508
105509   /* If this is the right table of a LEFT OUTER JOIN, allocate and
105510   ** initialize a memory cell that records if this table matches any
105511   ** row of the left table of the join.
105512   */
105513   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
105514     pLevel->iLeftJoin = ++pParse->nMem;
105515     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
105516     VdbeComment((v, "init LEFT JOIN no-match flag"));
105517   }
105518
105519 #ifndef SQLITE_OMIT_VIRTUALTABLE
105520   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
105521     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
105522     **          to access the data.
105523     */
105524     int iReg;   /* P3 Value for OP_VFilter */
105525     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
105526     int nConstraint = pVtabIdx->nConstraint;
105527     struct sqlite3_index_constraint_usage *aUsage =
105528                                                 pVtabIdx->aConstraintUsage;
105529     const struct sqlite3_index_constraint *aConstraint =
105530                                                 pVtabIdx->aConstraint;
105531
105532     sqlite3ExprCachePush(pParse);
105533     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
105534     for(j=1; j<=nConstraint; j++){
105535       for(k=0; k<nConstraint; k++){
105536         if( aUsage[k].argvIndex==j ){
105537           int iTerm = aConstraint[k].iTermOffset;
105538           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
105539           break;
105540         }
105541       }
105542       if( k==nConstraint ) break;
105543     }
105544     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
105545     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
105546     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
105547                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
105548     pVtabIdx->needToFreeIdxStr = 0;
105549     for(j=0; j<nConstraint; j++){
105550       if( aUsage[j].omit ){
105551         int iTerm = aConstraint[j].iTermOffset;
105552         disableTerm(pLevel, &pWC->a[iTerm]);
105553       }
105554     }
105555     pLevel->op = OP_VNext;
105556     pLevel->p1 = iCur;
105557     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
105558     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
105559     sqlite3ExprCachePop(pParse, 1);
105560   }else
105561 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105562
105563   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
105564     /* Case 1:  We can directly reference a single row using an
105565     **          equality comparison against the ROWID field.  Or
105566     **          we reference multiple rows using a "rowid IN (...)"
105567     **          construct.
105568     */
105569     iReleaseReg = sqlite3GetTempReg(pParse);
105570     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
105571     assert( pTerm!=0 );
105572     assert( pTerm->pExpr!=0 );
105573     assert( pTerm->leftCursor==iCur );
105574     assert( omitTable==0 );
105575     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105576     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
105577     addrNxt = pLevel->addrNxt;
105578     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
105579     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
105580     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
105581     VdbeComment((v, "pk"));
105582     pLevel->op = OP_Noop;
105583   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
105584     /* Case 2:  We have an inequality comparison against the ROWID field.
105585     */
105586     int testOp = OP_Noop;
105587     int start;
105588     int memEndValue = 0;
105589     WhereTerm *pStart, *pEnd;
105590
105591     assert( omitTable==0 );
105592     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
105593     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
105594     if( bRev ){
105595       pTerm = pStart;
105596       pStart = pEnd;
105597       pEnd = pTerm;
105598     }
105599     if( pStart ){
105600       Expr *pX;             /* The expression that defines the start bound */
105601       int r1, rTemp;        /* Registers for holding the start boundary */
105602
105603       /* The following constant maps TK_xx codes into corresponding 
105604       ** seek opcodes.  It depends on a particular ordering of TK_xx
105605       */
105606       const u8 aMoveOp[] = {
105607            /* TK_GT */  OP_SeekGt,
105608            /* TK_LE */  OP_SeekLe,
105609            /* TK_LT */  OP_SeekLt,
105610            /* TK_GE */  OP_SeekGe
105611       };
105612       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
105613       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
105614       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
105615
105616       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105617       pX = pStart->pExpr;
105618       assert( pX!=0 );
105619       assert( pStart->leftCursor==iCur );
105620       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
105621       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
105622       VdbeComment((v, "pk"));
105623       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
105624       sqlite3ReleaseTempReg(pParse, rTemp);
105625       disableTerm(pLevel, pStart);
105626     }else{
105627       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
105628     }
105629     if( pEnd ){
105630       Expr *pX;
105631       pX = pEnd->pExpr;
105632       assert( pX!=0 );
105633       assert( pEnd->leftCursor==iCur );
105634       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105635       memEndValue = ++pParse->nMem;
105636       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
105637       if( pX->op==TK_LT || pX->op==TK_GT ){
105638         testOp = bRev ? OP_Le : OP_Ge;
105639       }else{
105640         testOp = bRev ? OP_Lt : OP_Gt;
105641       }
105642       disableTerm(pLevel, pEnd);
105643     }
105644     start = sqlite3VdbeCurrentAddr(v);
105645     pLevel->op = bRev ? OP_Prev : OP_Next;
105646     pLevel->p1 = iCur;
105647     pLevel->p2 = start;
105648     if( pStart==0 && pEnd==0 ){
105649       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
105650     }else{
105651       assert( pLevel->p5==0 );
105652     }
105653     if( testOp!=OP_Noop ){
105654       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
105655       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
105656       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
105657       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
105658       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
105659     }
105660   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
105661     /* Case 3: A scan using an index.
105662     **
105663     **         The WHERE clause may contain zero or more equality 
105664     **         terms ("==" or "IN" operators) that refer to the N
105665     **         left-most columns of the index. It may also contain
105666     **         inequality constraints (>, <, >= or <=) on the indexed
105667     **         column that immediately follows the N equalities. Only 
105668     **         the right-most column can be an inequality - the rest must
105669     **         use the "==" and "IN" operators. For example, if the 
105670     **         index is on (x,y,z), then the following clauses are all 
105671     **         optimized:
105672     **
105673     **            x=5
105674     **            x=5 AND y=10
105675     **            x=5 AND y<10
105676     **            x=5 AND y>5 AND y<10
105677     **            x=5 AND y=5 AND z<=10
105678     **
105679     **         The z<10 term of the following cannot be used, only
105680     **         the x=5 term:
105681     **
105682     **            x=5 AND z<10
105683     **
105684     **         N may be zero if there are inequality constraints.
105685     **         If there are no inequality constraints, then N is at
105686     **         least one.
105687     **
105688     **         This case is also used when there are no WHERE clause
105689     **         constraints but an index is selected anyway, in order
105690     **         to force the output order to conform to an ORDER BY.
105691     */  
105692     static const u8 aStartOp[] = {
105693       0,
105694       0,
105695       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
105696       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
105697       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
105698       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
105699       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
105700       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
105701     };
105702     static const u8 aEndOp[] = {
105703       OP_Noop,             /* 0: (!end_constraints) */
105704       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
105705       OP_IdxLT             /* 2: (end_constraints && bRev) */
105706     };
105707     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
105708     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
105709     int regBase;                 /* Base register holding constraint values */
105710     int r1;                      /* Temp register */
105711     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
105712     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
105713     int startEq;                 /* True if range start uses ==, >= or <= */
105714     int endEq;                   /* True if range end uses ==, >= or <= */
105715     int start_constraints;       /* Start of range is constrained */
105716     int nConstraint;             /* Number of constraint terms */
105717     Index *pIdx;                 /* The index we will be using */
105718     int iIdxCur;                 /* The VDBE cursor for the index */
105719     int nExtraReg = 0;           /* Number of extra registers needed */
105720     int op;                      /* Instruction opcode */
105721     char *zStartAff;             /* Affinity for start of range constraint */
105722     char *zEndAff;               /* Affinity for end of range constraint */
105723
105724     pIdx = pLevel->plan.u.pIdx;
105725     iIdxCur = pLevel->iIdxCur;
105726     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
105727
105728     /* If this loop satisfies a sort order (pOrderBy) request that 
105729     ** was passed to this function to implement a "SELECT min(x) ..." 
105730     ** query, then the caller will only allow the loop to run for
105731     ** a single iteration. This means that the first row returned
105732     ** should not have a NULL value stored in 'x'. If column 'x' is
105733     ** the first one after the nEq equality constraints in the index,
105734     ** this requires some special handling.
105735     */
105736     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
105737      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
105738      && (pIdx->nColumn>nEq)
105739     ){
105740       /* assert( pOrderBy->nExpr==1 ); */
105741       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
105742       isMinQuery = 1;
105743       nExtraReg = 1;
105744     }
105745
105746     /* Find any inequality constraint terms for the start and end 
105747     ** of the range. 
105748     */
105749     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
105750       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
105751       nExtraReg = 1;
105752     }
105753     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
105754       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
105755       nExtraReg = 1;
105756     }
105757
105758     /* Generate code to evaluate all constraint terms using == or IN
105759     ** and store the values of those terms in an array of registers
105760     ** starting at regBase.
105761     */
105762     regBase = codeAllEqualityTerms(
105763         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
105764     );
105765     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
105766     addrNxt = pLevel->addrNxt;
105767
105768     /* If we are doing a reverse order scan on an ascending index, or
105769     ** a forward order scan on a descending index, interchange the 
105770     ** start and end terms (pRangeStart and pRangeEnd).
105771     */
105772     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
105773      || (bRev && pIdx->nColumn==nEq)
105774     ){
105775       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
105776     }
105777
105778     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
105779     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
105780     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
105781     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
105782     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
105783     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
105784     start_constraints = pRangeStart || nEq>0;
105785
105786     /* Seek the index cursor to the start of the range. */
105787     nConstraint = nEq;
105788     if( pRangeStart ){
105789       Expr *pRight = pRangeStart->pExpr->pRight;
105790       sqlite3ExprCode(pParse, pRight, regBase+nEq);
105791       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
105792         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
105793       }
105794       if( zStartAff ){
105795         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
105796           /* Since the comparison is to be performed with no conversions
105797           ** applied to the operands, set the affinity to apply to pRight to 
105798           ** SQLITE_AFF_NONE.  */
105799           zStartAff[nEq] = SQLITE_AFF_NONE;
105800         }
105801         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
105802           zStartAff[nEq] = SQLITE_AFF_NONE;
105803         }
105804       }  
105805       nConstraint++;
105806       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105807     }else if( isMinQuery ){
105808       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
105809       nConstraint++;
105810       startEq = 0;
105811       start_constraints = 1;
105812     }
105813     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
105814     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
105815     assert( op!=0 );
105816     testcase( op==OP_Rewind );
105817     testcase( op==OP_Last );
105818     testcase( op==OP_SeekGt );
105819     testcase( op==OP_SeekGe );
105820     testcase( op==OP_SeekLe );
105821     testcase( op==OP_SeekLt );
105822     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
105823
105824     /* Load the value for the inequality constraint at the end of the
105825     ** range (if any).
105826     */
105827     nConstraint = nEq;
105828     if( pRangeEnd ){
105829       Expr *pRight = pRangeEnd->pExpr->pRight;
105830       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
105831       sqlite3ExprCode(pParse, pRight, regBase+nEq);
105832       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
105833         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
105834       }
105835       if( zEndAff ){
105836         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
105837           /* Since the comparison is to be performed with no conversions
105838           ** applied to the operands, set the affinity to apply to pRight to 
105839           ** SQLITE_AFF_NONE.  */
105840           zEndAff[nEq] = SQLITE_AFF_NONE;
105841         }
105842         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
105843           zEndAff[nEq] = SQLITE_AFF_NONE;
105844         }
105845       }  
105846       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
105847       nConstraint++;
105848       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105849     }
105850     sqlite3DbFree(pParse->db, zStartAff);
105851     sqlite3DbFree(pParse->db, zEndAff);
105852
105853     /* Top of the loop body */
105854     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
105855
105856     /* Check if the index cursor is past the end of the range. */
105857     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
105858     testcase( op==OP_Noop );
105859     testcase( op==OP_IdxGE );
105860     testcase( op==OP_IdxLT );
105861     if( op!=OP_Noop ){
105862       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
105863       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
105864     }
105865
105866     /* If there are inequality constraints, check that the value
105867     ** of the table column that the inequality contrains is not NULL.
105868     ** If it is, jump to the next iteration of the loop.
105869     */
105870     r1 = sqlite3GetTempReg(pParse);
105871     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
105872     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
105873     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
105874       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
105875       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
105876     }
105877     sqlite3ReleaseTempReg(pParse, r1);
105878
105879     /* Seek the table cursor, if required */
105880     disableTerm(pLevel, pRangeStart);
105881     disableTerm(pLevel, pRangeEnd);
105882     if( !omitTable ){
105883       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
105884       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
105885       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
105886       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
105887     }
105888
105889     /* Record the instruction used to terminate the loop. Disable 
105890     ** WHERE clause terms made redundant by the index range scan.
105891     */
105892     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
105893       pLevel->op = OP_Noop;
105894     }else if( bRev ){
105895       pLevel->op = OP_Prev;
105896     }else{
105897       pLevel->op = OP_Next;
105898     }
105899     pLevel->p1 = iIdxCur;
105900   }else
105901
105902 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
105903   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
105904     /* Case 4:  Two or more separately indexed terms connected by OR
105905     **
105906     ** Example:
105907     **
105908     **   CREATE TABLE t1(a,b,c,d);
105909     **   CREATE INDEX i1 ON t1(a);
105910     **   CREATE INDEX i2 ON t1(b);
105911     **   CREATE INDEX i3 ON t1(c);
105912     **
105913     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
105914     **
105915     ** In the example, there are three indexed terms connected by OR.
105916     ** The top of the loop looks like this:
105917     **
105918     **          Null       1                # Zero the rowset in reg 1
105919     **
105920     ** Then, for each indexed term, the following. The arguments to
105921     ** RowSetTest are such that the rowid of the current row is inserted
105922     ** into the RowSet. If it is already present, control skips the
105923     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
105924     **
105925     **        sqlite3WhereBegin(<term>)
105926     **          RowSetTest                  # Insert rowid into rowset
105927     **          Gosub      2 A
105928     **        sqlite3WhereEnd()
105929     **
105930     ** Following the above, code to terminate the loop. Label A, the target
105931     ** of the Gosub above, jumps to the instruction right after the Goto.
105932     **
105933     **          Null       1                # Zero the rowset in reg 1
105934     **          Goto       B                # The loop is finished.
105935     **
105936     **       A: <loop body>                 # Return data, whatever.
105937     **
105938     **          Return     2                # Jump back to the Gosub
105939     **
105940     **       B: <after the loop>
105941     **
105942     */
105943     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
105944     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
105945     Index *pCov = 0;             /* Potential covering index (or NULL) */
105946     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
105947
105948     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
105949     int regRowset = 0;                        /* Register for RowSet object */
105950     int regRowid = 0;                         /* Register holding rowid */
105951     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
105952     int iRetInit;                             /* Address of regReturn init */
105953     int untestedTerms = 0;             /* Some terms not completely tested */
105954     int ii;                            /* Loop counter */
105955     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
105956    
105957     pTerm = pLevel->plan.u.pTerm;
105958     assert( pTerm!=0 );
105959     assert( pTerm->eOperator==WO_OR );
105960     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
105961     pOrWc = &pTerm->u.pOrInfo->wc;
105962     pLevel->op = OP_Return;
105963     pLevel->p1 = regReturn;
105964
105965     /* Set up a new SrcList in pOrTab containing the table being scanned
105966     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
105967     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
105968     */
105969     if( pWInfo->nLevel>1 ){
105970       int nNotReady;                 /* The number of notReady tables */
105971       struct SrcList_item *origSrc;     /* Original list of tables */
105972       nNotReady = pWInfo->nLevel - iLevel - 1;
105973       pOrTab = sqlite3StackAllocRaw(pParse->db,
105974                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
105975       if( pOrTab==0 ) return notReady;
105976       pOrTab->nAlloc = (i16)(nNotReady + 1);
105977       pOrTab->nSrc = pOrTab->nAlloc;
105978       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
105979       origSrc = pWInfo->pTabList->a;
105980       for(k=1; k<=nNotReady; k++){
105981         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
105982       }
105983     }else{
105984       pOrTab = pWInfo->pTabList;
105985     }
105986
105987     /* Initialize the rowset register to contain NULL. An SQL NULL is 
105988     ** equivalent to an empty rowset.
105989     **
105990     ** Also initialize regReturn to contain the address of the instruction 
105991     ** immediately following the OP_Return at the bottom of the loop. This
105992     ** is required in a few obscure LEFT JOIN cases where control jumps
105993     ** over the top of the loop into the body of it. In this case the 
105994     ** correct response for the end-of-loop code (the OP_Return) is to 
105995     ** fall through to the next instruction, just as an OP_Next does if
105996     ** called on an uninitialized cursor.
105997     */
105998     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
105999       regRowset = ++pParse->nMem;
106000       regRowid = ++pParse->nMem;
106001       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
106002     }
106003     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
106004
106005     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
106006     ** Then for every term xN, evaluate as the subexpression: xN AND z
106007     ** That way, terms in y that are factored into the disjunction will
106008     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
106009     **
106010     ** Actually, each subexpression is converted to "xN AND w" where w is
106011     ** the "interesting" terms of z - terms that did not originate in the
106012     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
106013     ** indices.
106014     */
106015     if( pWC->nTerm>1 ){
106016       int iTerm;
106017       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
106018         Expr *pExpr = pWC->a[iTerm].pExpr;
106019         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
106020         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
106021         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
106022         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
106023         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
106024       }
106025       if( pAndExpr ){
106026         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
106027       }
106028     }
106029
106030     for(ii=0; ii<pOrWc->nTerm; ii++){
106031       WhereTerm *pOrTerm = &pOrWc->a[ii];
106032       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
106033         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
106034         Expr *pOrExpr = pOrTerm->pExpr;
106035         if( pAndExpr ){
106036           pAndExpr->pLeft = pOrExpr;
106037           pOrExpr = pAndExpr;
106038         }
106039         /* Loop through table entries that match term pOrTerm. */
106040         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
106041                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
106042                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
106043         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
106044         if( pSubWInfo ){
106045           WhereLevel *pLvl;
106046           explainOneScan(
106047               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
106048           );
106049           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106050             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
106051             int r;
106052             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
106053                                          regRowid, 0);
106054             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
106055                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
106056           }
106057           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
106058
106059           /* The pSubWInfo->untestedTerms flag means that this OR term
106060           ** contained one or more AND term from a notReady table.  The
106061           ** terms from the notReady table could not be tested and will
106062           ** need to be tested later.
106063           */
106064           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
106065
106066           /* If all of the OR-connected terms are optimized using the same
106067           ** index, and the index is opened using the same cursor number
106068           ** by each call to sqlite3WhereBegin() made by this loop, it may
106069           ** be possible to use that index as a covering index.
106070           **
106071           ** If the call to sqlite3WhereBegin() above resulted in a scan that
106072           ** uses an index, and this is either the first OR-connected term
106073           ** processed or the index is the same as that used by all previous
106074           ** terms, set pCov to the candidate covering index. Otherwise, set 
106075           ** pCov to NULL to indicate that no candidate covering index will 
106076           ** be available.
106077           */
106078           pLvl = &pSubWInfo->a[0];
106079           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
106080            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
106081            && (ii==0 || pLvl->plan.u.pIdx==pCov)
106082           ){
106083             assert( pLvl->iIdxCur==iCovCur );
106084             pCov = pLvl->plan.u.pIdx;
106085           }else{
106086             pCov = 0;
106087           }
106088
106089           /* Finish the loop through table entries that match term pOrTerm. */
106090           sqlite3WhereEnd(pSubWInfo);
106091         }
106092       }
106093     }
106094     pLevel->u.pCovidx = pCov;
106095     if( pCov ) pLevel->iIdxCur = iCovCur;
106096     if( pAndExpr ){
106097       pAndExpr->pLeft = 0;
106098       sqlite3ExprDelete(pParse->db, pAndExpr);
106099     }
106100     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
106101     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
106102     sqlite3VdbeResolveLabel(v, iLoopBody);
106103
106104     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
106105     if( !untestedTerms ) disableTerm(pLevel, pTerm);
106106   }else
106107 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106108
106109   {
106110     /* Case 5:  There is no usable index.  We must do a complete
106111     **          scan of the entire table.
106112     */
106113     static const u8 aStep[] = { OP_Next, OP_Prev };
106114     static const u8 aStart[] = { OP_Rewind, OP_Last };
106115     assert( bRev==0 || bRev==1 );
106116     assert( omitTable==0 );
106117     pLevel->op = aStep[bRev];
106118     pLevel->p1 = iCur;
106119     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
106120     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106121   }
106122   notReady &= ~getMask(pWC->pMaskSet, iCur);
106123
106124   /* Insert code to test every subexpression that can be completely
106125   ** computed using the current set of tables.
106126   **
106127   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
106128   ** the use of indices become tests that are evaluated against each row of
106129   ** the relevant input tables.
106130   */
106131   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
106132     Expr *pE;
106133     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
106134     testcase( pTerm->wtFlags & TERM_CODED );
106135     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106136     if( (pTerm->prereqAll & notReady)!=0 ){
106137       testcase( pWInfo->untestedTerms==0
106138                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
106139       pWInfo->untestedTerms = 1;
106140       continue;
106141     }
106142     pE = pTerm->pExpr;
106143     assert( pE!=0 );
106144     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
106145       continue;
106146     }
106147     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
106148     pTerm->wtFlags |= TERM_CODED;
106149   }
106150
106151   /* For a LEFT OUTER JOIN, generate code that will record the fact that
106152   ** at least one row of the right table has matched the left table.  
106153   */
106154   if( pLevel->iLeftJoin ){
106155     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
106156     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
106157     VdbeComment((v, "record LEFT JOIN hit"));
106158     sqlite3ExprCacheClear(pParse);
106159     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
106160       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
106161       testcase( pTerm->wtFlags & TERM_CODED );
106162       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106163       if( (pTerm->prereqAll & notReady)!=0 ){
106164         assert( pWInfo->untestedTerms );
106165         continue;
106166       }
106167       assert( pTerm->pExpr );
106168       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
106169       pTerm->wtFlags |= TERM_CODED;
106170     }
106171   }
106172   sqlite3ReleaseTempReg(pParse, iReleaseReg);
106173
106174   return notReady;
106175 }
106176
106177 #if defined(SQLITE_TEST)
106178 /*
106179 ** The following variable holds a text description of query plan generated
106180 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
106181 ** overwrites the previous.  This information is used for testing and
106182 ** analysis only.
106183 */
106184 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
106185 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
106186
106187 #endif /* SQLITE_TEST */
106188
106189
106190 /*
106191 ** Free a WhereInfo structure
106192 */
106193 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
106194   if( ALWAYS(pWInfo) ){
106195     int i;
106196     for(i=0; i<pWInfo->nLevel; i++){
106197       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
106198       if( pInfo ){
106199         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
106200         if( pInfo->needToFreeIdxStr ){
106201           sqlite3_free(pInfo->idxStr);
106202         }
106203         sqlite3DbFree(db, pInfo);
106204       }
106205       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
106206         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
106207         if( pIdx ){
106208           sqlite3DbFree(db, pIdx->zColAff);
106209           sqlite3DbFree(db, pIdx);
106210         }
106211       }
106212     }
106213     whereClauseClear(pWInfo->pWC);
106214     sqlite3DbFree(db, pWInfo);
106215   }
106216 }
106217
106218
106219 /*
106220 ** Generate the beginning of the loop used for WHERE clause processing.
106221 ** The return value is a pointer to an opaque structure that contains
106222 ** information needed to terminate the loop.  Later, the calling routine
106223 ** should invoke sqlite3WhereEnd() with the return value of this function
106224 ** in order to complete the WHERE clause processing.
106225 **
106226 ** If an error occurs, this routine returns NULL.
106227 **
106228 ** The basic idea is to do a nested loop, one loop for each table in
106229 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
106230 ** same as a SELECT with only a single table in the FROM clause.)  For
106231 ** example, if the SQL is this:
106232 **
106233 **       SELECT * FROM t1, t2, t3 WHERE ...;
106234 **
106235 ** Then the code generated is conceptually like the following:
106236 **
106237 **      foreach row1 in t1 do       \    Code generated
106238 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
106239 **          foreach row3 in t3 do   /
106240 **            ...
106241 **          end                     \    Code generated
106242 **        end                        |-- by sqlite3WhereEnd()
106243 **      end                         /
106244 **
106245 ** Note that the loops might not be nested in the order in which they
106246 ** appear in the FROM clause if a different order is better able to make
106247 ** use of indices.  Note also that when the IN operator appears in
106248 ** the WHERE clause, it might result in additional nested loops for
106249 ** scanning through all values on the right-hand side of the IN.
106250 **
106251 ** There are Btree cursors associated with each table.  t1 uses cursor
106252 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
106253 ** And so forth.  This routine generates code to open those VDBE cursors
106254 ** and sqlite3WhereEnd() generates the code to close them.
106255 **
106256 ** The code that sqlite3WhereBegin() generates leaves the cursors named
106257 ** in pTabList pointing at their appropriate entries.  The [...] code
106258 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
106259 ** data from the various tables of the loop.
106260 **
106261 ** If the WHERE clause is empty, the foreach loops must each scan their
106262 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
106263 ** the tables have indices and there are terms in the WHERE clause that
106264 ** refer to those indices, a complete table scan can be avoided and the
106265 ** code will run much faster.  Most of the work of this routine is checking
106266 ** to see if there are indices that can be used to speed up the loop.
106267 **
106268 ** Terms of the WHERE clause are also used to limit which rows actually
106269 ** make it to the "..." in the middle of the loop.  After each "foreach",
106270 ** terms of the WHERE clause that use only terms in that loop and outer
106271 ** loops are evaluated and if false a jump is made around all subsequent
106272 ** inner loops (or around the "..." if the test occurs within the inner-
106273 ** most loop)
106274 **
106275 ** OUTER JOINS
106276 **
106277 ** An outer join of tables t1 and t2 is conceptally coded as follows:
106278 **
106279 **    foreach row1 in t1 do
106280 **      flag = 0
106281 **      foreach row2 in t2 do
106282 **        start:
106283 **          ...
106284 **          flag = 1
106285 **      end
106286 **      if flag==0 then
106287 **        move the row2 cursor to a null row
106288 **        goto start
106289 **      fi
106290 **    end
106291 **
106292 ** ORDER BY CLAUSE PROCESSING
106293 **
106294 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
106295 ** if there is one.  If there is no ORDER BY clause or if this routine
106296 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
106297 **
106298 ** If an index can be used so that the natural output order of the table
106299 ** scan is correct for the ORDER BY clause, then that index is used and
106300 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
106301 ** unnecessary sort of the result set if an index appropriate for the
106302 ** ORDER BY clause already exists.
106303 **
106304 ** If the where clause loops cannot be arranged to provide the correct
106305 ** output order, then the *ppOrderBy is unchanged.
106306 */
106307 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
106308   Parse *pParse,        /* The parser context */
106309   SrcList *pTabList,    /* A list of all tables to be scanned */
106310   Expr *pWhere,         /* The WHERE clause */
106311   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
106312   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
106313   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
106314   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
106315 ){
106316   int i;                     /* Loop counter */
106317   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
106318   int nTabList;              /* Number of elements in pTabList */
106319   WhereInfo *pWInfo;         /* Will become the return value of this function */
106320   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
106321   Bitmask notReady;          /* Cursors that are not yet positioned */
106322   WhereMaskSet *pMaskSet;    /* The expression mask set */
106323   WhereClause *pWC;               /* Decomposition of the WHERE clause */
106324   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
106325   WhereLevel *pLevel;             /* A single level in the pWInfo list */
106326   int iFrom;                      /* First unused FROM clause element */
106327   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
106328   sqlite3 *db;               /* Database connection */
106329
106330   /* The number of tables in the FROM clause is limited by the number of
106331   ** bits in a Bitmask 
106332   */
106333   testcase( pTabList->nSrc==BMS );
106334   if( pTabList->nSrc>BMS ){
106335     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
106336     return 0;
106337   }
106338
106339   /* This function normally generates a nested loop for all tables in 
106340   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
106341   ** only generate code for the first table in pTabList and assume that
106342   ** any cursors associated with subsequent tables are uninitialized.
106343   */
106344   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
106345
106346   /* Allocate and initialize the WhereInfo structure that will become the
106347   ** return value. A single allocation is used to store the WhereInfo
106348   ** struct, the contents of WhereInfo.a[], the WhereClause structure
106349   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
106350   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
106351   ** some architectures. Hence the ROUND8() below.
106352   */
106353   db = pParse->db;
106354   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
106355   pWInfo = sqlite3DbMallocZero(db, 
106356       nByteWInfo + 
106357       sizeof(WhereClause) +
106358       sizeof(WhereMaskSet)
106359   );
106360   if( db->mallocFailed ){
106361     sqlite3DbFree(db, pWInfo);
106362     pWInfo = 0;
106363     goto whereBeginError;
106364   }
106365   pWInfo->nLevel = nTabList;
106366   pWInfo->pParse = pParse;
106367   pWInfo->pTabList = pTabList;
106368   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
106369   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
106370   pWInfo->wctrlFlags = wctrlFlags;
106371   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
106372   pMaskSet = (WhereMaskSet*)&pWC[1];
106373
106374   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
106375   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
106376   if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
106377
106378   /* Split the WHERE clause into separate subexpressions where each
106379   ** subexpression is separated by an AND operator.
106380   */
106381   initMaskSet(pMaskSet);
106382   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
106383   sqlite3ExprCodeConstants(pParse, pWhere);
106384   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
106385     
106386   /* Special case: a WHERE clause that is constant.  Evaluate the
106387   ** expression and either jump over all of the code or fall thru.
106388   */
106389   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
106390     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
106391     pWhere = 0;
106392   }
106393
106394   /* Assign a bit from the bitmask to every term in the FROM clause.
106395   **
106396   ** When assigning bitmask values to FROM clause cursors, it must be
106397   ** the case that if X is the bitmask for the N-th FROM clause term then
106398   ** the bitmask for all FROM clause terms to the left of the N-th term
106399   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
106400   ** its Expr.iRightJoinTable value to find the bitmask of the right table
106401   ** of the join.  Subtracting one from the right table bitmask gives a
106402   ** bitmask for all tables to the left of the join.  Knowing the bitmask
106403   ** for all tables to the left of a left join is important.  Ticket #3015.
106404   **
106405   ** Configure the WhereClause.vmask variable so that bits that correspond
106406   ** to virtual table cursors are set. This is used to selectively disable 
106407   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
106408   ** with virtual tables.
106409   **
106410   ** Note that bitmasks are created for all pTabList->nSrc tables in
106411   ** pTabList, not just the first nTabList tables.  nTabList is normally
106412   ** equal to pTabList->nSrc but might be shortened to 1 if the
106413   ** WHERE_ONETABLE_ONLY flag is set.
106414   */
106415   assert( pWC->vmask==0 && pMaskSet->n==0 );
106416   for(i=0; i<pTabList->nSrc; i++){
106417     createMask(pMaskSet, pTabList->a[i].iCursor);
106418 #ifndef SQLITE_OMIT_VIRTUALTABLE
106419     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
106420       pWC->vmask |= ((Bitmask)1 << i);
106421     }
106422 #endif
106423   }
106424 #ifndef NDEBUG
106425   {
106426     Bitmask toTheLeft = 0;
106427     for(i=0; i<pTabList->nSrc; i++){
106428       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
106429       assert( (m-1)==toTheLeft );
106430       toTheLeft |= m;
106431     }
106432   }
106433 #endif
106434
106435   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
106436   ** add new virtual terms onto the end of the WHERE clause.  We do not
106437   ** want to analyze these virtual terms, so start analyzing at the end
106438   ** and work forward so that the added virtual terms are never processed.
106439   */
106440   exprAnalyzeAll(pTabList, pWC);
106441   if( db->mallocFailed ){
106442     goto whereBeginError;
106443   }
106444
106445   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
106446   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
106447   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
106448   */
106449   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
106450     pDistinct = 0;
106451     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
106452   }
106453
106454   /* Chose the best index to use for each table in the FROM clause.
106455   **
106456   ** This loop fills in the following fields:
106457   **
106458   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
106459   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
106460   **   pWInfo->a[].nEq       The number of == and IN constraints
106461   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
106462   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
106463   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
106464   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
106465   **
106466   ** This loop also figures out the nesting order of tables in the FROM
106467   ** clause.
106468   */
106469   notReady = ~(Bitmask)0;
106470   andFlags = ~0;
106471   WHERETRACE(("*** Optimizer Start ***\n"));
106472   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
106473     WhereCost bestPlan;         /* Most efficient plan seen so far */
106474     Index *pIdx;                /* Index for FROM table at pTabItem */
106475     int j;                      /* For looping over FROM tables */
106476     int bestJ = -1;             /* The value of j */
106477     Bitmask m;                  /* Bitmask value for j or bestJ */
106478     int isOptimal;              /* Iterator for optimal/non-optimal search */
106479     int nUnconstrained;         /* Number tables without INDEXED BY */
106480     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
106481
106482     memset(&bestPlan, 0, sizeof(bestPlan));
106483     bestPlan.rCost = SQLITE_BIG_DBL;
106484     WHERETRACE(("*** Begin search for loop %d ***\n", i));
106485
106486     /* Loop through the remaining entries in the FROM clause to find the
106487     ** next nested loop. The loop tests all FROM clause entries
106488     ** either once or twice. 
106489     **
106490     ** The first test is always performed if there are two or more entries
106491     ** remaining and never performed if there is only one FROM clause entry
106492     ** to choose from.  The first test looks for an "optimal" scan.  In
106493     ** this context an optimal scan is one that uses the same strategy
106494     ** for the given FROM clause entry as would be selected if the entry
106495     ** were used as the innermost nested loop.  In other words, a table
106496     ** is chosen such that the cost of running that table cannot be reduced
106497     ** by waiting for other tables to run first.  This "optimal" test works
106498     ** by first assuming that the FROM clause is on the inner loop and finding
106499     ** its query plan, then checking to see if that query plan uses any
106500     ** other FROM clause terms that are notReady.  If no notReady terms are
106501     ** used then the "optimal" query plan works.
106502     **
106503     ** Note that the WhereCost.nRow parameter for an optimal scan might
106504     ** not be as small as it would be if the table really were the innermost
106505     ** join.  The nRow value can be reduced by WHERE clause constraints
106506     ** that do not use indices.  But this nRow reduction only happens if the
106507     ** table really is the innermost join.  
106508     **
106509     ** The second loop iteration is only performed if no optimal scan
106510     ** strategies were found by the first iteration. This second iteration
106511     ** is used to search for the lowest cost scan overall.
106512     **
106513     ** Previous versions of SQLite performed only the second iteration -
106514     ** the next outermost loop was always that with the lowest overall
106515     ** cost. However, this meant that SQLite could select the wrong plan
106516     ** for scripts such as the following:
106517     **   
106518     **   CREATE TABLE t1(a, b); 
106519     **   CREATE TABLE t2(c, d);
106520     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
106521     **
106522     ** The best strategy is to iterate through table t1 first. However it
106523     ** is not possible to determine this with a simple greedy algorithm.
106524     ** Since the cost of a linear scan through table t2 is the same 
106525     ** as the cost of a linear scan through table t1, a simple greedy 
106526     ** algorithm may choose to use t2 for the outer loop, which is a much
106527     ** costlier approach.
106528     */
106529     nUnconstrained = 0;
106530     notIndexed = 0;
106531     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
106532       Bitmask mask;             /* Mask of tables not yet ready */
106533       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
106534         int doNotReorder;    /* True if this table should not be reordered */
106535         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
106536         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
106537         ExprList *pDist;     /* DISTINCT clause for index to optimize */
106538   
106539         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
106540         if( j!=iFrom && doNotReorder ) break;
106541         m = getMask(pMaskSet, pTabItem->iCursor);
106542         if( (m & notReady)==0 ){
106543           if( j==iFrom ) iFrom++;
106544           continue;
106545         }
106546         mask = (isOptimal ? m : notReady);
106547         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
106548         pDist = (i==0 ? pDistinct : 0);
106549         if( pTabItem->pIndex==0 ) nUnconstrained++;
106550   
106551         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
106552                     j, isOptimal));
106553         assert( pTabItem->pTab );
106554 #ifndef SQLITE_OMIT_VIRTUALTABLE
106555         if( IsVirtual(pTabItem->pTab) ){
106556           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
106557           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
106558                            &sCost, pp);
106559         }else 
106560 #endif
106561         {
106562           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
106563               pDist, &sCost);
106564         }
106565         assert( isOptimal || (sCost.used&notReady)==0 );
106566
106567         /* If an INDEXED BY clause is present, then the plan must use that
106568         ** index if it uses any index at all */
106569         assert( pTabItem->pIndex==0 
106570                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
106571                   || sCost.plan.u.pIdx==pTabItem->pIndex );
106572
106573         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
106574           notIndexed |= m;
106575         }
106576
106577         /* Conditions under which this table becomes the best so far:
106578         **
106579         **   (1) The table must not depend on other tables that have not
106580         **       yet run.
106581         **
106582         **   (2) A full-table-scan plan cannot supercede indexed plan unless
106583         **       the full-table-scan is an "optimal" plan as defined above.
106584         **
106585         **   (3) All tables have an INDEXED BY clause or this table lacks an
106586         **       INDEXED BY clause or this table uses the specific
106587         **       index specified by its INDEXED BY clause.  This rule ensures
106588         **       that a best-so-far is always selected even if an impossible
106589         **       combination of INDEXED BY clauses are given.  The error
106590         **       will be detected and relayed back to the application later.
106591         **       The NEVER() comes about because rule (2) above prevents
106592         **       An indexable full-table-scan from reaching rule (3).
106593         **
106594         **   (4) The plan cost must be lower than prior plans or else the
106595         **       cost must be the same and the number of rows must be lower.
106596         */
106597         if( (sCost.used&notReady)==0                       /* (1) */
106598             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
106599                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
106600                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
106601             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
106602                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
106603             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
106604                 || (sCost.rCost<=bestPlan.rCost 
106605                  && sCost.plan.nRow<bestPlan.plan.nRow))
106606         ){
106607           WHERETRACE(("=== table %d is best so far"
106608                       " with cost=%g and nRow=%g\n",
106609                       j, sCost.rCost, sCost.plan.nRow));
106610           bestPlan = sCost;
106611           bestJ = j;
106612         }
106613         if( doNotReorder ) break;
106614       }
106615     }
106616     assert( bestJ>=0 );
106617     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
106618     WHERETRACE(("*** Optimizer selects table %d for loop %d"
106619                 " with cost=%g and nRow=%g\n",
106620                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
106621     /* The ALWAYS() that follows was added to hush up clang scan-build */
106622     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
106623       *ppOrderBy = 0;
106624     }
106625     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
106626       assert( pWInfo->eDistinct==0 );
106627       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
106628     }
106629     andFlags &= bestPlan.plan.wsFlags;
106630     pLevel->plan = bestPlan.plan;
106631     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
106632     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
106633     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
106634       if( (wctrlFlags & WHERE_ONETABLE_ONLY) 
106635        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0 
106636       ){
106637         pLevel->iIdxCur = iIdxCur;
106638       }else{
106639         pLevel->iIdxCur = pParse->nTab++;
106640       }
106641     }else{
106642       pLevel->iIdxCur = -1;
106643     }
106644     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
106645     pLevel->iFrom = (u8)bestJ;
106646     if( bestPlan.plan.nRow>=(double)1 ){
106647       pParse->nQueryLoop *= bestPlan.plan.nRow;
106648     }
106649
106650     /* Check that if the table scanned by this loop iteration had an
106651     ** INDEXED BY clause attached to it, that the named index is being
106652     ** used for the scan. If not, then query compilation has failed.
106653     ** Return an error.
106654     */
106655     pIdx = pTabList->a[bestJ].pIndex;
106656     if( pIdx ){
106657       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
106658         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
106659         goto whereBeginError;
106660       }else{
106661         /* If an INDEXED BY clause is used, the bestIndex() function is
106662         ** guaranteed to find the index specified in the INDEXED BY clause
106663         ** if it find an index at all. */
106664         assert( bestPlan.plan.u.pIdx==pIdx );
106665       }
106666     }
106667   }
106668   WHERETRACE(("*** Optimizer Finished ***\n"));
106669   if( pParse->nErr || db->mallocFailed ){
106670     goto whereBeginError;
106671   }
106672
106673   /* If the total query only selects a single row, then the ORDER BY
106674   ** clause is irrelevant.
106675   */
106676   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
106677     *ppOrderBy = 0;
106678   }
106679
106680   /* If the caller is an UPDATE or DELETE statement that is requesting
106681   ** to use a one-pass algorithm, determine if this is appropriate.
106682   ** The one-pass algorithm only works if the WHERE clause constraints
106683   ** the statement to update a single row.
106684   */
106685   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
106686   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
106687     pWInfo->okOnePass = 1;
106688     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
106689   }
106690
106691   /* Open all tables in the pTabList and any indices selected for
106692   ** searching those tables.
106693   */
106694   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
106695   notReady = ~(Bitmask)0;
106696   pWInfo->nRowOut = (double)1;
106697   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
106698     Table *pTab;     /* Table to open */
106699     int iDb;         /* Index of database containing table/index */
106700
106701     pTabItem = &pTabList->a[pLevel->iFrom];
106702     pTab = pTabItem->pTab;
106703     pLevel->iTabCur = pTabItem->iCursor;
106704     pWInfo->nRowOut *= pLevel->plan.nRow;
106705     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106706     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
106707       /* Do nothing */
106708     }else
106709 #ifndef SQLITE_OMIT_VIRTUALTABLE
106710     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
106711       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
106712       int iCur = pTabItem->iCursor;
106713       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
106714     }else
106715 #endif
106716     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
106717          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
106718       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
106719       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
106720       testcase( pTab->nCol==BMS-1 );
106721       testcase( pTab->nCol==BMS );
106722       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
106723         Bitmask b = pTabItem->colUsed;
106724         int n = 0;
106725         for(; b; b=b>>1, n++){}
106726         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
106727                             SQLITE_INT_TO_PTR(n), P4_INT32);
106728         assert( n<=pTab->nCol );
106729       }
106730     }else{
106731       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
106732     }
106733 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106734     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
106735       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
106736     }else
106737 #endif
106738     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
106739       Index *pIx = pLevel->plan.u.pIdx;
106740       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
106741       int iIndexCur = pLevel->iIdxCur;
106742       assert( pIx->pSchema==pTab->pSchema );
106743       assert( iIndexCur>=0 );
106744       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
106745                         (char*)pKey, P4_KEYINFO_HANDOFF);
106746       VdbeComment((v, "%s", pIx->zName));
106747     }
106748     sqlite3CodeVerifySchema(pParse, iDb);
106749     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
106750   }
106751   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
106752   if( db->mallocFailed ) goto whereBeginError;
106753
106754   /* Generate the code to do the search.  Each iteration of the for
106755   ** loop below generates code for a single nested loop of the VM
106756   ** program.
106757   */
106758   notReady = ~(Bitmask)0;
106759   for(i=0; i<nTabList; i++){
106760     pLevel = &pWInfo->a[i];
106761     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
106762     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
106763     pWInfo->iContinue = pLevel->addrCont;
106764   }
106765
106766 #ifdef SQLITE_TEST  /* For testing and debugging use only */
106767   /* Record in the query plan information about the current table
106768   ** and the index used to access it (if any).  If the table itself
106769   ** is not used, its name is just '{}'.  If no index is used
106770   ** the index is listed as "{}".  If the primary key is used the
106771   ** index name is '*'.
106772   */
106773   for(i=0; i<nTabList; i++){
106774     char *z;
106775     int n;
106776     pLevel = &pWInfo->a[i];
106777     pTabItem = &pTabList->a[pLevel->iFrom];
106778     z = pTabItem->zAlias;
106779     if( z==0 ) z = pTabItem->pTab->zName;
106780     n = sqlite3Strlen30(z);
106781     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
106782       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
106783         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
106784         nQPlan += 2;
106785       }else{
106786         memcpy(&sqlite3_query_plan[nQPlan], z, n);
106787         nQPlan += n;
106788       }
106789       sqlite3_query_plan[nQPlan++] = ' ';
106790     }
106791     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
106792     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
106793     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
106794       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
106795       nQPlan += 2;
106796     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
106797       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
106798       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
106799         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
106800         nQPlan += n;
106801         sqlite3_query_plan[nQPlan++] = ' ';
106802       }
106803     }else{
106804       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
106805       nQPlan += 3;
106806     }
106807   }
106808   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
106809     sqlite3_query_plan[--nQPlan] = 0;
106810   }
106811   sqlite3_query_plan[nQPlan] = 0;
106812   nQPlan = 0;
106813 #endif /* SQLITE_TEST // Testing and debugging use only */
106814
106815   /* Record the continuation address in the WhereInfo structure.  Then
106816   ** clean up and return.
106817   */
106818   return pWInfo;
106819
106820   /* Jump here if malloc fails */
106821 whereBeginError:
106822   if( pWInfo ){
106823     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
106824     whereInfoFree(db, pWInfo);
106825   }
106826   return 0;
106827 }
106828
106829 /*
106830 ** Generate the end of the WHERE loop.  See comments on 
106831 ** sqlite3WhereBegin() for additional information.
106832 */
106833 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
106834   Parse *pParse = pWInfo->pParse;
106835   Vdbe *v = pParse->pVdbe;
106836   int i;
106837   WhereLevel *pLevel;
106838   SrcList *pTabList = pWInfo->pTabList;
106839   sqlite3 *db = pParse->db;
106840
106841   /* Generate loop termination code.
106842   */
106843   sqlite3ExprCacheClear(pParse);
106844   for(i=pWInfo->nLevel-1; i>=0; i--){
106845     pLevel = &pWInfo->a[i];
106846     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
106847     if( pLevel->op!=OP_Noop ){
106848       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
106849       sqlite3VdbeChangeP5(v, pLevel->p5);
106850     }
106851     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
106852       struct InLoop *pIn;
106853       int j;
106854       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
106855       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
106856         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
106857         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
106858         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
106859       }
106860       sqlite3DbFree(db, pLevel->u.in.aInLoop);
106861     }
106862     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
106863     if( pLevel->iLeftJoin ){
106864       int addr;
106865       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
106866       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
106867            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
106868       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
106869         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
106870       }
106871       if( pLevel->iIdxCur>=0 ){
106872         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
106873       }
106874       if( pLevel->op==OP_Return ){
106875         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
106876       }else{
106877         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
106878       }
106879       sqlite3VdbeJumpHere(v, addr);
106880     }
106881   }
106882
106883   /* The "break" point is here, just past the end of the outer loop.
106884   ** Set it.
106885   */
106886   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
106887
106888   /* Close all of the cursors that were opened by sqlite3WhereBegin.
106889   */
106890   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
106891   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
106892     Index *pIdx = 0;
106893     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
106894     Table *pTab = pTabItem->pTab;
106895     assert( pTab!=0 );
106896     if( (pTab->tabFlags & TF_Ephemeral)==0
106897      && pTab->pSelect==0
106898      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
106899     ){
106900       int ws = pLevel->plan.wsFlags;
106901       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
106902         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
106903       }
106904       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
106905         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
106906       }
106907     }
106908
106909     /* If this scan uses an index, make code substitutions to read data
106910     ** from the index in preference to the table. Sometimes, this means
106911     ** the table need never be read from. This is a performance boost,
106912     ** as the vdbe level waits until the table is read before actually
106913     ** seeking the table cursor to the record corresponding to the current
106914     ** position in the index.
106915     ** 
106916     ** Calls to the code generator in between sqlite3WhereBegin and
106917     ** sqlite3WhereEnd will have created code that references the table
106918     ** directly.  This loop scans all that code looking for opcodes
106919     ** that reference the table and converts them into opcodes that
106920     ** reference the index.
106921     */
106922     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
106923       pIdx = pLevel->plan.u.pIdx;
106924     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106925       pIdx = pLevel->u.pCovidx;
106926     }
106927     if( pIdx && !db->mallocFailed){
106928       int k, j, last;
106929       VdbeOp *pOp;
106930
106931       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
106932       last = sqlite3VdbeCurrentAddr(v);
106933       for(k=pWInfo->iTop; k<last; k++, pOp++){
106934         if( pOp->p1!=pLevel->iTabCur ) continue;
106935         if( pOp->opcode==OP_Column ){
106936           for(j=0; j<pIdx->nColumn; j++){
106937             if( pOp->p2==pIdx->aiColumn[j] ){
106938               pOp->p2 = j;
106939               pOp->p1 = pLevel->iIdxCur;
106940               break;
106941             }
106942           }
106943           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
106944                || j<pIdx->nColumn );
106945         }else if( pOp->opcode==OP_Rowid ){
106946           pOp->p1 = pLevel->iIdxCur;
106947           pOp->opcode = OP_IdxRowid;
106948         }
106949       }
106950     }
106951   }
106952
106953   /* Final cleanup
106954   */
106955   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
106956   whereInfoFree(db, pWInfo);
106957   return;
106958 }
106959
106960 /************** End of where.c ***********************************************/
106961 /************** Begin file parse.c *******************************************/
106962 /* Driver template for the LEMON parser generator.
106963 ** The author disclaims copyright to this source code.
106964 **
106965 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
106966 ** The only modifications are the addition of a couple of NEVER()
106967 ** macros to disable tests that are needed in the case of a general
106968 ** LALR(1) grammar but which are always false in the
106969 ** specific grammar used by SQLite.
106970 */
106971 /* First off, code is included that follows the "include" declaration
106972 ** in the input grammar file. */
106973 /* #include <stdio.h> */
106974
106975
106976 /*
106977 ** Disable all error recovery processing in the parser push-down
106978 ** automaton.
106979 */
106980 #define YYNOERRORRECOVERY 1
106981
106982 /*
106983 ** Make yytestcase() the same as testcase()
106984 */
106985 #define yytestcase(X) testcase(X)
106986
106987 /*
106988 ** An instance of this structure holds information about the
106989 ** LIMIT clause of a SELECT statement.
106990 */
106991 struct LimitVal {
106992   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
106993   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
106994 };
106995
106996 /*
106997 ** An instance of this structure is used to store the LIKE,
106998 ** GLOB, NOT LIKE, and NOT GLOB operators.
106999 */
107000 struct LikeOp {
107001   Token eOperator;  /* "like" or "glob" or "regexp" */
107002   int bNot;         /* True if the NOT keyword is present */
107003 };
107004
107005 /*
107006 ** An instance of the following structure describes the event of a
107007 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
107008 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
107009 **
107010 **      UPDATE ON (a,b,c)
107011 **
107012 ** Then the "b" IdList records the list "a,b,c".
107013 */
107014 struct TrigEvent { int a; IdList * b; };
107015
107016 /*
107017 ** An instance of this structure holds the ATTACH key and the key type.
107018 */
107019 struct AttachKey { int type;  Token key; };
107020
107021 /*
107022 ** One or more VALUES claues
107023 */
107024 struct ValueList {
107025   ExprList *pList;
107026   Select *pSelect;
107027 };
107028
107029
107030   /* This is a utility routine used to set the ExprSpan.zStart and
107031   ** ExprSpan.zEnd values of pOut so that the span covers the complete
107032   ** range of text beginning with pStart and going to the end of pEnd.
107033   */
107034   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
107035     pOut->zStart = pStart->z;
107036     pOut->zEnd = &pEnd->z[pEnd->n];
107037   }
107038
107039   /* Construct a new Expr object from a single identifier.  Use the
107040   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
107041   ** that created the expression.
107042   */
107043   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
107044     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
107045     pOut->zStart = pValue->z;
107046     pOut->zEnd = &pValue->z[pValue->n];
107047   }
107048
107049   /* This routine constructs a binary expression node out of two ExprSpan
107050   ** objects and uses the result to populate a new ExprSpan object.
107051   */
107052   static void spanBinaryExpr(
107053     ExprSpan *pOut,     /* Write the result here */
107054     Parse *pParse,      /* The parsing context.  Errors accumulate here */
107055     int op,             /* The binary operation */
107056     ExprSpan *pLeft,    /* The left operand */
107057     ExprSpan *pRight    /* The right operand */
107058   ){
107059     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
107060     pOut->zStart = pLeft->zStart;
107061     pOut->zEnd = pRight->zEnd;
107062   }
107063
107064   /* Construct an expression node for a unary postfix operator
107065   */
107066   static void spanUnaryPostfix(
107067     ExprSpan *pOut,        /* Write the new expression node here */
107068     Parse *pParse,         /* Parsing context to record errors */
107069     int op,                /* The operator */
107070     ExprSpan *pOperand,    /* The operand */
107071     Token *pPostOp         /* The operand token for setting the span */
107072   ){
107073     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107074     pOut->zStart = pOperand->zStart;
107075     pOut->zEnd = &pPostOp->z[pPostOp->n];
107076   }                           
107077
107078   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
107079   ** unary TK_ISNULL or TK_NOTNULL expression. */
107080   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
107081     sqlite3 *db = pParse->db;
107082     if( db->mallocFailed==0 && pY->op==TK_NULL ){
107083       pA->op = (u8)op;
107084       sqlite3ExprDelete(db, pA->pRight);
107085       pA->pRight = 0;
107086     }
107087   }
107088
107089   /* Construct an expression node for a unary prefix operator
107090   */
107091   static void spanUnaryPrefix(
107092     ExprSpan *pOut,        /* Write the new expression node here */
107093     Parse *pParse,         /* Parsing context to record errors */
107094     int op,                /* The operator */
107095     ExprSpan *pOperand,    /* The operand */
107096     Token *pPreOp         /* The operand token for setting the span */
107097   ){
107098     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107099     pOut->zStart = pPreOp->z;
107100     pOut->zEnd = pOperand->zEnd;
107101   }
107102 /* Next is all token values, in a form suitable for use by makeheaders.
107103 ** This section will be null unless lemon is run with the -m switch.
107104 */
107105 /* 
107106 ** These constants (all generated automatically by the parser generator)
107107 ** specify the various kinds of tokens (terminals) that the parser
107108 ** understands. 
107109 **
107110 ** Each symbol here is a terminal symbol in the grammar.
107111 */
107112 /* Make sure the INTERFACE macro is defined.
107113 */
107114 #ifndef INTERFACE
107115 # define INTERFACE 1
107116 #endif
107117 /* The next thing included is series of defines which control
107118 ** various aspects of the generated parser.
107119 **    YYCODETYPE         is the data type used for storing terminal
107120 **                       and nonterminal numbers.  "unsigned char" is
107121 **                       used if there are fewer than 250 terminals
107122 **                       and nonterminals.  "int" is used otherwise.
107123 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
107124 **                       to no legal terminal or nonterminal number.  This
107125 **                       number is used to fill in empty slots of the hash 
107126 **                       table.
107127 **    YYFALLBACK         If defined, this indicates that one or more tokens
107128 **                       have fall-back values which should be used if the
107129 **                       original value of the token will not parse.
107130 **    YYACTIONTYPE       is the data type used for storing terminal
107131 **                       and nonterminal numbers.  "unsigned char" is
107132 **                       used if there are fewer than 250 rules and
107133 **                       states combined.  "int" is used otherwise.
107134 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
107135 **                       directly to the parser from the tokenizer.
107136 **    YYMINORTYPE        is the data type used for all minor tokens.
107137 **                       This is typically a union of many types, one of
107138 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
107139 **                       for base tokens is called "yy0".
107140 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
107141 **                       zero the stack is dynamically sized using realloc()
107142 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
107143 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
107144 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
107145 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
107146 **    YYNSTATE           the combined number of states.
107147 **    YYNRULE            the number of rules in the grammar
107148 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
107149 **                       defined, then do no error processing.
107150 */
107151 #define YYCODETYPE unsigned char
107152 #define YYNOCODE 251
107153 #define YYACTIONTYPE unsigned short int
107154 #define YYWILDCARD 67
107155 #define sqlite3ParserTOKENTYPE Token
107156 typedef union {
107157   int yyinit;
107158   sqlite3ParserTOKENTYPE yy0;
107159   struct LimitVal yy64;
107160   Expr* yy122;
107161   Select* yy159;
107162   IdList* yy180;
107163   struct {int value; int mask;} yy207;
107164   u8 yy258;
107165   struct LikeOp yy318;
107166   TriggerStep* yy327;
107167   ExprSpan yy342;
107168   SrcList* yy347;
107169   int yy392;
107170   struct TrigEvent yy410;
107171   ExprList* yy442;
107172   struct ValueList yy487;
107173 } YYMINORTYPE;
107174 #ifndef YYSTACKDEPTH
107175 #define YYSTACKDEPTH 100
107176 #endif
107177 #define sqlite3ParserARG_SDECL Parse *pParse;
107178 #define sqlite3ParserARG_PDECL ,Parse *pParse
107179 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
107180 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
107181 #define YYNSTATE 627
107182 #define YYNRULE 327
107183 #define YYFALLBACK 1
107184 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
107185 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
107186 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
107187
107188 /* The yyzerominor constant is used to initialize instances of
107189 ** YYMINORTYPE objects to zero. */
107190 static const YYMINORTYPE yyzerominor = { 0 };
107191
107192 /* Define the yytestcase() macro to be a no-op if is not already defined
107193 ** otherwise.
107194 **
107195 ** Applications can choose to define yytestcase() in the %include section
107196 ** to a macro that can assist in verifying code coverage.  For production
107197 ** code the yytestcase() macro should be turned off.  But it is useful
107198 ** for testing.
107199 */
107200 #ifndef yytestcase
107201 # define yytestcase(X)
107202 #endif
107203
107204
107205 /* Next are the tables used to determine what action to take based on the
107206 ** current state and lookahead token.  These tables are used to implement
107207 ** functions that take a state number and lookahead value and return an
107208 ** action integer.  
107209 **
107210 ** Suppose the action integer is N.  Then the action is determined as
107211 ** follows
107212 **
107213 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
107214 **                                      token onto the stack and goto state N.
107215 **
107216 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
107217 **
107218 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
107219 **
107220 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
107221 **
107222 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
107223 **                                      slots in the yy_action[] table.
107224 **
107225 ** The action table is constructed as a single large table named yy_action[].
107226 ** Given state S and lookahead X, the action is computed as
107227 **
107228 **      yy_action[ yy_shift_ofst[S] + X ]
107229 **
107230 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
107231 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
107232 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
107233 ** and that yy_default[S] should be used instead.  
107234 **
107235 ** The formula above is for computing the action when the lookahead is
107236 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
107237 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
107238 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
107239 ** YY_SHIFT_USE_DFLT.
107240 **
107241 ** The following are the tables generated in this section:
107242 **
107243 **  yy_action[]        A single table containing all actions.
107244 **  yy_lookahead[]     A table containing the lookahead for each entry in
107245 **                     yy_action.  Used to detect hash collisions.
107246 **  yy_shift_ofst[]    For each state, the offset into yy_action for
107247 **                     shifting terminals.
107248 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
107249 **                     shifting non-terminals after a reduce.
107250 **  yy_default[]       Default action for each state.
107251 */
107252 #define YY_ACTTAB_COUNT (1564)
107253 static const YYACTIONTYPE yy_action[] = {
107254  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
107255  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
107256  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
107257  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
107258  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
107259  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
107260  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
107261  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
107262  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
107263  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
107264  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
107265  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
107266  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
107267  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
107268  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
107269  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
107270  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
107271  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
107272  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
107273  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
107274  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
107275  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
107276  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
107277  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
107278  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
107279  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
107280  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
107281  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
107282  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
107283  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
107284  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
107285  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
107286  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
107287  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
107288  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
107289  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
107290  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
107291  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
107292  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
107293  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
107294  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
107295  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
107296  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
107297  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
107298  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
107299  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
107300  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
107301  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
107302  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
107303  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
107304  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
107305  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
107306  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
107307  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
107308  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
107309  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
107310  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
107311  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
107312  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
107313  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
107314  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
107315  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
107316  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
107317  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
107318  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
107319  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
107320  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
107321  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
107322  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
107323  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
107324  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
107325  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
107326  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
107327  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
107328  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
107329  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
107330  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
107331  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
107332  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
107333  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
107334  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
107335  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
107336  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
107337  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
107338  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
107339  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
107340  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
107341  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
107342  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
107343  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
107344  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
107345  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
107346  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
107347  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
107348  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
107349  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
107350  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
107351  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
107352  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
107353  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
107354  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
107355  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
107356  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
107357  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
107358  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
107359  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
107360  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
107361  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
107362  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
107363  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
107364  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
107365  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
107366  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
107367  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
107368  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
107369  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
107370  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
107371  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
107372  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
107373  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
107374  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
107375  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
107376  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
107377  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
107378  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
107379  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
107380  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
107381  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
107382  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
107383  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
107384  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
107385  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
107386  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
107387  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
107388  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
107389  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
107390  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
107391  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
107392  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
107393  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
107394  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
107395  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
107396  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
107397  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
107398  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
107399  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
107400  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
107401  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
107402  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
107403  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
107404  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
107405  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
107406  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
107407  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
107408  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
107409  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
107410  /*  1560 */   295,  498,  956,  488,
107411 };
107412 static const YYCODETYPE yy_lookahead[] = {
107413  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
107414  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
107415  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
107416  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
107417  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
107418  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107419  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
107420  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
107421  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107422  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
107423  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
107424  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
107425  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
107426  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
107427  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
107428  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
107429  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
107430  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
107431  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
107432  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
107433  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107434  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107435  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
107436  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
107437  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
107438  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
107439  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
107440  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107441  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
107442  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
107443  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
107444  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
107445  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
107446  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
107447  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
107448  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
107449  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107450  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
107451  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
107452  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
107453  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
107454  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
107455  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107456  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
107457  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
107458  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
107459  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
107460  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
107461  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
107462  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
107463  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
107464  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
107465  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
107466  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
107467  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
107468  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
107469  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
107470  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107471  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107472  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
107473  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
107474  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
107475  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
107476  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
107477  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107478  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
107479  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
107480  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
107481  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
107482  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
107483  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
107484  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
107485  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
107486  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107487  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
107488  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
107489  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
107490  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
107491  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
107492  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107493  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
107494  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
107495  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
107496  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
107497  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
107498  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
107499  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
107500  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
107501  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
107502  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
107503  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
107504  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
107505  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
107506  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
107507  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107508  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107509  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
107510  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
107511  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
107512  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
107513  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
107514  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107515  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
107516  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
107517  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
107518  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
107519  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
107520  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
107521  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
107522  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
107523  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107524  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
107525  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
107526  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
107527  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
107528  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
107529  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107530  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
107531  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
107532  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
107533  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
107534  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
107535  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
107536  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
107537  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
107538  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
107539  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
107540  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
107541  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
107542  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
107543  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
107544  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
107545  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
107546  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
107547  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
107548  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
107549  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
107550  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
107551  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
107552  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
107553  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
107554  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
107555  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
107556  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
107557  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
107558  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
107559  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
107560  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
107561  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
107562  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
107563  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
107564  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
107565  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
107566  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
107567  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
107568  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
107569  /*  1560 */   195,  182,  250,  186,
107570 };
107571 #define YY_SHIFT_USE_DFLT (-70)
107572 #define YY_SHIFT_COUNT (416)
107573 #define YY_SHIFT_MIN   (-69)
107574 #define YY_SHIFT_MAX   (1487)
107575 static const short yy_shift_ofst[] = {
107576  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
107577  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
107578  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
107579  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
107580  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
107581  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
107582  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
107583  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
107584  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
107585  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
107586  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
107587  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
107588  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
107589  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
107590  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
107591  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
107592  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
107593  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
107594  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
107595  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
107596  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
107597  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
107598  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
107599  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
107600  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
107601  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
107602  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
107603  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
107604  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
107605  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
107606  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
107607  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
107608  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
107609  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
107610  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
107611  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
107612  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
107613  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
107614  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
107615  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
107616  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
107617  /*   410 */    92,   75,   45,  114,   25,   11,    5,
107618 };
107619 #define YY_REDUCE_USE_DFLT (-169)
107620 #define YY_REDUCE_COUNT (308)
107621 #define YY_REDUCE_MIN   (-168)
107622 #define YY_REDUCE_MAX   (1391)
107623 static const short yy_reduce_ofst[] = {
107624  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
107625  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
107626  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
107627  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
107628  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
107629  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
107630  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
107631  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
107632  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
107633  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
107634  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
107635  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
107636  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
107637  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
107638  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
107639  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
107640  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
107641  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
107642  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
107643  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
107644  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
107645  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
107646  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
107647  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
107648  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
107649  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
107650  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
107651  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
107652  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
107653  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
107654  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
107655 };
107656 static const YYACTIONTYPE yy_default[] = {
107657  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
107658  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
107659  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107660  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107661  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107662  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107663  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
107664  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
107665  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
107666  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
107667  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
107668  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107669  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
107670  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
107671  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107672  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
107673  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107674  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107675  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
107676  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107677  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
107678  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
107679  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
107680  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
107681  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
107682  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
107683  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
107684  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
107685  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
107686  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
107687  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
107688  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
107689  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
107690  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
107691  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
107692  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
107693  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
107694  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107695  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
107696  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
107697  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
107698  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
107699  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
107700  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
107701  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
107702  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
107703  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
107704  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
107705  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
107706  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
107707  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
107708  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
107709  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
107710  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
107711  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
107712  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
107713  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
107714  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
107715  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
107716  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
107717  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
107718  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
107719  /*   620 */   665,  639,  636,  635,  631,  630,  628,
107720 };
107721
107722 /* The next table maps tokens into fallback tokens.  If a construct
107723 ** like the following:
107724 ** 
107725 **      %fallback ID X Y Z.
107726 **
107727 ** appears in the grammar, then ID becomes a fallback token for X, Y,
107728 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
107729 ** but it does not parse, the type of the token is changed to ID and
107730 ** the parse is retried before an error is thrown.
107731 */
107732 #ifdef YYFALLBACK
107733 static const YYCODETYPE yyFallback[] = {
107734     0,  /*          $ => nothing */
107735     0,  /*       SEMI => nothing */
107736    26,  /*    EXPLAIN => ID */
107737    26,  /*      QUERY => ID */
107738    26,  /*       PLAN => ID */
107739    26,  /*      BEGIN => ID */
107740     0,  /* TRANSACTION => nothing */
107741    26,  /*   DEFERRED => ID */
107742    26,  /*  IMMEDIATE => ID */
107743    26,  /*  EXCLUSIVE => ID */
107744     0,  /*     COMMIT => nothing */
107745    26,  /*        END => ID */
107746    26,  /*   ROLLBACK => ID */
107747    26,  /*  SAVEPOINT => ID */
107748    26,  /*    RELEASE => ID */
107749     0,  /*         TO => nothing */
107750     0,  /*      TABLE => nothing */
107751     0,  /*     CREATE => nothing */
107752    26,  /*         IF => ID */
107753     0,  /*        NOT => nothing */
107754     0,  /*     EXISTS => nothing */
107755    26,  /*       TEMP => ID */
107756     0,  /*         LP => nothing */
107757     0,  /*         RP => nothing */
107758     0,  /*         AS => nothing */
107759     0,  /*      COMMA => nothing */
107760     0,  /*         ID => nothing */
107761     0,  /*    INDEXED => nothing */
107762    26,  /*      ABORT => ID */
107763    26,  /*     ACTION => ID */
107764    26,  /*      AFTER => ID */
107765    26,  /*    ANALYZE => ID */
107766    26,  /*        ASC => ID */
107767    26,  /*     ATTACH => ID */
107768    26,  /*     BEFORE => ID */
107769    26,  /*         BY => ID */
107770    26,  /*    CASCADE => ID */
107771    26,  /*       CAST => ID */
107772    26,  /*   COLUMNKW => ID */
107773    26,  /*   CONFLICT => ID */
107774    26,  /*   DATABASE => ID */
107775    26,  /*       DESC => ID */
107776    26,  /*     DETACH => ID */
107777    26,  /*       EACH => ID */
107778    26,  /*       FAIL => ID */
107779    26,  /*        FOR => ID */
107780    26,  /*     IGNORE => ID */
107781    26,  /*  INITIALLY => ID */
107782    26,  /*    INSTEAD => ID */
107783    26,  /*    LIKE_KW => ID */
107784    26,  /*      MATCH => ID */
107785    26,  /*         NO => ID */
107786    26,  /*        KEY => ID */
107787    26,  /*         OF => ID */
107788    26,  /*     OFFSET => ID */
107789    26,  /*     PRAGMA => ID */
107790    26,  /*      RAISE => ID */
107791    26,  /*    REPLACE => ID */
107792    26,  /*   RESTRICT => ID */
107793    26,  /*        ROW => ID */
107794    26,  /*    TRIGGER => ID */
107795    26,  /*     VACUUM => ID */
107796    26,  /*       VIEW => ID */
107797    26,  /*    VIRTUAL => ID */
107798    26,  /*    REINDEX => ID */
107799    26,  /*     RENAME => ID */
107800    26,  /*   CTIME_KW => ID */
107801 };
107802 #endif /* YYFALLBACK */
107803
107804 /* The following structure represents a single element of the
107805 ** parser's stack.  Information stored includes:
107806 **
107807 **   +  The state number for the parser at this level of the stack.
107808 **
107809 **   +  The value of the token stored at this level of the stack.
107810 **      (In other words, the "major" token.)
107811 **
107812 **   +  The semantic value stored at this level of the stack.  This is
107813 **      the information used by the action routines in the grammar.
107814 **      It is sometimes called the "minor" token.
107815 */
107816 struct yyStackEntry {
107817   YYACTIONTYPE stateno;  /* The state-number */
107818   YYCODETYPE major;      /* The major token value.  This is the code
107819                          ** number for the token at this stack level */
107820   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
107821                          ** is the value of the token  */
107822 };
107823 typedef struct yyStackEntry yyStackEntry;
107824
107825 /* The state of the parser is completely contained in an instance of
107826 ** the following structure */
107827 struct yyParser {
107828   int yyidx;                    /* Index of top element in stack */
107829 #ifdef YYTRACKMAXSTACKDEPTH
107830   int yyidxMax;                 /* Maximum value of yyidx */
107831 #endif
107832   int yyerrcnt;                 /* Shifts left before out of the error */
107833   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
107834 #if YYSTACKDEPTH<=0
107835   int yystksz;                  /* Current side of the stack */
107836   yyStackEntry *yystack;        /* The parser's stack */
107837 #else
107838   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
107839 #endif
107840 };
107841 typedef struct yyParser yyParser;
107842
107843 #ifndef NDEBUG
107844 /* #include <stdio.h> */
107845 static FILE *yyTraceFILE = 0;
107846 static char *yyTracePrompt = 0;
107847 #endif /* NDEBUG */
107848
107849 #ifndef NDEBUG
107850 /* 
107851 ** Turn parser tracing on by giving a stream to which to write the trace
107852 ** and a prompt to preface each trace message.  Tracing is turned off
107853 ** by making either argument NULL 
107854 **
107855 ** Inputs:
107856 ** <ul>
107857 ** <li> A FILE* to which trace output should be written.
107858 **      If NULL, then tracing is turned off.
107859 ** <li> A prefix string written at the beginning of every
107860 **      line of trace output.  If NULL, then tracing is
107861 **      turned off.
107862 ** </ul>
107863 **
107864 ** Outputs:
107865 ** None.
107866 */
107867 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
107868   yyTraceFILE = TraceFILE;
107869   yyTracePrompt = zTracePrompt;
107870   if( yyTraceFILE==0 ) yyTracePrompt = 0;
107871   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
107872 }
107873 #endif /* NDEBUG */
107874
107875 #ifndef NDEBUG
107876 /* For tracing shifts, the names of all terminals and nonterminals
107877 ** are required.  The following table supplies these names */
107878 static const char *const yyTokenName[] = { 
107879   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
107880   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
107881   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
107882   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
107883   "TABLE",         "CREATE",        "IF",            "NOT",         
107884   "EXISTS",        "TEMP",          "LP",            "RP",          
107885   "AS",            "COMMA",         "ID",            "INDEXED",     
107886   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
107887   "ASC",           "ATTACH",        "BEFORE",        "BY",          
107888   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
107889   "DATABASE",      "DESC",          "DETACH",        "EACH",        
107890   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
107891   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
107892   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
107893   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
107894   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
107895   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
107896   "OR",            "AND",           "IS",            "BETWEEN",     
107897   "IN",            "ISNULL",        "NOTNULL",       "NE",          
107898   "EQ",            "GT",            "LE",            "LT",          
107899   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
107900   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
107901   "STAR",          "SLASH",         "REM",           "CONCAT",      
107902   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
107903   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
107904   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
107905   "ON",            "INSERT",        "DELETE",        "UPDATE",      
107906   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
107907   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
107908   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
107909   "JOIN",          "USING",         "ORDER",         "GROUP",       
107910   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
107911   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
107912   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
107913   "THEN",          "ELSE",          "INDEX",         "ALTER",       
107914   "ADD",           "error",         "input",         "cmdlist",     
107915   "ecmd",          "explain",       "cmdx",          "cmd",         
107916   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
107917   "create_table",  "create_table_args",  "createkw",      "temp",        
107918   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
107919   "select",        "column",        "columnid",      "type",        
107920   "carglist",      "id",            "ids",           "typetoken",   
107921   "typename",      "signed",        "plus_num",      "minus_num",   
107922   "ccons",         "term",          "expr",          "onconf",      
107923   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
107924   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
107925   "conslist",      "tconscomma",    "tcons",         "idxlist",     
107926   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
107927   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
107928   "distinct",      "selcollist",    "from",          "where_opt",   
107929   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
107930   "sclp",          "as",            "seltablist",    "stl_prefix",  
107931   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
107932   "joinop2",       "inscollist",    "sortlist",      "nexprlist",   
107933   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",   
107934   "exprlist",      "likeop",        "between_op",    "in_op",       
107935   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",  
107936   "collate",       "nmnum",         "number",        "trigger_decl",
107937   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
107938   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
107939   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
107940   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
107941   "lp",            "anylist",     
107942 };
107943 #endif /* NDEBUG */
107944
107945 #ifndef NDEBUG
107946 /* For tracing reduce actions, the names of all rules are required.
107947 */
107948 static const char *const yyRuleName[] = {
107949  /*   0 */ "input ::= cmdlist",
107950  /*   1 */ "cmdlist ::= cmdlist ecmd",
107951  /*   2 */ "cmdlist ::= ecmd",
107952  /*   3 */ "ecmd ::= SEMI",
107953  /*   4 */ "ecmd ::= explain cmdx SEMI",
107954  /*   5 */ "explain ::=",
107955  /*   6 */ "explain ::= EXPLAIN",
107956  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
107957  /*   8 */ "cmdx ::= cmd",
107958  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
107959  /*  10 */ "trans_opt ::=",
107960  /*  11 */ "trans_opt ::= TRANSACTION",
107961  /*  12 */ "trans_opt ::= TRANSACTION nm",
107962  /*  13 */ "transtype ::=",
107963  /*  14 */ "transtype ::= DEFERRED",
107964  /*  15 */ "transtype ::= IMMEDIATE",
107965  /*  16 */ "transtype ::= EXCLUSIVE",
107966  /*  17 */ "cmd ::= COMMIT trans_opt",
107967  /*  18 */ "cmd ::= END trans_opt",
107968  /*  19 */ "cmd ::= ROLLBACK trans_opt",
107969  /*  20 */ "savepoint_opt ::= SAVEPOINT",
107970  /*  21 */ "savepoint_opt ::=",
107971  /*  22 */ "cmd ::= SAVEPOINT nm",
107972  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
107973  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
107974  /*  25 */ "cmd ::= create_table create_table_args",
107975  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
107976  /*  27 */ "createkw ::= CREATE",
107977  /*  28 */ "ifnotexists ::=",
107978  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
107979  /*  30 */ "temp ::= TEMP",
107980  /*  31 */ "temp ::=",
107981  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
107982  /*  33 */ "create_table_args ::= AS select",
107983  /*  34 */ "columnlist ::= columnlist COMMA column",
107984  /*  35 */ "columnlist ::= column",
107985  /*  36 */ "column ::= columnid type carglist",
107986  /*  37 */ "columnid ::= nm",
107987  /*  38 */ "id ::= ID",
107988  /*  39 */ "id ::= INDEXED",
107989  /*  40 */ "ids ::= ID|STRING",
107990  /*  41 */ "nm ::= id",
107991  /*  42 */ "nm ::= STRING",
107992  /*  43 */ "nm ::= JOIN_KW",
107993  /*  44 */ "type ::=",
107994  /*  45 */ "type ::= typetoken",
107995  /*  46 */ "typetoken ::= typename",
107996  /*  47 */ "typetoken ::= typename LP signed RP",
107997  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
107998  /*  49 */ "typename ::= ids",
107999  /*  50 */ "typename ::= typename ids",
108000  /*  51 */ "signed ::= plus_num",
108001  /*  52 */ "signed ::= minus_num",
108002  /*  53 */ "carglist ::= carglist ccons",
108003  /*  54 */ "carglist ::=",
108004  /*  55 */ "ccons ::= CONSTRAINT nm",
108005  /*  56 */ "ccons ::= DEFAULT term",
108006  /*  57 */ "ccons ::= DEFAULT LP expr RP",
108007  /*  58 */ "ccons ::= DEFAULT PLUS term",
108008  /*  59 */ "ccons ::= DEFAULT MINUS term",
108009  /*  60 */ "ccons ::= DEFAULT id",
108010  /*  61 */ "ccons ::= NULL onconf",
108011  /*  62 */ "ccons ::= NOT NULL onconf",
108012  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
108013  /*  64 */ "ccons ::= UNIQUE onconf",
108014  /*  65 */ "ccons ::= CHECK LP expr RP",
108015  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
108016  /*  67 */ "ccons ::= defer_subclause",
108017  /*  68 */ "ccons ::= COLLATE ids",
108018  /*  69 */ "autoinc ::=",
108019  /*  70 */ "autoinc ::= AUTOINCR",
108020  /*  71 */ "refargs ::=",
108021  /*  72 */ "refargs ::= refargs refarg",
108022  /*  73 */ "refarg ::= MATCH nm",
108023  /*  74 */ "refarg ::= ON INSERT refact",
108024  /*  75 */ "refarg ::= ON DELETE refact",
108025  /*  76 */ "refarg ::= ON UPDATE refact",
108026  /*  77 */ "refact ::= SET NULL",
108027  /*  78 */ "refact ::= SET DEFAULT",
108028  /*  79 */ "refact ::= CASCADE",
108029  /*  80 */ "refact ::= RESTRICT",
108030  /*  81 */ "refact ::= NO ACTION",
108031  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
108032  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
108033  /*  84 */ "init_deferred_pred_opt ::=",
108034  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
108035  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
108036  /*  87 */ "conslist_opt ::=",
108037  /*  88 */ "conslist_opt ::= COMMA conslist",
108038  /*  89 */ "conslist ::= conslist tconscomma tcons",
108039  /*  90 */ "conslist ::= tcons",
108040  /*  91 */ "tconscomma ::= COMMA",
108041  /*  92 */ "tconscomma ::=",
108042  /*  93 */ "tcons ::= CONSTRAINT nm",
108043  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
108044  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
108045  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
108046  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
108047  /*  98 */ "defer_subclause_opt ::=",
108048  /*  99 */ "defer_subclause_opt ::= defer_subclause",
108049  /* 100 */ "onconf ::=",
108050  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
108051  /* 102 */ "orconf ::=",
108052  /* 103 */ "orconf ::= OR resolvetype",
108053  /* 104 */ "resolvetype ::= raisetype",
108054  /* 105 */ "resolvetype ::= IGNORE",
108055  /* 106 */ "resolvetype ::= REPLACE",
108056  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
108057  /* 108 */ "ifexists ::= IF EXISTS",
108058  /* 109 */ "ifexists ::=",
108059  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
108060  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
108061  /* 112 */ "cmd ::= select",
108062  /* 113 */ "select ::= oneselect",
108063  /* 114 */ "select ::= select multiselect_op oneselect",
108064  /* 115 */ "multiselect_op ::= UNION",
108065  /* 116 */ "multiselect_op ::= UNION ALL",
108066  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
108067  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
108068  /* 119 */ "distinct ::= DISTINCT",
108069  /* 120 */ "distinct ::= ALL",
108070  /* 121 */ "distinct ::=",
108071  /* 122 */ "sclp ::= selcollist COMMA",
108072  /* 123 */ "sclp ::=",
108073  /* 124 */ "selcollist ::= sclp expr as",
108074  /* 125 */ "selcollist ::= sclp STAR",
108075  /* 126 */ "selcollist ::= sclp nm DOT STAR",
108076  /* 127 */ "as ::= AS nm",
108077  /* 128 */ "as ::= ids",
108078  /* 129 */ "as ::=",
108079  /* 130 */ "from ::=",
108080  /* 131 */ "from ::= FROM seltablist",
108081  /* 132 */ "stl_prefix ::= seltablist joinop",
108082  /* 133 */ "stl_prefix ::=",
108083  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
108084  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
108085  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
108086  /* 137 */ "dbnm ::=",
108087  /* 138 */ "dbnm ::= DOT nm",
108088  /* 139 */ "fullname ::= nm dbnm",
108089  /* 140 */ "joinop ::= COMMA|JOIN",
108090  /* 141 */ "joinop ::= JOIN_KW JOIN",
108091  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
108092  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
108093  /* 144 */ "on_opt ::= ON expr",
108094  /* 145 */ "on_opt ::=",
108095  /* 146 */ "indexed_opt ::=",
108096  /* 147 */ "indexed_opt ::= INDEXED BY nm",
108097  /* 148 */ "indexed_opt ::= NOT INDEXED",
108098  /* 149 */ "using_opt ::= USING LP inscollist RP",
108099  /* 150 */ "using_opt ::=",
108100  /* 151 */ "orderby_opt ::=",
108101  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
108102  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
108103  /* 154 */ "sortlist ::= expr sortorder",
108104  /* 155 */ "sortorder ::= ASC",
108105  /* 156 */ "sortorder ::= DESC",
108106  /* 157 */ "sortorder ::=",
108107  /* 158 */ "groupby_opt ::=",
108108  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
108109  /* 160 */ "having_opt ::=",
108110  /* 161 */ "having_opt ::= HAVING expr",
108111  /* 162 */ "limit_opt ::=",
108112  /* 163 */ "limit_opt ::= LIMIT expr",
108113  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
108114  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
108115  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
108116  /* 167 */ "where_opt ::=",
108117  /* 168 */ "where_opt ::= WHERE expr",
108118  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
108119  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
108120  /* 171 */ "setlist ::= nm EQ expr",
108121  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
108122  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
108123  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
108124  /* 175 */ "insert_cmd ::= INSERT orconf",
108125  /* 176 */ "insert_cmd ::= REPLACE",
108126  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
108127  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
108128  /* 179 */ "inscollist_opt ::=",
108129  /* 180 */ "inscollist_opt ::= LP inscollist RP",
108130  /* 181 */ "inscollist ::= inscollist COMMA nm",
108131  /* 182 */ "inscollist ::= nm",
108132  /* 183 */ "expr ::= term",
108133  /* 184 */ "expr ::= LP expr RP",
108134  /* 185 */ "term ::= NULL",
108135  /* 186 */ "expr ::= id",
108136  /* 187 */ "expr ::= JOIN_KW",
108137  /* 188 */ "expr ::= nm DOT nm",
108138  /* 189 */ "expr ::= nm DOT nm DOT nm",
108139  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
108140  /* 191 */ "term ::= STRING",
108141  /* 192 */ "expr ::= REGISTER",
108142  /* 193 */ "expr ::= VARIABLE",
108143  /* 194 */ "expr ::= expr COLLATE ids",
108144  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
108145  /* 196 */ "expr ::= ID LP distinct exprlist RP",
108146  /* 197 */ "expr ::= ID LP STAR RP",
108147  /* 198 */ "term ::= CTIME_KW",
108148  /* 199 */ "expr ::= expr AND expr",
108149  /* 200 */ "expr ::= expr OR expr",
108150  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
108151  /* 202 */ "expr ::= expr EQ|NE expr",
108152  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
108153  /* 204 */ "expr ::= expr PLUS|MINUS expr",
108154  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
108155  /* 206 */ "expr ::= expr CONCAT expr",
108156  /* 207 */ "likeop ::= LIKE_KW",
108157  /* 208 */ "likeop ::= NOT LIKE_KW",
108158  /* 209 */ "likeop ::= MATCH",
108159  /* 210 */ "likeop ::= NOT MATCH",
108160  /* 211 */ "expr ::= expr likeop expr",
108161  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
108162  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
108163  /* 214 */ "expr ::= expr NOT NULL",
108164  /* 215 */ "expr ::= expr IS expr",
108165  /* 216 */ "expr ::= expr IS NOT expr",
108166  /* 217 */ "expr ::= NOT expr",
108167  /* 218 */ "expr ::= BITNOT expr",
108168  /* 219 */ "expr ::= MINUS expr",
108169  /* 220 */ "expr ::= PLUS expr",
108170  /* 221 */ "between_op ::= BETWEEN",
108171  /* 222 */ "between_op ::= NOT BETWEEN",
108172  /* 223 */ "expr ::= expr between_op expr AND expr",
108173  /* 224 */ "in_op ::= IN",
108174  /* 225 */ "in_op ::= NOT IN",
108175  /* 226 */ "expr ::= expr in_op LP exprlist RP",
108176  /* 227 */ "expr ::= LP select RP",
108177  /* 228 */ "expr ::= expr in_op LP select RP",
108178  /* 229 */ "expr ::= expr in_op nm dbnm",
108179  /* 230 */ "expr ::= EXISTS LP select RP",
108180  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
108181  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
108182  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
108183  /* 234 */ "case_else ::= ELSE expr",
108184  /* 235 */ "case_else ::=",
108185  /* 236 */ "case_operand ::= expr",
108186  /* 237 */ "case_operand ::=",
108187  /* 238 */ "exprlist ::= nexprlist",
108188  /* 239 */ "exprlist ::=",
108189  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
108190  /* 241 */ "nexprlist ::= expr",
108191  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
108192  /* 243 */ "uniqueflag ::= UNIQUE",
108193  /* 244 */ "uniqueflag ::=",
108194  /* 245 */ "idxlist_opt ::=",
108195  /* 246 */ "idxlist_opt ::= LP idxlist RP",
108196  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
108197  /* 248 */ "idxlist ::= nm collate sortorder",
108198  /* 249 */ "collate ::=",
108199  /* 250 */ "collate ::= COLLATE ids",
108200  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
108201  /* 252 */ "cmd ::= VACUUM",
108202  /* 253 */ "cmd ::= VACUUM nm",
108203  /* 254 */ "cmd ::= PRAGMA nm dbnm",
108204  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
108205  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
108206  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
108207  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
108208  /* 259 */ "nmnum ::= plus_num",
108209  /* 260 */ "nmnum ::= nm",
108210  /* 261 */ "nmnum ::= ON",
108211  /* 262 */ "nmnum ::= DELETE",
108212  /* 263 */ "nmnum ::= DEFAULT",
108213  /* 264 */ "plus_num ::= PLUS number",
108214  /* 265 */ "plus_num ::= number",
108215  /* 266 */ "minus_num ::= MINUS number",
108216  /* 267 */ "number ::= INTEGER|FLOAT",
108217  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
108218  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
108219  /* 270 */ "trigger_time ::= BEFORE",
108220  /* 271 */ "trigger_time ::= AFTER",
108221  /* 272 */ "trigger_time ::= INSTEAD OF",
108222  /* 273 */ "trigger_time ::=",
108223  /* 274 */ "trigger_event ::= DELETE|INSERT",
108224  /* 275 */ "trigger_event ::= UPDATE",
108225  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
108226  /* 277 */ "foreach_clause ::=",
108227  /* 278 */ "foreach_clause ::= FOR EACH ROW",
108228  /* 279 */ "when_clause ::=",
108229  /* 280 */ "when_clause ::= WHEN expr",
108230  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
108231  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
108232  /* 283 */ "trnm ::= nm",
108233  /* 284 */ "trnm ::= nm DOT nm",
108234  /* 285 */ "tridxby ::=",
108235  /* 286 */ "tridxby ::= INDEXED BY nm",
108236  /* 287 */ "tridxby ::= NOT INDEXED",
108237  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
108238  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
108239  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
108240  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
108241  /* 292 */ "trigger_cmd ::= select",
108242  /* 293 */ "expr ::= RAISE LP IGNORE RP",
108243  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
108244  /* 295 */ "raisetype ::= ROLLBACK",
108245  /* 296 */ "raisetype ::= ABORT",
108246  /* 297 */ "raisetype ::= FAIL",
108247  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
108248  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
108249  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
108250  /* 301 */ "key_opt ::=",
108251  /* 302 */ "key_opt ::= KEY expr",
108252  /* 303 */ "database_kw_opt ::= DATABASE",
108253  /* 304 */ "database_kw_opt ::=",
108254  /* 305 */ "cmd ::= REINDEX",
108255  /* 306 */ "cmd ::= REINDEX nm dbnm",
108256  /* 307 */ "cmd ::= ANALYZE",
108257  /* 308 */ "cmd ::= ANALYZE nm dbnm",
108258  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
108259  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
108260  /* 311 */ "add_column_fullname ::= fullname",
108261  /* 312 */ "kwcolumn_opt ::=",
108262  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
108263  /* 314 */ "cmd ::= create_vtab",
108264  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
108265  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
108266  /* 317 */ "vtabarglist ::= vtabarg",
108267  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
108268  /* 319 */ "vtabarg ::=",
108269  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
108270  /* 321 */ "vtabargtoken ::= ANY",
108271  /* 322 */ "vtabargtoken ::= lp anylist RP",
108272  /* 323 */ "lp ::= LP",
108273  /* 324 */ "anylist ::=",
108274  /* 325 */ "anylist ::= anylist LP anylist RP",
108275  /* 326 */ "anylist ::= anylist ANY",
108276 };
108277 #endif /* NDEBUG */
108278
108279
108280 #if YYSTACKDEPTH<=0
108281 /*
108282 ** Try to increase the size of the parser stack.
108283 */
108284 static void yyGrowStack(yyParser *p){
108285   int newSize;
108286   yyStackEntry *pNew;
108287
108288   newSize = p->yystksz*2 + 100;
108289   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
108290   if( pNew ){
108291     p->yystack = pNew;
108292     p->yystksz = newSize;
108293 #ifndef NDEBUG
108294     if( yyTraceFILE ){
108295       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
108296               yyTracePrompt, p->yystksz);
108297     }
108298 #endif
108299   }
108300 }
108301 #endif
108302
108303 /* 
108304 ** This function allocates a new parser.
108305 ** The only argument is a pointer to a function which works like
108306 ** malloc.
108307 **
108308 ** Inputs:
108309 ** A pointer to the function used to allocate memory.
108310 **
108311 ** Outputs:
108312 ** A pointer to a parser.  This pointer is used in subsequent calls
108313 ** to sqlite3Parser and sqlite3ParserFree.
108314 */
108315 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
108316   yyParser *pParser;
108317   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
108318   if( pParser ){
108319     pParser->yyidx = -1;
108320 #ifdef YYTRACKMAXSTACKDEPTH
108321     pParser->yyidxMax = 0;
108322 #endif
108323 #if YYSTACKDEPTH<=0
108324     pParser->yystack = NULL;
108325     pParser->yystksz = 0;
108326     yyGrowStack(pParser);
108327 #endif
108328   }
108329   return pParser;
108330 }
108331
108332 /* The following function deletes the value associated with a
108333 ** symbol.  The symbol can be either a terminal or nonterminal.
108334 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
108335 ** the value.
108336 */
108337 static void yy_destructor(
108338   yyParser *yypParser,    /* The parser */
108339   YYCODETYPE yymajor,     /* Type code for object to destroy */
108340   YYMINORTYPE *yypminor   /* The object to be destroyed */
108341 ){
108342   sqlite3ParserARG_FETCH;
108343   switch( yymajor ){
108344     /* Here is inserted the actions which take place when a
108345     ** terminal or non-terminal is destroyed.  This can happen
108346     ** when the symbol is popped from the stack during a
108347     ** reduce or during error processing or when a parser is 
108348     ** being destroyed before it is finished parsing.
108349     **
108350     ** Note: during a reduce, the only symbols destroyed are those
108351     ** which appear on the RHS of the rule, but which are not used
108352     ** inside the C code.
108353     */
108354     case 160: /* select */
108355     case 194: /* oneselect */
108356 {
108357 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
108358 }
108359       break;
108360     case 173: /* term */
108361     case 174: /* expr */
108362 {
108363 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
108364 }
108365       break;
108366     case 178: /* idxlist_opt */
108367     case 187: /* idxlist */
108368     case 197: /* selcollist */
108369     case 200: /* groupby_opt */
108370     case 202: /* orderby_opt */
108371     case 204: /* sclp */
108372     case 214: /* sortlist */
108373     case 215: /* nexprlist */
108374     case 216: /* setlist */
108375     case 220: /* exprlist */
108376     case 225: /* case_exprlist */
108377 {
108378 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
108379 }
108380       break;
108381     case 193: /* fullname */
108382     case 198: /* from */
108383     case 206: /* seltablist */
108384     case 207: /* stl_prefix */
108385 {
108386 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
108387 }
108388       break;
108389     case 199: /* where_opt */
108390     case 201: /* having_opt */
108391     case 210: /* on_opt */
108392     case 224: /* case_operand */
108393     case 226: /* case_else */
108394     case 236: /* when_clause */
108395     case 241: /* key_opt */
108396 {
108397 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
108398 }
108399       break;
108400     case 211: /* using_opt */
108401     case 213: /* inscollist */
108402     case 218: /* inscollist_opt */
108403 {
108404 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
108405 }
108406       break;
108407     case 219: /* valuelist */
108408 {
108409
108410   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
108411   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
108412
108413 }
108414       break;
108415     case 232: /* trigger_cmd_list */
108416     case 237: /* trigger_cmd */
108417 {
108418 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
108419 }
108420       break;
108421     case 234: /* trigger_event */
108422 {
108423 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
108424 }
108425       break;
108426     default:  break;   /* If no destructor action specified: do nothing */
108427   }
108428 }
108429
108430 /*
108431 ** Pop the parser's stack once.
108432 **
108433 ** If there is a destructor routine associated with the token which
108434 ** is popped from the stack, then call it.
108435 **
108436 ** Return the major token number for the symbol popped.
108437 */
108438 static int yy_pop_parser_stack(yyParser *pParser){
108439   YYCODETYPE yymajor;
108440   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
108441
108442   /* There is no mechanism by which the parser stack can be popped below
108443   ** empty in SQLite.  */
108444   if( NEVER(pParser->yyidx<0) ) return 0;
108445 #ifndef NDEBUG
108446   if( yyTraceFILE && pParser->yyidx>=0 ){
108447     fprintf(yyTraceFILE,"%sPopping %s\n",
108448       yyTracePrompt,
108449       yyTokenName[yytos->major]);
108450   }
108451 #endif
108452   yymajor = yytos->major;
108453   yy_destructor(pParser, yymajor, &yytos->minor);
108454   pParser->yyidx--;
108455   return yymajor;
108456 }
108457
108458 /* 
108459 ** Deallocate and destroy a parser.  Destructors are all called for
108460 ** all stack elements before shutting the parser down.
108461 **
108462 ** Inputs:
108463 ** <ul>
108464 ** <li>  A pointer to the parser.  This should be a pointer
108465 **       obtained from sqlite3ParserAlloc.
108466 ** <li>  A pointer to a function used to reclaim memory obtained
108467 **       from malloc.
108468 ** </ul>
108469 */
108470 SQLITE_PRIVATE void sqlite3ParserFree(
108471   void *p,                    /* The parser to be deleted */
108472   void (*freeProc)(void*)     /* Function used to reclaim memory */
108473 ){
108474   yyParser *pParser = (yyParser*)p;
108475   /* In SQLite, we never try to destroy a parser that was not successfully
108476   ** created in the first place. */
108477   if( NEVER(pParser==0) ) return;
108478   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
108479 #if YYSTACKDEPTH<=0
108480   free(pParser->yystack);
108481 #endif
108482   (*freeProc)((void*)pParser);
108483 }
108484
108485 /*
108486 ** Return the peak depth of the stack for a parser.
108487 */
108488 #ifdef YYTRACKMAXSTACKDEPTH
108489 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
108490   yyParser *pParser = (yyParser*)p;
108491   return pParser->yyidxMax;
108492 }
108493 #endif
108494
108495 /*
108496 ** Find the appropriate action for a parser given the terminal
108497 ** look-ahead token iLookAhead.
108498 **
108499 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108500 ** independent of the look-ahead.  If it is, return the action, otherwise
108501 ** return YY_NO_ACTION.
108502 */
108503 static int yy_find_shift_action(
108504   yyParser *pParser,        /* The parser */
108505   YYCODETYPE iLookAhead     /* The look-ahead token */
108506 ){
108507   int i;
108508   int stateno = pParser->yystack[pParser->yyidx].stateno;
108509  
108510   if( stateno>YY_SHIFT_COUNT
108511    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
108512     return yy_default[stateno];
108513   }
108514   assert( iLookAhead!=YYNOCODE );
108515   i += iLookAhead;
108516   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
108517     if( iLookAhead>0 ){
108518 #ifdef YYFALLBACK
108519       YYCODETYPE iFallback;            /* Fallback token */
108520       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
108521              && (iFallback = yyFallback[iLookAhead])!=0 ){
108522 #ifndef NDEBUG
108523         if( yyTraceFILE ){
108524           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
108525              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
108526         }
108527 #endif
108528         return yy_find_shift_action(pParser, iFallback);
108529       }
108530 #endif
108531 #ifdef YYWILDCARD
108532       {
108533         int j = i - iLookAhead + YYWILDCARD;
108534         if( 
108535 #if YY_SHIFT_MIN+YYWILDCARD<0
108536           j>=0 &&
108537 #endif
108538 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
108539           j<YY_ACTTAB_COUNT &&
108540 #endif
108541           yy_lookahead[j]==YYWILDCARD
108542         ){
108543 #ifndef NDEBUG
108544           if( yyTraceFILE ){
108545             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
108546                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
108547           }
108548 #endif /* NDEBUG */
108549           return yy_action[j];
108550         }
108551       }
108552 #endif /* YYWILDCARD */
108553     }
108554     return yy_default[stateno];
108555   }else{
108556     return yy_action[i];
108557   }
108558 }
108559
108560 /*
108561 ** Find the appropriate action for a parser given the non-terminal
108562 ** look-ahead token iLookAhead.
108563 **
108564 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108565 ** independent of the look-ahead.  If it is, return the action, otherwise
108566 ** return YY_NO_ACTION.
108567 */
108568 static int yy_find_reduce_action(
108569   int stateno,              /* Current state number */
108570   YYCODETYPE iLookAhead     /* The look-ahead token */
108571 ){
108572   int i;
108573 #ifdef YYERRORSYMBOL
108574   if( stateno>YY_REDUCE_COUNT ){
108575     return yy_default[stateno];
108576   }
108577 #else
108578   assert( stateno<=YY_REDUCE_COUNT );
108579 #endif
108580   i = yy_reduce_ofst[stateno];
108581   assert( i!=YY_REDUCE_USE_DFLT );
108582   assert( iLookAhead!=YYNOCODE );
108583   i += iLookAhead;
108584 #ifdef YYERRORSYMBOL
108585   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
108586     return yy_default[stateno];
108587   }
108588 #else
108589   assert( i>=0 && i<YY_ACTTAB_COUNT );
108590   assert( yy_lookahead[i]==iLookAhead );
108591 #endif
108592   return yy_action[i];
108593 }
108594
108595 /*
108596 ** The following routine is called if the stack overflows.
108597 */
108598 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
108599    sqlite3ParserARG_FETCH;
108600    yypParser->yyidx--;
108601 #ifndef NDEBUG
108602    if( yyTraceFILE ){
108603      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
108604    }
108605 #endif
108606    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
108607    /* Here code is inserted which will execute if the parser
108608    ** stack every overflows */
108609
108610   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
108611   sqlite3ErrorMsg(pParse, "parser stack overflow");
108612    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
108613 }
108614
108615 /*
108616 ** Perform a shift action.
108617 */
108618 static void yy_shift(
108619   yyParser *yypParser,          /* The parser to be shifted */
108620   int yyNewState,               /* The new state to shift in */
108621   int yyMajor,                  /* The major token to shift in */
108622   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
108623 ){
108624   yyStackEntry *yytos;
108625   yypParser->yyidx++;
108626 #ifdef YYTRACKMAXSTACKDEPTH
108627   if( yypParser->yyidx>yypParser->yyidxMax ){
108628     yypParser->yyidxMax = yypParser->yyidx;
108629   }
108630 #endif
108631 #if YYSTACKDEPTH>0 
108632   if( yypParser->yyidx>=YYSTACKDEPTH ){
108633     yyStackOverflow(yypParser, yypMinor);
108634     return;
108635   }
108636 #else
108637   if( yypParser->yyidx>=yypParser->yystksz ){
108638     yyGrowStack(yypParser);
108639     if( yypParser->yyidx>=yypParser->yystksz ){
108640       yyStackOverflow(yypParser, yypMinor);
108641       return;
108642     }
108643   }
108644 #endif
108645   yytos = &yypParser->yystack[yypParser->yyidx];
108646   yytos->stateno = (YYACTIONTYPE)yyNewState;
108647   yytos->major = (YYCODETYPE)yyMajor;
108648   yytos->minor = *yypMinor;
108649 #ifndef NDEBUG
108650   if( yyTraceFILE && yypParser->yyidx>0 ){
108651     int i;
108652     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
108653     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
108654     for(i=1; i<=yypParser->yyidx; i++)
108655       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
108656     fprintf(yyTraceFILE,"\n");
108657   }
108658 #endif
108659 }
108660
108661 /* The following table contains information about every rule that
108662 ** is used during the reduce.
108663 */
108664 static const struct {
108665   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
108666   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
108667 } yyRuleInfo[] = {
108668   { 142, 1 },
108669   { 143, 2 },
108670   { 143, 1 },
108671   { 144, 1 },
108672   { 144, 3 },
108673   { 145, 0 },
108674   { 145, 1 },
108675   { 145, 3 },
108676   { 146, 1 },
108677   { 147, 3 },
108678   { 149, 0 },
108679   { 149, 1 },
108680   { 149, 2 },
108681   { 148, 0 },
108682   { 148, 1 },
108683   { 148, 1 },
108684   { 148, 1 },
108685   { 147, 2 },
108686   { 147, 2 },
108687   { 147, 2 },
108688   { 151, 1 },
108689   { 151, 0 },
108690   { 147, 2 },
108691   { 147, 3 },
108692   { 147, 5 },
108693   { 147, 2 },
108694   { 152, 6 },
108695   { 154, 1 },
108696   { 156, 0 },
108697   { 156, 3 },
108698   { 155, 1 },
108699   { 155, 0 },
108700   { 153, 4 },
108701   { 153, 2 },
108702   { 158, 3 },
108703   { 158, 1 },
108704   { 161, 3 },
108705   { 162, 1 },
108706   { 165, 1 },
108707   { 165, 1 },
108708   { 166, 1 },
108709   { 150, 1 },
108710   { 150, 1 },
108711   { 150, 1 },
108712   { 163, 0 },
108713   { 163, 1 },
108714   { 167, 1 },
108715   { 167, 4 },
108716   { 167, 6 },
108717   { 168, 1 },
108718   { 168, 2 },
108719   { 169, 1 },
108720   { 169, 1 },
108721   { 164, 2 },
108722   { 164, 0 },
108723   { 172, 2 },
108724   { 172, 2 },
108725   { 172, 4 },
108726   { 172, 3 },
108727   { 172, 3 },
108728   { 172, 2 },
108729   { 172, 2 },
108730   { 172, 3 },
108731   { 172, 5 },
108732   { 172, 2 },
108733   { 172, 4 },
108734   { 172, 4 },
108735   { 172, 1 },
108736   { 172, 2 },
108737   { 177, 0 },
108738   { 177, 1 },
108739   { 179, 0 },
108740   { 179, 2 },
108741   { 181, 2 },
108742   { 181, 3 },
108743   { 181, 3 },
108744   { 181, 3 },
108745   { 182, 2 },
108746   { 182, 2 },
108747   { 182, 1 },
108748   { 182, 1 },
108749   { 182, 2 },
108750   { 180, 3 },
108751   { 180, 2 },
108752   { 183, 0 },
108753   { 183, 2 },
108754   { 183, 2 },
108755   { 159, 0 },
108756   { 159, 2 },
108757   { 184, 3 },
108758   { 184, 1 },
108759   { 185, 1 },
108760   { 185, 0 },
108761   { 186, 2 },
108762   { 186, 7 },
108763   { 186, 5 },
108764   { 186, 5 },
108765   { 186, 10 },
108766   { 188, 0 },
108767   { 188, 1 },
108768   { 175, 0 },
108769   { 175, 3 },
108770   { 189, 0 },
108771   { 189, 2 },
108772   { 190, 1 },
108773   { 190, 1 },
108774   { 190, 1 },
108775   { 147, 4 },
108776   { 192, 2 },
108777   { 192, 0 },
108778   { 147, 8 },
108779   { 147, 4 },
108780   { 147, 1 },
108781   { 160, 1 },
108782   { 160, 3 },
108783   { 195, 1 },
108784   { 195, 2 },
108785   { 195, 1 },
108786   { 194, 9 },
108787   { 196, 1 },
108788   { 196, 1 },
108789   { 196, 0 },
108790   { 204, 2 },
108791   { 204, 0 },
108792   { 197, 3 },
108793   { 197, 2 },
108794   { 197, 4 },
108795   { 205, 2 },
108796   { 205, 1 },
108797   { 205, 0 },
108798   { 198, 0 },
108799   { 198, 2 },
108800   { 207, 2 },
108801   { 207, 0 },
108802   { 206, 7 },
108803   { 206, 7 },
108804   { 206, 7 },
108805   { 157, 0 },
108806   { 157, 2 },
108807   { 193, 2 },
108808   { 208, 1 },
108809   { 208, 2 },
108810   { 208, 3 },
108811   { 208, 4 },
108812   { 210, 2 },
108813   { 210, 0 },
108814   { 209, 0 },
108815   { 209, 3 },
108816   { 209, 2 },
108817   { 211, 4 },
108818   { 211, 0 },
108819   { 202, 0 },
108820   { 202, 3 },
108821   { 214, 4 },
108822   { 214, 2 },
108823   { 176, 1 },
108824   { 176, 1 },
108825   { 176, 0 },
108826   { 200, 0 },
108827   { 200, 3 },
108828   { 201, 0 },
108829   { 201, 2 },
108830   { 203, 0 },
108831   { 203, 2 },
108832   { 203, 4 },
108833   { 203, 4 },
108834   { 147, 5 },
108835   { 199, 0 },
108836   { 199, 2 },
108837   { 147, 7 },
108838   { 216, 5 },
108839   { 216, 3 },
108840   { 147, 5 },
108841   { 147, 5 },
108842   { 147, 6 },
108843   { 217, 2 },
108844   { 217, 1 },
108845   { 219, 4 },
108846   { 219, 5 },
108847   { 218, 0 },
108848   { 218, 3 },
108849   { 213, 3 },
108850   { 213, 1 },
108851   { 174, 1 },
108852   { 174, 3 },
108853   { 173, 1 },
108854   { 174, 1 },
108855   { 174, 1 },
108856   { 174, 3 },
108857   { 174, 5 },
108858   { 173, 1 },
108859   { 173, 1 },
108860   { 174, 1 },
108861   { 174, 1 },
108862   { 174, 3 },
108863   { 174, 6 },
108864   { 174, 5 },
108865   { 174, 4 },
108866   { 173, 1 },
108867   { 174, 3 },
108868   { 174, 3 },
108869   { 174, 3 },
108870   { 174, 3 },
108871   { 174, 3 },
108872   { 174, 3 },
108873   { 174, 3 },
108874   { 174, 3 },
108875   { 221, 1 },
108876   { 221, 2 },
108877   { 221, 1 },
108878   { 221, 2 },
108879   { 174, 3 },
108880   { 174, 5 },
108881   { 174, 2 },
108882   { 174, 3 },
108883   { 174, 3 },
108884   { 174, 4 },
108885   { 174, 2 },
108886   { 174, 2 },
108887   { 174, 2 },
108888   { 174, 2 },
108889   { 222, 1 },
108890   { 222, 2 },
108891   { 174, 5 },
108892   { 223, 1 },
108893   { 223, 2 },
108894   { 174, 5 },
108895   { 174, 3 },
108896   { 174, 5 },
108897   { 174, 4 },
108898   { 174, 4 },
108899   { 174, 5 },
108900   { 225, 5 },
108901   { 225, 4 },
108902   { 226, 2 },
108903   { 226, 0 },
108904   { 224, 1 },
108905   { 224, 0 },
108906   { 220, 1 },
108907   { 220, 0 },
108908   { 215, 3 },
108909   { 215, 1 },
108910   { 147, 11 },
108911   { 227, 1 },
108912   { 227, 0 },
108913   { 178, 0 },
108914   { 178, 3 },
108915   { 187, 5 },
108916   { 187, 3 },
108917   { 228, 0 },
108918   { 228, 2 },
108919   { 147, 4 },
108920   { 147, 1 },
108921   { 147, 2 },
108922   { 147, 3 },
108923   { 147, 5 },
108924   { 147, 6 },
108925   { 147, 5 },
108926   { 147, 6 },
108927   { 229, 1 },
108928   { 229, 1 },
108929   { 229, 1 },
108930   { 229, 1 },
108931   { 229, 1 },
108932   { 170, 2 },
108933   { 170, 1 },
108934   { 171, 2 },
108935   { 230, 1 },
108936   { 147, 5 },
108937   { 231, 11 },
108938   { 233, 1 },
108939   { 233, 1 },
108940   { 233, 2 },
108941   { 233, 0 },
108942   { 234, 1 },
108943   { 234, 1 },
108944   { 234, 3 },
108945   { 235, 0 },
108946   { 235, 3 },
108947   { 236, 0 },
108948   { 236, 2 },
108949   { 232, 3 },
108950   { 232, 2 },
108951   { 238, 1 },
108952   { 238, 3 },
108953   { 239, 0 },
108954   { 239, 3 },
108955   { 239, 2 },
108956   { 237, 7 },
108957   { 237, 5 },
108958   { 237, 5 },
108959   { 237, 5 },
108960   { 237, 1 },
108961   { 174, 4 },
108962   { 174, 6 },
108963   { 191, 1 },
108964   { 191, 1 },
108965   { 191, 1 },
108966   { 147, 4 },
108967   { 147, 6 },
108968   { 147, 3 },
108969   { 241, 0 },
108970   { 241, 2 },
108971   { 240, 1 },
108972   { 240, 0 },
108973   { 147, 1 },
108974   { 147, 3 },
108975   { 147, 1 },
108976   { 147, 3 },
108977   { 147, 6 },
108978   { 147, 6 },
108979   { 242, 1 },
108980   { 243, 0 },
108981   { 243, 1 },
108982   { 147, 1 },
108983   { 147, 4 },
108984   { 244, 8 },
108985   { 245, 1 },
108986   { 245, 3 },
108987   { 246, 0 },
108988   { 246, 2 },
108989   { 247, 1 },
108990   { 247, 3 },
108991   { 248, 1 },
108992   { 249, 0 },
108993   { 249, 4 },
108994   { 249, 2 },
108995 };
108996
108997 static void yy_accept(yyParser*);  /* Forward Declaration */
108998
108999 /*
109000 ** Perform a reduce action and the shift that must immediately
109001 ** follow the reduce.
109002 */
109003 static void yy_reduce(
109004   yyParser *yypParser,         /* The parser */
109005   int yyruleno                 /* Number of the rule by which to reduce */
109006 ){
109007   int yygoto;                     /* The next state */
109008   int yyact;                      /* The next action */
109009   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
109010   yyStackEntry *yymsp;            /* The top of the parser's stack */
109011   int yysize;                     /* Amount to pop the stack */
109012   sqlite3ParserARG_FETCH;
109013   yymsp = &yypParser->yystack[yypParser->yyidx];
109014 #ifndef NDEBUG
109015   if( yyTraceFILE && yyruleno>=0 
109016         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
109017     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
109018       yyRuleName[yyruleno]);
109019   }
109020 #endif /* NDEBUG */
109021
109022   /* Silence complaints from purify about yygotominor being uninitialized
109023   ** in some cases when it is copied into the stack after the following
109024   ** switch.  yygotominor is uninitialized when a rule reduces that does
109025   ** not set the value of its left-hand side nonterminal.  Leaving the
109026   ** value of the nonterminal uninitialized is utterly harmless as long
109027   ** as the value is never used.  So really the only thing this code
109028   ** accomplishes is to quieten purify.  
109029   **
109030   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
109031   ** without this code, their parser segfaults.  I'm not sure what there
109032   ** parser is doing to make this happen.  This is the second bug report
109033   ** from wireshark this week.  Clearly they are stressing Lemon in ways
109034   ** that it has not been previously stressed...  (SQLite ticket #2172)
109035   */
109036   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
109037   yygotominor = yyzerominor;
109038
109039
109040   switch( yyruleno ){
109041   /* Beginning here are the reduction cases.  A typical example
109042   ** follows:
109043   **   case 0:
109044   **  #line <lineno> <grammarfile>
109045   **     { ... }           // User supplied code
109046   **  #line <lineno> <thisfile>
109047   **     break;
109048   */
109049       case 5: /* explain ::= */
109050 { sqlite3BeginParse(pParse, 0); }
109051         break;
109052       case 6: /* explain ::= EXPLAIN */
109053 { sqlite3BeginParse(pParse, 1); }
109054         break;
109055       case 7: /* explain ::= EXPLAIN QUERY PLAN */
109056 { sqlite3BeginParse(pParse, 2); }
109057         break;
109058       case 8: /* cmdx ::= cmd */
109059 { sqlite3FinishCoding(pParse); }
109060         break;
109061       case 9: /* cmd ::= BEGIN transtype trans_opt */
109062 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
109063         break;
109064       case 13: /* transtype ::= */
109065 {yygotominor.yy392 = TK_DEFERRED;}
109066         break;
109067       case 14: /* transtype ::= DEFERRED */
109068       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
109069       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
109070       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
109071       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
109072 {yygotominor.yy392 = yymsp[0].major;}
109073         break;
109074       case 17: /* cmd ::= COMMIT trans_opt */
109075       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
109076 {sqlite3CommitTransaction(pParse);}
109077         break;
109078       case 19: /* cmd ::= ROLLBACK trans_opt */
109079 {sqlite3RollbackTransaction(pParse);}
109080         break;
109081       case 22: /* cmd ::= SAVEPOINT nm */
109082 {
109083   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
109084 }
109085         break;
109086       case 23: /* cmd ::= RELEASE savepoint_opt nm */
109087 {
109088   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
109089 }
109090         break;
109091       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
109092 {
109093   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
109094 }
109095         break;
109096       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
109097 {
109098    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
109099 }
109100         break;
109101       case 27: /* createkw ::= CREATE */
109102 {
109103   pParse->db->lookaside.bEnabled = 0;
109104   yygotominor.yy0 = yymsp[0].minor.yy0;
109105 }
109106         break;
109107       case 28: /* ifnotexists ::= */
109108       case 31: /* temp ::= */ yytestcase(yyruleno==31);
109109       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
109110       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
109111       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
109112       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
109113       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
109114       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
109115       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
109116       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
109117       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
109118       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
109119 {yygotominor.yy392 = 0;}
109120         break;
109121       case 29: /* ifnotexists ::= IF NOT EXISTS */
109122       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
109123       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
109124       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
109125       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
109126       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
109127       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
109128       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
109129 {yygotominor.yy392 = 1;}
109130         break;
109131       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
109132 {
109133   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
109134 }
109135         break;
109136       case 33: /* create_table_args ::= AS select */
109137 {
109138   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
109139   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
109140 }
109141         break;
109142       case 36: /* column ::= columnid type carglist */
109143 {
109144   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
109145   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
109146 }
109147         break;
109148       case 37: /* columnid ::= nm */
109149 {
109150   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
109151   yygotominor.yy0 = yymsp[0].minor.yy0;
109152   pParse->constraintName.n = 0;
109153 }
109154         break;
109155       case 38: /* id ::= ID */
109156       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
109157       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
109158       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
109159       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
109160       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
109161       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
109162       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
109163       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
109164       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
109165       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
109166       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
109167       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
109168       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
109169       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
109170       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
109171       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
109172       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
109173       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
109174       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
109175       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
109176       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
109177       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
109178 {yygotominor.yy0 = yymsp[0].minor.yy0;}
109179         break;
109180       case 45: /* type ::= typetoken */
109181 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
109182         break;
109183       case 47: /* typetoken ::= typename LP signed RP */
109184 {
109185   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
109186   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
109187 }
109188         break;
109189       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
109190 {
109191   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
109192   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
109193 }
109194         break;
109195       case 50: /* typename ::= typename ids */
109196 {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);}
109197         break;
109198       case 55: /* ccons ::= CONSTRAINT nm */
109199       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
109200 {pParse->constraintName = yymsp[0].minor.yy0;}
109201         break;
109202       case 56: /* ccons ::= DEFAULT term */
109203       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
109204 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
109205         break;
109206       case 57: /* ccons ::= DEFAULT LP expr RP */
109207 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
109208         break;
109209       case 59: /* ccons ::= DEFAULT MINUS term */
109210 {
109211   ExprSpan v;
109212   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
109213   v.zStart = yymsp[-1].minor.yy0.z;
109214   v.zEnd = yymsp[0].minor.yy342.zEnd;
109215   sqlite3AddDefaultValue(pParse,&v);
109216 }
109217         break;
109218       case 60: /* ccons ::= DEFAULT id */
109219 {
109220   ExprSpan v;
109221   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
109222   sqlite3AddDefaultValue(pParse,&v);
109223 }
109224         break;
109225       case 62: /* ccons ::= NOT NULL onconf */
109226 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
109227         break;
109228       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
109229 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
109230         break;
109231       case 64: /* ccons ::= UNIQUE onconf */
109232 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
109233         break;
109234       case 65: /* ccons ::= CHECK LP expr RP */
109235 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
109236         break;
109237       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
109238 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
109239         break;
109240       case 67: /* ccons ::= defer_subclause */
109241 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
109242         break;
109243       case 68: /* ccons ::= COLLATE ids */
109244 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
109245         break;
109246       case 71: /* refargs ::= */
109247 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
109248         break;
109249       case 72: /* refargs ::= refargs refarg */
109250 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
109251         break;
109252       case 73: /* refarg ::= MATCH nm */
109253       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
109254 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
109255         break;
109256       case 75: /* refarg ::= ON DELETE refact */
109257 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
109258         break;
109259       case 76: /* refarg ::= ON UPDATE refact */
109260 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
109261         break;
109262       case 77: /* refact ::= SET NULL */
109263 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
109264         break;
109265       case 78: /* refact ::= SET DEFAULT */
109266 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
109267         break;
109268       case 79: /* refact ::= CASCADE */
109269 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
109270         break;
109271       case 80: /* refact ::= RESTRICT */
109272 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
109273         break;
109274       case 81: /* refact ::= NO ACTION */
109275 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
109276         break;
109277       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
109278       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
109279       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
109280       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
109281 {yygotominor.yy392 = yymsp[0].minor.yy392;}
109282         break;
109283       case 87: /* conslist_opt ::= */
109284 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
109285         break;
109286       case 88: /* conslist_opt ::= COMMA conslist */
109287 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
109288         break;
109289       case 91: /* tconscomma ::= COMMA */
109290 {pParse->constraintName.n = 0;}
109291         break;
109292       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
109293 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
109294         break;
109295       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
109296 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
109297         break;
109298       case 96: /* tcons ::= CHECK LP expr RP onconf */
109299 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
109300         break;
109301       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
109302 {
109303     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
109304     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
109305 }
109306         break;
109307       case 100: /* onconf ::= */
109308 {yygotominor.yy392 = OE_Default;}
109309         break;
109310       case 102: /* orconf ::= */
109311 {yygotominor.yy258 = OE_Default;}
109312         break;
109313       case 103: /* orconf ::= OR resolvetype */
109314 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
109315         break;
109316       case 105: /* resolvetype ::= IGNORE */
109317 {yygotominor.yy392 = OE_Ignore;}
109318         break;
109319       case 106: /* resolvetype ::= REPLACE */
109320 {yygotominor.yy392 = OE_Replace;}
109321         break;
109322       case 107: /* cmd ::= DROP TABLE ifexists fullname */
109323 {
109324   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
109325 }
109326         break;
109327       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
109328 {
109329   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);
109330 }
109331         break;
109332       case 111: /* cmd ::= DROP VIEW ifexists fullname */
109333 {
109334   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
109335 }
109336         break;
109337       case 112: /* cmd ::= select */
109338 {
109339   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
109340   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
109341   sqlite3ExplainBegin(pParse->pVdbe);
109342   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
109343   sqlite3ExplainFinish(pParse->pVdbe);
109344   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
109345 }
109346         break;
109347       case 113: /* select ::= oneselect */
109348 {yygotominor.yy159 = yymsp[0].minor.yy159;}
109349         break;
109350       case 114: /* select ::= select multiselect_op oneselect */
109351 {
109352   if( yymsp[0].minor.yy159 ){
109353     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
109354     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
109355   }else{
109356     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
109357   }
109358   yygotominor.yy159 = yymsp[0].minor.yy159;
109359 }
109360         break;
109361       case 116: /* multiselect_op ::= UNION ALL */
109362 {yygotominor.yy392 = TK_ALL;}
109363         break;
109364       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
109365 {
109366   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
109367 }
109368         break;
109369       case 122: /* sclp ::= selcollist COMMA */
109370       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
109371 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
109372         break;
109373       case 123: /* sclp ::= */
109374       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
109375       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
109376       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
109377       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
109378 {yygotominor.yy442 = 0;}
109379         break;
109380       case 124: /* selcollist ::= sclp expr as */
109381 {
109382    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
109383    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
109384    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
109385 }
109386         break;
109387       case 125: /* selcollist ::= sclp STAR */
109388 {
109389   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
109390   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
109391 }
109392         break;
109393       case 126: /* selcollist ::= sclp nm DOT STAR */
109394 {
109395   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
109396   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109397   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
109398   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
109399 }
109400         break;
109401       case 129: /* as ::= */
109402 {yygotominor.yy0.n = 0;}
109403         break;
109404       case 130: /* from ::= */
109405 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
109406         break;
109407       case 131: /* from ::= FROM seltablist */
109408 {
109409   yygotominor.yy347 = yymsp[0].minor.yy347;
109410   sqlite3SrcListShiftJoinType(yygotominor.yy347);
109411 }
109412         break;
109413       case 132: /* stl_prefix ::= seltablist joinop */
109414 {
109415    yygotominor.yy347 = yymsp[-1].minor.yy347;
109416    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
109417 }
109418         break;
109419       case 133: /* stl_prefix ::= */
109420 {yygotominor.yy347 = 0;}
109421         break;
109422       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
109423 {
109424   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);
109425   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
109426 }
109427         break;
109428       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
109429 {
109430     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);
109431   }
109432         break;
109433       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
109434 {
109435     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
109436       yygotominor.yy347 = yymsp[-4].minor.yy347;
109437     }else{
109438       Select *pSubquery;
109439       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
109440       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
109441       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
109442     }
109443   }
109444         break;
109445       case 137: /* dbnm ::= */
109446       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
109447 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
109448         break;
109449       case 139: /* fullname ::= nm dbnm */
109450 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
109451         break;
109452       case 140: /* joinop ::= COMMA|JOIN */
109453 { yygotominor.yy392 = JT_INNER; }
109454         break;
109455       case 141: /* joinop ::= JOIN_KW JOIN */
109456 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
109457         break;
109458       case 142: /* joinop ::= JOIN_KW nm JOIN */
109459 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
109460         break;
109461       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
109462 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
109463         break;
109464       case 144: /* on_opt ::= ON expr */
109465       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
109466       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
109467       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
109468       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
109469 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
109470         break;
109471       case 145: /* on_opt ::= */
109472       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
109473       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
109474       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
109475       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
109476 {yygotominor.yy122 = 0;}
109477         break;
109478       case 148: /* indexed_opt ::= NOT INDEXED */
109479 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
109480         break;
109481       case 149: /* using_opt ::= USING LP inscollist RP */
109482       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
109483 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
109484         break;
109485       case 150: /* using_opt ::= */
109486       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
109487 {yygotominor.yy180 = 0;}
109488         break;
109489       case 152: /* orderby_opt ::= ORDER BY sortlist */
109490       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
109491       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
109492 {yygotominor.yy442 = yymsp[0].minor.yy442;}
109493         break;
109494       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
109495 {
109496   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
109497   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
109498 }
109499         break;
109500       case 154: /* sortlist ::= expr sortorder */
109501 {
109502   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
109503   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
109504 }
109505         break;
109506       case 155: /* sortorder ::= ASC */
109507       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
109508 {yygotominor.yy392 = SQLITE_SO_ASC;}
109509         break;
109510       case 156: /* sortorder ::= DESC */
109511 {yygotominor.yy392 = SQLITE_SO_DESC;}
109512         break;
109513       case 162: /* limit_opt ::= */
109514 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
109515         break;
109516       case 163: /* limit_opt ::= LIMIT expr */
109517 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
109518         break;
109519       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
109520 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
109521         break;
109522       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
109523 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
109524         break;
109525       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
109526 {
109527   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
109528   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
109529 }
109530         break;
109531       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
109532 {
109533   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
109534   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
109535   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
109536 }
109537         break;
109538       case 170: /* setlist ::= setlist COMMA nm EQ expr */
109539 {
109540   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
109541   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
109542 }
109543         break;
109544       case 171: /* setlist ::= nm EQ expr */
109545 {
109546   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
109547   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
109548 }
109549         break;
109550       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
109551 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
109552         break;
109553       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
109554 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
109555         break;
109556       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
109557 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
109558         break;
109559       case 175: /* insert_cmd ::= INSERT orconf */
109560 {yygotominor.yy258 = yymsp[0].minor.yy258;}
109561         break;
109562       case 176: /* insert_cmd ::= REPLACE */
109563 {yygotominor.yy258 = OE_Replace;}
109564         break;
109565       case 177: /* valuelist ::= VALUES LP nexprlist RP */
109566 {
109567   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
109568   yygotominor.yy487.pSelect = 0;
109569 }
109570         break;
109571       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
109572 {
109573   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
109574   if( yymsp[-4].minor.yy487.pList ){
109575     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
109576     yymsp[-4].minor.yy487.pList = 0;
109577   }
109578   yygotominor.yy487.pList = 0;
109579   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
109580     sqlite3SelectDelete(pParse->db, pRight);
109581     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
109582     yygotominor.yy487.pSelect = 0;
109583   }else{
109584     pRight->op = TK_ALL;
109585     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
109586     pRight->selFlags |= SF_Values;
109587     pRight->pPrior->selFlags |= SF_Values;
109588     yygotominor.yy487.pSelect = pRight;
109589   }
109590 }
109591         break;
109592       case 181: /* inscollist ::= inscollist COMMA nm */
109593 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
109594         break;
109595       case 182: /* inscollist ::= nm */
109596 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
109597         break;
109598       case 183: /* expr ::= term */
109599 {yygotominor.yy342 = yymsp[0].minor.yy342;}
109600         break;
109601       case 184: /* expr ::= LP expr RP */
109602 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
109603         break;
109604       case 185: /* term ::= NULL */
109605       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
109606       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
109607 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
109608         break;
109609       case 186: /* expr ::= id */
109610       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
109611 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
109612         break;
109613       case 188: /* expr ::= nm DOT nm */
109614 {
109615   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109616   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
109617   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
109618   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
109619 }
109620         break;
109621       case 189: /* expr ::= nm DOT nm DOT nm */
109622 {
109623   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
109624   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109625   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
109626   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
109627   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
109628   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
109629 }
109630         break;
109631       case 192: /* expr ::= REGISTER */
109632 {
109633   /* When doing a nested parse, one can include terms in an expression
109634   ** that look like this:   #1 #2 ...  These terms refer to registers
109635   ** in the virtual machine.  #N is the N-th register. */
109636   if( pParse->nested==0 ){
109637     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
109638     yygotominor.yy342.pExpr = 0;
109639   }else{
109640     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
109641     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
109642   }
109643   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
109644 }
109645         break;
109646       case 193: /* expr ::= VARIABLE */
109647 {
109648   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
109649   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
109650   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
109651 }
109652         break;
109653       case 194: /* expr ::= expr COLLATE ids */
109654 {
109655   yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
109656   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
109657   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109658 }
109659         break;
109660       case 195: /* expr ::= CAST LP expr AS typetoken RP */
109661 {
109662   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
109663   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
109664 }
109665         break;
109666       case 196: /* expr ::= ID LP distinct exprlist RP */
109667 {
109668   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
109669     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
109670   }
109671   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
109672   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
109673   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
109674     yygotominor.yy342.pExpr->flags |= EP_Distinct;
109675   }
109676 }
109677         break;
109678       case 197: /* expr ::= ID LP STAR RP */
109679 {
109680   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
109681   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
109682 }
109683         break;
109684       case 198: /* term ::= CTIME_KW */
109685 {
109686   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
109687   ** treated as functions that return constants */
109688   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
109689   if( yygotominor.yy342.pExpr ){
109690     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  
109691   }
109692   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
109693 }
109694         break;
109695       case 199: /* expr ::= expr AND expr */
109696       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
109697       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
109698       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
109699       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
109700       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
109701       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
109702       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
109703 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
109704         break;
109705       case 207: /* likeop ::= LIKE_KW */
109706       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
109707 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
109708         break;
109709       case 208: /* likeop ::= NOT LIKE_KW */
109710       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
109711 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
109712         break;
109713       case 211: /* expr ::= expr likeop expr */
109714 {
109715   ExprList *pList;
109716   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
109717   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
109718   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
109719   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109720   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
109721   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
109722   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
109723 }
109724         break;
109725       case 212: /* expr ::= expr likeop expr ESCAPE expr */
109726 {
109727   ExprList *pList;
109728   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
109729   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
109730   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
109731   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
109732   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109733   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
109734   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
109735   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
109736 }
109737         break;
109738       case 213: /* expr ::= expr ISNULL|NOTNULL */
109739 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
109740         break;
109741       case 214: /* expr ::= expr NOT NULL */
109742 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
109743         break;
109744       case 215: /* expr ::= expr IS expr */
109745 {
109746   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
109747   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
109748 }
109749         break;
109750       case 216: /* expr ::= expr IS NOT expr */
109751 {
109752   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
109753   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
109754 }
109755         break;
109756       case 217: /* expr ::= NOT expr */
109757       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
109758 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
109759         break;
109760       case 219: /* expr ::= MINUS expr */
109761 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
109762         break;
109763       case 220: /* expr ::= PLUS expr */
109764 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
109765         break;
109766       case 223: /* expr ::= expr between_op expr AND expr */
109767 {
109768   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
109769   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
109770   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
109771   if( yygotominor.yy342.pExpr ){
109772     yygotominor.yy342.pExpr->x.pList = pList;
109773   }else{
109774     sqlite3ExprListDelete(pParse->db, pList);
109775   } 
109776   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109777   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
109778   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
109779 }
109780         break;
109781       case 226: /* expr ::= expr in_op LP exprlist RP */
109782 {
109783     if( yymsp[-1].minor.yy442==0 ){
109784       /* Expressions of the form
109785       **
109786       **      expr1 IN ()
109787       **      expr1 NOT IN ()
109788       **
109789       ** simplify to constants 0 (false) and 1 (true), respectively,
109790       ** regardless of the value of expr1.
109791       */
109792       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
109793       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
109794     }else{
109795       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
109796       if( yygotominor.yy342.pExpr ){
109797         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
109798         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
109799       }else{
109800         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
109801       }
109802       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109803     }
109804     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
109805     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109806   }
109807         break;
109808       case 227: /* expr ::= LP select RP */
109809 {
109810     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
109811     if( yygotominor.yy342.pExpr ){
109812       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
109813       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
109814       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
109815     }else{
109816       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
109817     }
109818     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
109819     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109820   }
109821         break;
109822       case 228: /* expr ::= expr in_op LP select RP */
109823 {
109824     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
109825     if( yygotominor.yy342.pExpr ){
109826       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
109827       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
109828       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
109829     }else{
109830       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
109831     }
109832     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109833     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
109834     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109835   }
109836         break;
109837       case 229: /* expr ::= expr in_op nm dbnm */
109838 {
109839     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
109840     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
109841     if( yygotominor.yy342.pExpr ){
109842       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
109843       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
109844       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
109845     }else{
109846       sqlite3SrcListDelete(pParse->db, pSrc);
109847     }
109848     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
109849     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
109850     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];
109851   }
109852         break;
109853       case 230: /* expr ::= EXISTS LP select RP */
109854 {
109855     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
109856     if( p ){
109857       p->x.pSelect = yymsp[-1].minor.yy159;
109858       ExprSetProperty(p, EP_xIsSelect);
109859       sqlite3ExprSetHeight(pParse, p);
109860     }else{
109861       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
109862     }
109863     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
109864     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109865   }
109866         break;
109867       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
109868 {
109869   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
109870   if( yygotominor.yy342.pExpr ){
109871     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
109872     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
109873   }else{
109874     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
109875   }
109876   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
109877   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
109878 }
109879         break;
109880       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
109881 {
109882   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
109883   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
109884 }
109885         break;
109886       case 233: /* case_exprlist ::= WHEN expr THEN expr */
109887 {
109888   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
109889   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
109890 }
109891         break;
109892       case 240: /* nexprlist ::= nexprlist COMMA expr */
109893 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
109894         break;
109895       case 241: /* nexprlist ::= expr */
109896 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
109897         break;
109898       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
109899 {
109900   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
109901                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
109902                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
109903 }
109904         break;
109905       case 243: /* uniqueflag ::= UNIQUE */
109906       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
109907 {yygotominor.yy392 = OE_Abort;}
109908         break;
109909       case 244: /* uniqueflag ::= */
109910 {yygotominor.yy392 = OE_None;}
109911         break;
109912       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
109913 {
109914   Expr *p = 0;
109915   if( yymsp[-1].minor.yy0.n>0 ){
109916     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
109917     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
109918   }
109919   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
109920   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
109921   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
109922   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
109923 }
109924         break;
109925       case 248: /* idxlist ::= nm collate sortorder */
109926 {
109927   Expr *p = 0;
109928   if( yymsp[-1].minor.yy0.n>0 ){
109929     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
109930     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
109931   }
109932   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
109933   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
109934   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
109935   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
109936 }
109937         break;
109938       case 249: /* collate ::= */
109939 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
109940         break;
109941       case 251: /* cmd ::= DROP INDEX ifexists fullname */
109942 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
109943         break;
109944       case 252: /* cmd ::= VACUUM */
109945       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
109946 {sqlite3Vacuum(pParse);}
109947         break;
109948       case 254: /* cmd ::= PRAGMA nm dbnm */
109949 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
109950         break;
109951       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
109952 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
109953         break;
109954       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
109955 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
109956         break;
109957       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
109958 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
109959         break;
109960       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
109961 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
109962         break;
109963       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
109964 {
109965   Token all;
109966   all.z = yymsp[-3].minor.yy0.z;
109967   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
109968   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
109969 }
109970         break;
109971       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
109972 {
109973   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);
109974   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
109975 }
109976         break;
109977       case 270: /* trigger_time ::= BEFORE */
109978       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
109979 { yygotominor.yy392 = TK_BEFORE; }
109980         break;
109981       case 271: /* trigger_time ::= AFTER */
109982 { yygotominor.yy392 = TK_AFTER;  }
109983         break;
109984       case 272: /* trigger_time ::= INSTEAD OF */
109985 { yygotominor.yy392 = TK_INSTEAD;}
109986         break;
109987       case 274: /* trigger_event ::= DELETE|INSERT */
109988       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
109989 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
109990         break;
109991       case 276: /* trigger_event ::= UPDATE OF inscollist */
109992 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
109993         break;
109994       case 279: /* when_clause ::= */
109995       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
109996 { yygotominor.yy122 = 0; }
109997         break;
109998       case 280: /* when_clause ::= WHEN expr */
109999       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
110000 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
110001         break;
110002       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
110003 {
110004   assert( yymsp[-2].minor.yy327!=0 );
110005   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
110006   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
110007   yygotominor.yy327 = yymsp[-2].minor.yy327;
110008 }
110009         break;
110010       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
110011
110012   assert( yymsp[-1].minor.yy327!=0 );
110013   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
110014   yygotominor.yy327 = yymsp[-1].minor.yy327;
110015 }
110016         break;
110017       case 284: /* trnm ::= nm DOT nm */
110018 {
110019   yygotominor.yy0 = yymsp[0].minor.yy0;
110020   sqlite3ErrorMsg(pParse, 
110021         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
110022         "statements within triggers");
110023 }
110024         break;
110025       case 286: /* tridxby ::= INDEXED BY nm */
110026 {
110027   sqlite3ErrorMsg(pParse,
110028         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
110029         "within triggers");
110030 }
110031         break;
110032       case 287: /* tridxby ::= NOT INDEXED */
110033 {
110034   sqlite3ErrorMsg(pParse,
110035         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
110036         "within triggers");
110037 }
110038         break;
110039       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
110040 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
110041         break;
110042       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
110043 {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);}
110044         break;
110045       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
110046 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
110047         break;
110048       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
110049 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
110050         break;
110051       case 292: /* trigger_cmd ::= select */
110052 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
110053         break;
110054       case 293: /* expr ::= RAISE LP IGNORE RP */
110055 {
110056   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
110057   if( yygotominor.yy342.pExpr ){
110058     yygotominor.yy342.pExpr->affinity = OE_Ignore;
110059   }
110060   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110061   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110062 }
110063         break;
110064       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
110065 {
110066   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
110067   if( yygotominor.yy342.pExpr ) {
110068     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
110069   }
110070   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
110071   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110072 }
110073         break;
110074       case 295: /* raisetype ::= ROLLBACK */
110075 {yygotominor.yy392 = OE_Rollback;}
110076         break;
110077       case 297: /* raisetype ::= FAIL */
110078 {yygotominor.yy392 = OE_Fail;}
110079         break;
110080       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
110081 {
110082   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
110083 }
110084         break;
110085       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
110086 {
110087   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
110088 }
110089         break;
110090       case 300: /* cmd ::= DETACH database_kw_opt expr */
110091 {
110092   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
110093 }
110094         break;
110095       case 305: /* cmd ::= REINDEX */
110096 {sqlite3Reindex(pParse, 0, 0);}
110097         break;
110098       case 306: /* cmd ::= REINDEX nm dbnm */
110099 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110100         break;
110101       case 307: /* cmd ::= ANALYZE */
110102 {sqlite3Analyze(pParse, 0, 0);}
110103         break;
110104       case 308: /* cmd ::= ANALYZE nm dbnm */
110105 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110106         break;
110107       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
110108 {
110109   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
110110 }
110111         break;
110112       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
110113 {
110114   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
110115 }
110116         break;
110117       case 311: /* add_column_fullname ::= fullname */
110118 {
110119   pParse->db->lookaside.bEnabled = 0;
110120   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
110121 }
110122         break;
110123       case 314: /* cmd ::= create_vtab */
110124 {sqlite3VtabFinishParse(pParse,0);}
110125         break;
110126       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
110127 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
110128         break;
110129       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
110130 {
110131     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
110132 }
110133         break;
110134       case 319: /* vtabarg ::= */
110135 {sqlite3VtabArgInit(pParse);}
110136         break;
110137       case 321: /* vtabargtoken ::= ANY */
110138       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
110139       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
110140 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
110141         break;
110142       default:
110143       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
110144       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
110145       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
110146       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
110147       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
110148       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
110149       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
110150       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
110151       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
110152       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
110153       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
110154       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
110155       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
110156       /* (44) type ::= */ yytestcase(yyruleno==44);
110157       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
110158       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
110159       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
110160       /* (54) carglist ::= */ yytestcase(yyruleno==54);
110161       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
110162       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
110163       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
110164       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
110165       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
110166       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
110167       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
110168       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
110169       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
110170       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
110171       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
110172       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
110173       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
110174       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
110175       /* (324) anylist ::= */ yytestcase(yyruleno==324);
110176       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
110177       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
110178         break;
110179   };
110180   yygoto = yyRuleInfo[yyruleno].lhs;
110181   yysize = yyRuleInfo[yyruleno].nrhs;
110182   yypParser->yyidx -= yysize;
110183   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
110184   if( yyact < YYNSTATE ){
110185 #ifdef NDEBUG
110186     /* If we are not debugging and the reduce action popped at least
110187     ** one element off the stack, then we can push the new element back
110188     ** onto the stack here, and skip the stack overflow test in yy_shift().
110189     ** That gives a significant speed improvement. */
110190     if( yysize ){
110191       yypParser->yyidx++;
110192       yymsp -= yysize-1;
110193       yymsp->stateno = (YYACTIONTYPE)yyact;
110194       yymsp->major = (YYCODETYPE)yygoto;
110195       yymsp->minor = yygotominor;
110196     }else
110197 #endif
110198     {
110199       yy_shift(yypParser,yyact,yygoto,&yygotominor);
110200     }
110201   }else{
110202     assert( yyact == YYNSTATE + YYNRULE + 1 );
110203     yy_accept(yypParser);
110204   }
110205 }
110206
110207 /*
110208 ** The following code executes when the parse fails
110209 */
110210 #ifndef YYNOERRORRECOVERY
110211 static void yy_parse_failed(
110212   yyParser *yypParser           /* The parser */
110213 ){
110214   sqlite3ParserARG_FETCH;
110215 #ifndef NDEBUG
110216   if( yyTraceFILE ){
110217     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
110218   }
110219 #endif
110220   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110221   /* Here code is inserted which will be executed whenever the
110222   ** parser fails */
110223   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110224 }
110225 #endif /* YYNOERRORRECOVERY */
110226
110227 /*
110228 ** The following code executes when a syntax error first occurs.
110229 */
110230 static void yy_syntax_error(
110231   yyParser *yypParser,           /* The parser */
110232   int yymajor,                   /* The major type of the error token */
110233   YYMINORTYPE yyminor            /* The minor type of the error token */
110234 ){
110235   sqlite3ParserARG_FETCH;
110236 #define TOKEN (yyminor.yy0)
110237
110238   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
110239   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
110240   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
110241   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110242 }
110243
110244 /*
110245 ** The following is executed when the parser accepts
110246 */
110247 static void yy_accept(
110248   yyParser *yypParser           /* The parser */
110249 ){
110250   sqlite3ParserARG_FETCH;
110251 #ifndef NDEBUG
110252   if( yyTraceFILE ){
110253     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
110254   }
110255 #endif
110256   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110257   /* Here code is inserted which will be executed whenever the
110258   ** parser accepts */
110259   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110260 }
110261
110262 /* The main parser program.
110263 ** The first argument is a pointer to a structure obtained from
110264 ** "sqlite3ParserAlloc" which describes the current state of the parser.
110265 ** The second argument is the major token number.  The third is
110266 ** the minor token.  The fourth optional argument is whatever the
110267 ** user wants (and specified in the grammar) and is available for
110268 ** use by the action routines.
110269 **
110270 ** Inputs:
110271 ** <ul>
110272 ** <li> A pointer to the parser (an opaque structure.)
110273 ** <li> The major token number.
110274 ** <li> The minor token number.
110275 ** <li> An option argument of a grammar-specified type.
110276 ** </ul>
110277 **
110278 ** Outputs:
110279 ** None.
110280 */
110281 SQLITE_PRIVATE void sqlite3Parser(
110282   void *yyp,                   /* The parser */
110283   int yymajor,                 /* The major token code number */
110284   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
110285   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
110286 ){
110287   YYMINORTYPE yyminorunion;
110288   int yyact;            /* The parser action. */
110289 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110290   int yyendofinput;     /* True if we are at the end of input */
110291 #endif
110292 #ifdef YYERRORSYMBOL
110293   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
110294 #endif
110295   yyParser *yypParser;  /* The parser */
110296
110297   /* (re)initialize the parser, if necessary */
110298   yypParser = (yyParser*)yyp;
110299   if( yypParser->yyidx<0 ){
110300 #if YYSTACKDEPTH<=0
110301     if( yypParser->yystksz <=0 ){
110302       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
110303       yyminorunion = yyzerominor;
110304       yyStackOverflow(yypParser, &yyminorunion);
110305       return;
110306     }
110307 #endif
110308     yypParser->yyidx = 0;
110309     yypParser->yyerrcnt = -1;
110310     yypParser->yystack[0].stateno = 0;
110311     yypParser->yystack[0].major = 0;
110312   }
110313   yyminorunion.yy0 = yyminor;
110314 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110315   yyendofinput = (yymajor==0);
110316 #endif
110317   sqlite3ParserARG_STORE;
110318
110319 #ifndef NDEBUG
110320   if( yyTraceFILE ){
110321     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
110322   }
110323 #endif
110324
110325   do{
110326     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
110327     if( yyact<YYNSTATE ){
110328       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
110329       yypParser->yyerrcnt--;
110330       yymajor = YYNOCODE;
110331     }else if( yyact < YYNSTATE + YYNRULE ){
110332       yy_reduce(yypParser,yyact-YYNSTATE);
110333     }else{
110334       assert( yyact == YY_ERROR_ACTION );
110335 #ifdef YYERRORSYMBOL
110336       int yymx;
110337 #endif
110338 #ifndef NDEBUG
110339       if( yyTraceFILE ){
110340         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
110341       }
110342 #endif
110343 #ifdef YYERRORSYMBOL
110344       /* A syntax error has occurred.
110345       ** The response to an error depends upon whether or not the
110346       ** grammar defines an error token "ERROR".  
110347       **
110348       ** This is what we do if the grammar does define ERROR:
110349       **
110350       **  * Call the %syntax_error function.
110351       **
110352       **  * Begin popping the stack until we enter a state where
110353       **    it is legal to shift the error symbol, then shift
110354       **    the error symbol.
110355       **
110356       **  * Set the error count to three.
110357       **
110358       **  * Begin accepting and shifting new tokens.  No new error
110359       **    processing will occur until three tokens have been
110360       **    shifted successfully.
110361       **
110362       */
110363       if( yypParser->yyerrcnt<0 ){
110364         yy_syntax_error(yypParser,yymajor,yyminorunion);
110365       }
110366       yymx = yypParser->yystack[yypParser->yyidx].major;
110367       if( yymx==YYERRORSYMBOL || yyerrorhit ){
110368 #ifndef NDEBUG
110369         if( yyTraceFILE ){
110370           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
110371              yyTracePrompt,yyTokenName[yymajor]);
110372         }
110373 #endif
110374         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
110375         yymajor = YYNOCODE;
110376       }else{
110377          while(
110378           yypParser->yyidx >= 0 &&
110379           yymx != YYERRORSYMBOL &&
110380           (yyact = yy_find_reduce_action(
110381                         yypParser->yystack[yypParser->yyidx].stateno,
110382                         YYERRORSYMBOL)) >= YYNSTATE
110383         ){
110384           yy_pop_parser_stack(yypParser);
110385         }
110386         if( yypParser->yyidx < 0 || yymajor==0 ){
110387           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110388           yy_parse_failed(yypParser);
110389           yymajor = YYNOCODE;
110390         }else if( yymx!=YYERRORSYMBOL ){
110391           YYMINORTYPE u2;
110392           u2.YYERRSYMDT = 0;
110393           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
110394         }
110395       }
110396       yypParser->yyerrcnt = 3;
110397       yyerrorhit = 1;
110398 #elif defined(YYNOERRORRECOVERY)
110399       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
110400       ** do any kind of error recovery.  Instead, simply invoke the syntax
110401       ** error routine and continue going as if nothing had happened.
110402       **
110403       ** Applications can set this macro (for example inside %include) if
110404       ** they intend to abandon the parse upon the first syntax error seen.
110405       */
110406       yy_syntax_error(yypParser,yymajor,yyminorunion);
110407       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110408       yymajor = YYNOCODE;
110409       
110410 #else  /* YYERRORSYMBOL is not defined */
110411       /* This is what we do if the grammar does not define ERROR:
110412       **
110413       **  * Report an error message, and throw away the input token.
110414       **
110415       **  * If the input token is $, then fail the parse.
110416       **
110417       ** As before, subsequent error messages are suppressed until
110418       ** three input tokens have been successfully shifted.
110419       */
110420       if( yypParser->yyerrcnt<=0 ){
110421         yy_syntax_error(yypParser,yymajor,yyminorunion);
110422       }
110423       yypParser->yyerrcnt = 3;
110424       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110425       if( yyendofinput ){
110426         yy_parse_failed(yypParser);
110427       }
110428       yymajor = YYNOCODE;
110429 #endif
110430     }
110431   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
110432   return;
110433 }
110434
110435 /************** End of parse.c ***********************************************/
110436 /************** Begin file tokenize.c ****************************************/
110437 /*
110438 ** 2001 September 15
110439 **
110440 ** The author disclaims copyright to this source code.  In place of
110441 ** a legal notice, here is a blessing:
110442 **
110443 **    May you do good and not evil.
110444 **    May you find forgiveness for yourself and forgive others.
110445 **    May you share freely, never taking more than you give.
110446 **
110447 *************************************************************************
110448 ** An tokenizer for SQL
110449 **
110450 ** This file contains C code that splits an SQL input string up into
110451 ** individual tokens and sends those tokens one-by-one over to the
110452 ** parser for analysis.
110453 */
110454 /* #include <stdlib.h> */
110455
110456 /*
110457 ** The charMap() macro maps alphabetic characters into their
110458 ** lower-case ASCII equivalent.  On ASCII machines, this is just
110459 ** an upper-to-lower case map.  On EBCDIC machines we also need
110460 ** to adjust the encoding.  Only alphabetic characters and underscores
110461 ** need to be translated.
110462 */
110463 #ifdef SQLITE_ASCII
110464 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
110465 #endif
110466 #ifdef SQLITE_EBCDIC
110467 # define charMap(X) ebcdicToAscii[(unsigned char)X]
110468 const unsigned char ebcdicToAscii[] = {
110469 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
110470    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
110471    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
110472    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
110473    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
110474    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
110475    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
110476    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
110477    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
110478    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
110479    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
110480    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
110481    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
110482    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
110483    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
110484    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
110485    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
110486 };
110487 #endif
110488
110489 /*
110490 ** The sqlite3KeywordCode function looks up an identifier to determine if
110491 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
110492 ** returned.  If the input is not a keyword, TK_ID is returned.
110493 **
110494 ** The implementation of this routine was generated by a program,
110495 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
110496 ** The output of the mkkeywordhash.c program is written into a file
110497 ** named keywordhash.h and then included into this source file by
110498 ** the #include below.
110499 */
110500 /************** Include keywordhash.h in the middle of tokenize.c ************/
110501 /************** Begin file keywordhash.h *************************************/
110502 /***** This file contains automatically generated code ******
110503 **
110504 ** The code in this file has been automatically generated by
110505 **
110506 **   sqlite/tool/mkkeywordhash.c
110507 **
110508 ** The code in this file implements a function that determines whether
110509 ** or not a given identifier is really an SQL keyword.  The same thing
110510 ** might be implemented more directly using a hand-written hash table.
110511 ** But by using this automatically generated code, the size of the code
110512 ** is substantially reduced.  This is important for embedded applications
110513 ** on platforms with limited memory.
110514 */
110515 /* Hash score: 175 */
110516 static int keywordCode(const char *z, int n){
110517   /* zText[] encodes 811 bytes of keywords in 541 bytes */
110518   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
110519   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
110520   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
110521   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
110522   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
110523   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
110524   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
110525   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
110526   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
110527   /*   INITIALLY                                                          */
110528   static const char zText[540] = {
110529     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
110530     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
110531     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
110532     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
110533     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
110534     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
110535     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
110536     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
110537     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
110538     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
110539     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
110540     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
110541     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
110542     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
110543     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
110544     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
110545     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
110546     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
110547     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
110548     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
110549     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
110550     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
110551     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
110552     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
110553     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
110554     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
110555     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
110556     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
110557     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
110558     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
110559   };
110560   static const unsigned char aHash[127] = {
110561       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
110562       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
110563      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
110564        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
110565        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
110566       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
110567       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
110568       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
110569       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
110570       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
110571   };
110572   static const unsigned char aNext[121] = {
110573        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
110574        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
110575        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
110576        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
110577        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
110578       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
110579       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
110580        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
110581      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
110582       35,  64,   0,   0,
110583   };
110584   static const unsigned char aLen[121] = {
110585        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
110586        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
110587       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
110588        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
110589        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
110590        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
110591        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
110592        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
110593        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
110594        6,   4,   9,   3,
110595   };
110596   static const unsigned short int aOffset[121] = {
110597        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
110598       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
110599       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
110600      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
110601      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
110602      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
110603      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
110604      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
110605      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
110606      521, 527, 531, 536,
110607   };
110608   static const unsigned char aCode[121] = {
110609     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
110610     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
110611     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
110612     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
110613     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
110614     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
110615     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
110616     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
110617     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
110618     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
110619     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
110620     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
110621     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
110622     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
110623     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
110624     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
110625     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
110626     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
110627     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
110628     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
110629     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
110630     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
110631     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
110632     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
110633     TK_ALL,        
110634   };
110635   int h, i;
110636   if( n<2 ) return TK_ID;
110637   h = ((charMap(z[0])*4) ^
110638       (charMap(z[n-1])*3) ^
110639       n) % 127;
110640   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
110641     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
110642       testcase( i==0 ); /* REINDEX */
110643       testcase( i==1 ); /* INDEXED */
110644       testcase( i==2 ); /* INDEX */
110645       testcase( i==3 ); /* DESC */
110646       testcase( i==4 ); /* ESCAPE */
110647       testcase( i==5 ); /* EACH */
110648       testcase( i==6 ); /* CHECK */
110649       testcase( i==7 ); /* KEY */
110650       testcase( i==8 ); /* BEFORE */
110651       testcase( i==9 ); /* FOREIGN */
110652       testcase( i==10 ); /* FOR */
110653       testcase( i==11 ); /* IGNORE */
110654       testcase( i==12 ); /* REGEXP */
110655       testcase( i==13 ); /* EXPLAIN */
110656       testcase( i==14 ); /* INSTEAD */
110657       testcase( i==15 ); /* ADD */
110658       testcase( i==16 ); /* DATABASE */
110659       testcase( i==17 ); /* AS */
110660       testcase( i==18 ); /* SELECT */
110661       testcase( i==19 ); /* TABLE */
110662       testcase( i==20 ); /* LEFT */
110663       testcase( i==21 ); /* THEN */
110664       testcase( i==22 ); /* END */
110665       testcase( i==23 ); /* DEFERRABLE */
110666       testcase( i==24 ); /* ELSE */
110667       testcase( i==25 ); /* EXCEPT */
110668       testcase( i==26 ); /* TRANSACTION */
110669       testcase( i==27 ); /* ACTION */
110670       testcase( i==28 ); /* ON */
110671       testcase( i==29 ); /* NATURAL */
110672       testcase( i==30 ); /* ALTER */
110673       testcase( i==31 ); /* RAISE */
110674       testcase( i==32 ); /* EXCLUSIVE */
110675       testcase( i==33 ); /* EXISTS */
110676       testcase( i==34 ); /* SAVEPOINT */
110677       testcase( i==35 ); /* INTERSECT */
110678       testcase( i==36 ); /* TRIGGER */
110679       testcase( i==37 ); /* REFERENCES */
110680       testcase( i==38 ); /* CONSTRAINT */
110681       testcase( i==39 ); /* INTO */
110682       testcase( i==40 ); /* OFFSET */
110683       testcase( i==41 ); /* OF */
110684       testcase( i==42 ); /* SET */
110685       testcase( i==43 ); /* TEMPORARY */
110686       testcase( i==44 ); /* TEMP */
110687       testcase( i==45 ); /* OR */
110688       testcase( i==46 ); /* UNIQUE */
110689       testcase( i==47 ); /* QUERY */
110690       testcase( i==48 ); /* ATTACH */
110691       testcase( i==49 ); /* HAVING */
110692       testcase( i==50 ); /* GROUP */
110693       testcase( i==51 ); /* UPDATE */
110694       testcase( i==52 ); /* BEGIN */
110695       testcase( i==53 ); /* INNER */
110696       testcase( i==54 ); /* RELEASE */
110697       testcase( i==55 ); /* BETWEEN */
110698       testcase( i==56 ); /* NOTNULL */
110699       testcase( i==57 ); /* NOT */
110700       testcase( i==58 ); /* NO */
110701       testcase( i==59 ); /* NULL */
110702       testcase( i==60 ); /* LIKE */
110703       testcase( i==61 ); /* CASCADE */
110704       testcase( i==62 ); /* ASC */
110705       testcase( i==63 ); /* DELETE */
110706       testcase( i==64 ); /* CASE */
110707       testcase( i==65 ); /* COLLATE */
110708       testcase( i==66 ); /* CREATE */
110709       testcase( i==67 ); /* CURRENT_DATE */
110710       testcase( i==68 ); /* DETACH */
110711       testcase( i==69 ); /* IMMEDIATE */
110712       testcase( i==70 ); /* JOIN */
110713       testcase( i==71 ); /* INSERT */
110714       testcase( i==72 ); /* MATCH */
110715       testcase( i==73 ); /* PLAN */
110716       testcase( i==74 ); /* ANALYZE */
110717       testcase( i==75 ); /* PRAGMA */
110718       testcase( i==76 ); /* ABORT */
110719       testcase( i==77 ); /* VALUES */
110720       testcase( i==78 ); /* VIRTUAL */
110721       testcase( i==79 ); /* LIMIT */
110722       testcase( i==80 ); /* WHEN */
110723       testcase( i==81 ); /* WHERE */
110724       testcase( i==82 ); /* RENAME */
110725       testcase( i==83 ); /* AFTER */
110726       testcase( i==84 ); /* REPLACE */
110727       testcase( i==85 ); /* AND */
110728       testcase( i==86 ); /* DEFAULT */
110729       testcase( i==87 ); /* AUTOINCREMENT */
110730       testcase( i==88 ); /* TO */
110731       testcase( i==89 ); /* IN */
110732       testcase( i==90 ); /* CAST */
110733       testcase( i==91 ); /* COLUMN */
110734       testcase( i==92 ); /* COMMIT */
110735       testcase( i==93 ); /* CONFLICT */
110736       testcase( i==94 ); /* CROSS */
110737       testcase( i==95 ); /* CURRENT_TIMESTAMP */
110738       testcase( i==96 ); /* CURRENT_TIME */
110739       testcase( i==97 ); /* PRIMARY */
110740       testcase( i==98 ); /* DEFERRED */
110741       testcase( i==99 ); /* DISTINCT */
110742       testcase( i==100 ); /* IS */
110743       testcase( i==101 ); /* DROP */
110744       testcase( i==102 ); /* FAIL */
110745       testcase( i==103 ); /* FROM */
110746       testcase( i==104 ); /* FULL */
110747       testcase( i==105 ); /* GLOB */
110748       testcase( i==106 ); /* BY */
110749       testcase( i==107 ); /* IF */
110750       testcase( i==108 ); /* ISNULL */
110751       testcase( i==109 ); /* ORDER */
110752       testcase( i==110 ); /* RESTRICT */
110753       testcase( i==111 ); /* OUTER */
110754       testcase( i==112 ); /* RIGHT */
110755       testcase( i==113 ); /* ROLLBACK */
110756       testcase( i==114 ); /* ROW */
110757       testcase( i==115 ); /* UNION */
110758       testcase( i==116 ); /* USING */
110759       testcase( i==117 ); /* VACUUM */
110760       testcase( i==118 ); /* VIEW */
110761       testcase( i==119 ); /* INITIALLY */
110762       testcase( i==120 ); /* ALL */
110763       return aCode[i];
110764     }
110765   }
110766   return TK_ID;
110767 }
110768 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
110769   return keywordCode((char*)z, n);
110770 }
110771 #define SQLITE_N_KEYWORD 121
110772
110773 /************** End of keywordhash.h *****************************************/
110774 /************** Continuing where we left off in tokenize.c *******************/
110775
110776
110777 /*
110778 ** If X is a character that can be used in an identifier then
110779 ** IdChar(X) will be true.  Otherwise it is false.
110780 **
110781 ** For ASCII, any character with the high-order bit set is
110782 ** allowed in an identifier.  For 7-bit characters, 
110783 ** sqlite3IsIdChar[X] must be 1.
110784 **
110785 ** For EBCDIC, the rules are more complex but have the same
110786 ** end result.
110787 **
110788 ** Ticket #1066.  the SQL standard does not allow '$' in the
110789 ** middle of identfiers.  But many SQL implementations do. 
110790 ** SQLite will allow '$' in identifiers for compatibility.
110791 ** But the feature is undocumented.
110792 */
110793 #ifdef SQLITE_ASCII
110794 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
110795 #endif
110796 #ifdef SQLITE_EBCDIC
110797 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
110798 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
110799     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
110800     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
110801     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
110802     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
110803     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
110804     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
110805     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
110806     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
110807     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
110808     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
110809     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
110810     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
110811 };
110812 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
110813 #endif
110814
110815
110816 /*
110817 ** Return the length of the token that begins at z[0]. 
110818 ** Store the token type in *tokenType before returning.
110819 */
110820 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
110821   int i, c;
110822   switch( *z ){
110823     case ' ': case '\t': case '\n': case '\f': case '\r': {
110824       testcase( z[0]==' ' );
110825       testcase( z[0]=='\t' );
110826       testcase( z[0]=='\n' );
110827       testcase( z[0]=='\f' );
110828       testcase( z[0]=='\r' );
110829       for(i=1; sqlite3Isspace(z[i]); i++){}
110830       *tokenType = TK_SPACE;
110831       return i;
110832     }
110833     case '-': {
110834       if( z[1]=='-' ){
110835         /* IMP: R-50417-27976 -- syntax diagram for comments */
110836         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
110837         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
110838         return i;
110839       }
110840       *tokenType = TK_MINUS;
110841       return 1;
110842     }
110843     case '(': {
110844       *tokenType = TK_LP;
110845       return 1;
110846     }
110847     case ')': {
110848       *tokenType = TK_RP;
110849       return 1;
110850     }
110851     case ';': {
110852       *tokenType = TK_SEMI;
110853       return 1;
110854     }
110855     case '+': {
110856       *tokenType = TK_PLUS;
110857       return 1;
110858     }
110859     case '*': {
110860       *tokenType = TK_STAR;
110861       return 1;
110862     }
110863     case '/': {
110864       if( z[1]!='*' || z[2]==0 ){
110865         *tokenType = TK_SLASH;
110866         return 1;
110867       }
110868       /* IMP: R-50417-27976 -- syntax diagram for comments */
110869       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
110870       if( c ) i++;
110871       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
110872       return i;
110873     }
110874     case '%': {
110875       *tokenType = TK_REM;
110876       return 1;
110877     }
110878     case '=': {
110879       *tokenType = TK_EQ;
110880       return 1 + (z[1]=='=');
110881     }
110882     case '<': {
110883       if( (c=z[1])=='=' ){
110884         *tokenType = TK_LE;
110885         return 2;
110886       }else if( c=='>' ){
110887         *tokenType = TK_NE;
110888         return 2;
110889       }else if( c=='<' ){
110890         *tokenType = TK_LSHIFT;
110891         return 2;
110892       }else{
110893         *tokenType = TK_LT;
110894         return 1;
110895       }
110896     }
110897     case '>': {
110898       if( (c=z[1])=='=' ){
110899         *tokenType = TK_GE;
110900         return 2;
110901       }else if( c=='>' ){
110902         *tokenType = TK_RSHIFT;
110903         return 2;
110904       }else{
110905         *tokenType = TK_GT;
110906         return 1;
110907       }
110908     }
110909     case '!': {
110910       if( z[1]!='=' ){
110911         *tokenType = TK_ILLEGAL;
110912         return 2;
110913       }else{
110914         *tokenType = TK_NE;
110915         return 2;
110916       }
110917     }
110918     case '|': {
110919       if( z[1]!='|' ){
110920         *tokenType = TK_BITOR;
110921         return 1;
110922       }else{
110923         *tokenType = TK_CONCAT;
110924         return 2;
110925       }
110926     }
110927     case ',': {
110928       *tokenType = TK_COMMA;
110929       return 1;
110930     }
110931     case '&': {
110932       *tokenType = TK_BITAND;
110933       return 1;
110934     }
110935     case '~': {
110936       *tokenType = TK_BITNOT;
110937       return 1;
110938     }
110939     case '`':
110940     case '\'':
110941     case '"': {
110942       int delim = z[0];
110943       testcase( delim=='`' );
110944       testcase( delim=='\'' );
110945       testcase( delim=='"' );
110946       for(i=1; (c=z[i])!=0; i++){
110947         if( c==delim ){
110948           if( z[i+1]==delim ){
110949             i++;
110950           }else{
110951             break;
110952           }
110953         }
110954       }
110955       if( c=='\'' ){
110956         *tokenType = TK_STRING;
110957         return i+1;
110958       }else if( c!=0 ){
110959         *tokenType = TK_ID;
110960         return i+1;
110961       }else{
110962         *tokenType = TK_ILLEGAL;
110963         return i;
110964       }
110965     }
110966     case '.': {
110967 #ifndef SQLITE_OMIT_FLOATING_POINT
110968       if( !sqlite3Isdigit(z[1]) )
110969 #endif
110970       {
110971         *tokenType = TK_DOT;
110972         return 1;
110973       }
110974       /* If the next character is a digit, this is a floating point
110975       ** number that begins with ".".  Fall thru into the next case */
110976     }
110977     case '0': case '1': case '2': case '3': case '4':
110978     case '5': case '6': case '7': case '8': case '9': {
110979       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
110980       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
110981       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
110982       testcase( z[0]=='9' );
110983       *tokenType = TK_INTEGER;
110984       for(i=0; sqlite3Isdigit(z[i]); i++){}
110985 #ifndef SQLITE_OMIT_FLOATING_POINT
110986       if( z[i]=='.' ){
110987         i++;
110988         while( sqlite3Isdigit(z[i]) ){ i++; }
110989         *tokenType = TK_FLOAT;
110990       }
110991       if( (z[i]=='e' || z[i]=='E') &&
110992            ( sqlite3Isdigit(z[i+1]) 
110993             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
110994            )
110995       ){
110996         i += 2;
110997         while( sqlite3Isdigit(z[i]) ){ i++; }
110998         *tokenType = TK_FLOAT;
110999       }
111000 #endif
111001       while( IdChar(z[i]) ){
111002         *tokenType = TK_ILLEGAL;
111003         i++;
111004       }
111005       return i;
111006     }
111007     case '[': {
111008       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
111009       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
111010       return i;
111011     }
111012     case '?': {
111013       *tokenType = TK_VARIABLE;
111014       for(i=1; sqlite3Isdigit(z[i]); i++){}
111015       return i;
111016     }
111017     case '#': {
111018       for(i=1; sqlite3Isdigit(z[i]); i++){}
111019       if( i>1 ){
111020         /* Parameters of the form #NNN (where NNN is a number) are used
111021         ** internally by sqlite3NestedParse.  */
111022         *tokenType = TK_REGISTER;
111023         return i;
111024       }
111025       /* Fall through into the next case if the '#' is not followed by
111026       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
111027     }
111028 #ifndef SQLITE_OMIT_TCL_VARIABLE
111029     case '$':
111030 #endif
111031     case '@':  /* For compatibility with MS SQL Server */
111032     case ':': {
111033       int n = 0;
111034       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
111035       *tokenType = TK_VARIABLE;
111036       for(i=1; (c=z[i])!=0; i++){
111037         if( IdChar(c) ){
111038           n++;
111039 #ifndef SQLITE_OMIT_TCL_VARIABLE
111040         }else if( c=='(' && n>0 ){
111041           do{
111042             i++;
111043           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
111044           if( c==')' ){
111045             i++;
111046           }else{
111047             *tokenType = TK_ILLEGAL;
111048           }
111049           break;
111050         }else if( c==':' && z[i+1]==':' ){
111051           i++;
111052 #endif
111053         }else{
111054           break;
111055         }
111056       }
111057       if( n==0 ) *tokenType = TK_ILLEGAL;
111058       return i;
111059     }
111060 #ifndef SQLITE_OMIT_BLOB_LITERAL
111061     case 'x': case 'X': {
111062       testcase( z[0]=='x' ); testcase( z[0]=='X' );
111063       if( z[1]=='\'' ){
111064         *tokenType = TK_BLOB;
111065         for(i=2; sqlite3Isxdigit(z[i]); i++){}
111066         if( z[i]!='\'' || i%2 ){
111067           *tokenType = TK_ILLEGAL;
111068           while( z[i] && z[i]!='\'' ){ i++; }
111069         }
111070         if( z[i] ) i++;
111071         return i;
111072       }
111073       /* Otherwise fall through to the next case */
111074     }
111075 #endif
111076     default: {
111077       if( !IdChar(*z) ){
111078         break;
111079       }
111080       for(i=1; IdChar(z[i]); i++){}
111081       *tokenType = keywordCode((char*)z, i);
111082       return i;
111083     }
111084   }
111085   *tokenType = TK_ILLEGAL;
111086   return 1;
111087 }
111088
111089 /*
111090 ** Run the parser on the given SQL string.  The parser structure is
111091 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
111092 ** then an and attempt is made to write an error message into 
111093 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
111094 ** error message.
111095 */
111096 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
111097   int nErr = 0;                   /* Number of errors encountered */
111098   int i;                          /* Loop counter */
111099   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
111100   int tokenType;                  /* type of the next token */
111101   int lastTokenParsed = -1;       /* type of the previous token */
111102   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
111103   sqlite3 *db = pParse->db;       /* The database connection */
111104   int mxSqlLen;                   /* Max length of an SQL string */
111105
111106
111107   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
111108   if( db->activeVdbeCnt==0 ){
111109     db->u1.isInterrupted = 0;
111110   }
111111   pParse->rc = SQLITE_OK;
111112   pParse->zTail = zSql;
111113   i = 0;
111114   assert( pzErrMsg!=0 );
111115   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
111116   if( pEngine==0 ){
111117     db->mallocFailed = 1;
111118     return SQLITE_NOMEM;
111119   }
111120   assert( pParse->pNewTable==0 );
111121   assert( pParse->pNewTrigger==0 );
111122   assert( pParse->nVar==0 );
111123   assert( pParse->nzVar==0 );
111124   assert( pParse->azVar==0 );
111125   enableLookaside = db->lookaside.bEnabled;
111126   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
111127   while( !db->mallocFailed && zSql[i]!=0 ){
111128     assert( i>=0 );
111129     pParse->sLastToken.z = &zSql[i];
111130     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
111131     i += pParse->sLastToken.n;
111132     if( i>mxSqlLen ){
111133       pParse->rc = SQLITE_TOOBIG;
111134       break;
111135     }
111136     switch( tokenType ){
111137       case TK_SPACE: {
111138         if( db->u1.isInterrupted ){
111139           sqlite3ErrorMsg(pParse, "interrupt");
111140           pParse->rc = SQLITE_INTERRUPT;
111141           goto abort_parse;
111142         }
111143         break;
111144       }
111145       case TK_ILLEGAL: {
111146         sqlite3DbFree(db, *pzErrMsg);
111147         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
111148                         &pParse->sLastToken);
111149         nErr++;
111150         goto abort_parse;
111151       }
111152       case TK_SEMI: {
111153         pParse->zTail = &zSql[i];
111154         /* Fall thru into the default case */
111155       }
111156       default: {
111157         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
111158         lastTokenParsed = tokenType;
111159         if( pParse->rc!=SQLITE_OK ){
111160           goto abort_parse;
111161         }
111162         break;
111163       }
111164     }
111165   }
111166 abort_parse:
111167   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
111168     if( lastTokenParsed!=TK_SEMI ){
111169       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
111170       pParse->zTail = &zSql[i];
111171     }
111172     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
111173   }
111174 #ifdef YYTRACKMAXSTACKDEPTH
111175   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
111176       sqlite3ParserStackPeak(pEngine)
111177   );
111178 #endif /* YYDEBUG */
111179   sqlite3ParserFree(pEngine, sqlite3_free);
111180   db->lookaside.bEnabled = enableLookaside;
111181   if( db->mallocFailed ){
111182     pParse->rc = SQLITE_NOMEM;
111183   }
111184   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
111185     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
111186   }
111187   assert( pzErrMsg!=0 );
111188   if( pParse->zErrMsg ){
111189     *pzErrMsg = pParse->zErrMsg;
111190     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
111191     pParse->zErrMsg = 0;
111192     nErr++;
111193   }
111194   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
111195     sqlite3VdbeDelete(pParse->pVdbe);
111196     pParse->pVdbe = 0;
111197   }
111198 #ifndef SQLITE_OMIT_SHARED_CACHE
111199   if( pParse->nested==0 ){
111200     sqlite3DbFree(db, pParse->aTableLock);
111201     pParse->aTableLock = 0;
111202     pParse->nTableLock = 0;
111203   }
111204 #endif
111205 #ifndef SQLITE_OMIT_VIRTUALTABLE
111206   sqlite3_free(pParse->apVtabLock);
111207 #endif
111208
111209   if( !IN_DECLARE_VTAB ){
111210     /* If the pParse->declareVtab flag is set, do not delete any table 
111211     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
111212     ** will take responsibility for freeing the Table structure.
111213     */
111214     sqlite3DeleteTable(db, pParse->pNewTable);
111215   }
111216
111217   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
111218   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
111219   sqlite3DbFree(db, pParse->azVar);
111220   sqlite3DbFree(db, pParse->aAlias);
111221   while( pParse->pAinc ){
111222     AutoincInfo *p = pParse->pAinc;
111223     pParse->pAinc = p->pNext;
111224     sqlite3DbFree(db, p);
111225   }
111226   while( pParse->pZombieTab ){
111227     Table *p = pParse->pZombieTab;
111228     pParse->pZombieTab = p->pNextZombie;
111229     sqlite3DeleteTable(db, p);
111230   }
111231   if( nErr>0 && pParse->rc==SQLITE_OK ){
111232     pParse->rc = SQLITE_ERROR;
111233   }
111234   return nErr;
111235 }
111236
111237 /************** End of tokenize.c ********************************************/
111238 /************** Begin file complete.c ****************************************/
111239 /*
111240 ** 2001 September 15
111241 **
111242 ** The author disclaims copyright to this source code.  In place of
111243 ** a legal notice, here is a blessing:
111244 **
111245 **    May you do good and not evil.
111246 **    May you find forgiveness for yourself and forgive others.
111247 **    May you share freely, never taking more than you give.
111248 **
111249 *************************************************************************
111250 ** An tokenizer for SQL
111251 **
111252 ** This file contains C code that implements the sqlite3_complete() API.
111253 ** This code used to be part of the tokenizer.c source file.  But by
111254 ** separating it out, the code will be automatically omitted from
111255 ** static links that do not use it.
111256 */
111257 #ifndef SQLITE_OMIT_COMPLETE
111258
111259 /*
111260 ** This is defined in tokenize.c.  We just have to import the definition.
111261 */
111262 #ifndef SQLITE_AMALGAMATION
111263 #ifdef SQLITE_ASCII
111264 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
111265 #endif
111266 #ifdef SQLITE_EBCDIC
111267 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
111268 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
111269 #endif
111270 #endif /* SQLITE_AMALGAMATION */
111271
111272
111273 /*
111274 ** Token types used by the sqlite3_complete() routine.  See the header
111275 ** comments on that procedure for additional information.
111276 */
111277 #define tkSEMI    0
111278 #define tkWS      1
111279 #define tkOTHER   2
111280 #ifndef SQLITE_OMIT_TRIGGER
111281 #define tkEXPLAIN 3
111282 #define tkCREATE  4
111283 #define tkTEMP    5
111284 #define tkTRIGGER 6
111285 #define tkEND     7
111286 #endif
111287
111288 /*
111289 ** Return TRUE if the given SQL string ends in a semicolon.
111290 **
111291 ** Special handling is require for CREATE TRIGGER statements.
111292 ** Whenever the CREATE TRIGGER keywords are seen, the statement
111293 ** must end with ";END;".
111294 **
111295 ** This implementation uses a state machine with 8 states:
111296 **
111297 **   (0) INVALID   We have not yet seen a non-whitespace character.
111298 **
111299 **   (1) START     At the beginning or end of an SQL statement.  This routine
111300 **                 returns 1 if it ends in the START state and 0 if it ends
111301 **                 in any other state.
111302 **
111303 **   (2) NORMAL    We are in the middle of statement which ends with a single
111304 **                 semicolon.
111305 **
111306 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
111307 **                 a statement.
111308 **
111309 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
111310 **                 statement, possibly preceeded by EXPLAIN and/or followed by
111311 **                 TEMP or TEMPORARY
111312 **
111313 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
111314 **                 ended by a semicolon, the keyword END, and another semicolon.
111315 **
111316 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
111317 **                 the end of a trigger definition.
111318 **
111319 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
111320 **                 of a trigger difinition.
111321 **
111322 ** Transitions between states above are determined by tokens extracted
111323 ** from the input.  The following tokens are significant:
111324 **
111325 **   (0) tkSEMI      A semicolon.
111326 **   (1) tkWS        Whitespace.
111327 **   (2) tkOTHER     Any other SQL token.
111328 **   (3) tkEXPLAIN   The "explain" keyword.
111329 **   (4) tkCREATE    The "create" keyword.
111330 **   (5) tkTEMP      The "temp" or "temporary" keyword.
111331 **   (6) tkTRIGGER   The "trigger" keyword.
111332 **   (7) tkEND       The "end" keyword.
111333 **
111334 ** Whitespace never causes a state transition and is always ignored.
111335 ** This means that a SQL string of all whitespace is invalid.
111336 **
111337 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
111338 ** to recognize the end of a trigger can be omitted.  All we have to do
111339 ** is look for a semicolon that is not part of an string or comment.
111340 */
111341 SQLITE_API int sqlite3_complete(const char *zSql){
111342   u8 state = 0;   /* Current state, using numbers defined in header comment */
111343   u8 token;       /* Value of the next token */
111344
111345 #ifndef SQLITE_OMIT_TRIGGER
111346   /* A complex statement machine used to detect the end of a CREATE TRIGGER
111347   ** statement.  This is the normal case.
111348   */
111349   static const u8 trans[8][8] = {
111350                      /* Token:                                                */
111351      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
111352      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
111353      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
111354      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
111355      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
111356      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
111357      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
111358      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
111359      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
111360   };
111361 #else
111362   /* If triggers are not supported by this compile then the statement machine
111363   ** used to detect the end of a statement is much simplier
111364   */
111365   static const u8 trans[3][3] = {
111366                      /* Token:           */
111367      /* State:       **  SEMI  WS  OTHER */
111368      /* 0 INVALID: */ {    1,  0,     2, },
111369      /* 1   START: */ {    1,  1,     2, },
111370      /* 2  NORMAL: */ {    1,  2,     2, },
111371   };
111372 #endif /* SQLITE_OMIT_TRIGGER */
111373
111374   while( *zSql ){
111375     switch( *zSql ){
111376       case ';': {  /* A semicolon */
111377         token = tkSEMI;
111378         break;
111379       }
111380       case ' ':
111381       case '\r':
111382       case '\t':
111383       case '\n':
111384       case '\f': {  /* White space is ignored */
111385         token = tkWS;
111386         break;
111387       }
111388       case '/': {   /* C-style comments */
111389         if( zSql[1]!='*' ){
111390           token = tkOTHER;
111391           break;
111392         }
111393         zSql += 2;
111394         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
111395         if( zSql[0]==0 ) return 0;
111396         zSql++;
111397         token = tkWS;
111398         break;
111399       }
111400       case '-': {   /* SQL-style comments from "--" to end of line */
111401         if( zSql[1]!='-' ){
111402           token = tkOTHER;
111403           break;
111404         }
111405         while( *zSql && *zSql!='\n' ){ zSql++; }
111406         if( *zSql==0 ) return state==1;
111407         token = tkWS;
111408         break;
111409       }
111410       case '[': {   /* Microsoft-style identifiers in [...] */
111411         zSql++;
111412         while( *zSql && *zSql!=']' ){ zSql++; }
111413         if( *zSql==0 ) return 0;
111414         token = tkOTHER;
111415         break;
111416       }
111417       case '`':     /* Grave-accent quoted symbols used by MySQL */
111418       case '"':     /* single- and double-quoted strings */
111419       case '\'': {
111420         int c = *zSql;
111421         zSql++;
111422         while( *zSql && *zSql!=c ){ zSql++; }
111423         if( *zSql==0 ) return 0;
111424         token = tkOTHER;
111425         break;
111426       }
111427       default: {
111428 #ifdef SQLITE_EBCDIC
111429         unsigned char c;
111430 #endif
111431         if( IdChar((u8)*zSql) ){
111432           /* Keywords and unquoted identifiers */
111433           int nId;
111434           for(nId=1; IdChar(zSql[nId]); nId++){}
111435 #ifdef SQLITE_OMIT_TRIGGER
111436           token = tkOTHER;
111437 #else
111438           switch( *zSql ){
111439             case 'c': case 'C': {
111440               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
111441                 token = tkCREATE;
111442               }else{
111443                 token = tkOTHER;
111444               }
111445               break;
111446             }
111447             case 't': case 'T': {
111448               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
111449                 token = tkTRIGGER;
111450               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
111451                 token = tkTEMP;
111452               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
111453                 token = tkTEMP;
111454               }else{
111455                 token = tkOTHER;
111456               }
111457               break;
111458             }
111459             case 'e':  case 'E': {
111460               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
111461                 token = tkEND;
111462               }else
111463 #ifndef SQLITE_OMIT_EXPLAIN
111464               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
111465                 token = tkEXPLAIN;
111466               }else
111467 #endif
111468               {
111469                 token = tkOTHER;
111470               }
111471               break;
111472             }
111473             default: {
111474               token = tkOTHER;
111475               break;
111476             }
111477           }
111478 #endif /* SQLITE_OMIT_TRIGGER */
111479           zSql += nId-1;
111480         }else{
111481           /* Operators and special symbols */
111482           token = tkOTHER;
111483         }
111484         break;
111485       }
111486     }
111487     state = trans[state][token];
111488     zSql++;
111489   }
111490   return state==1;
111491 }
111492
111493 #ifndef SQLITE_OMIT_UTF16
111494 /*
111495 ** This routine is the same as the sqlite3_complete() routine described
111496 ** above, except that the parameter is required to be UTF-16 encoded, not
111497 ** UTF-8.
111498 */
111499 SQLITE_API int sqlite3_complete16(const void *zSql){
111500   sqlite3_value *pVal;
111501   char const *zSql8;
111502   int rc = SQLITE_NOMEM;
111503
111504 #ifndef SQLITE_OMIT_AUTOINIT
111505   rc = sqlite3_initialize();
111506   if( rc ) return rc;
111507 #endif
111508   pVal = sqlite3ValueNew(0);
111509   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
111510   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
111511   if( zSql8 ){
111512     rc = sqlite3_complete(zSql8);
111513   }else{
111514     rc = SQLITE_NOMEM;
111515   }
111516   sqlite3ValueFree(pVal);
111517   return sqlite3ApiExit(0, rc);
111518 }
111519 #endif /* SQLITE_OMIT_UTF16 */
111520 #endif /* SQLITE_OMIT_COMPLETE */
111521
111522 /************** End of complete.c ********************************************/
111523 /************** Begin file main.c ********************************************/
111524 /*
111525 ** 2001 September 15
111526 **
111527 ** The author disclaims copyright to this source code.  In place of
111528 ** a legal notice, here is a blessing:
111529 **
111530 **    May you do good and not evil.
111531 **    May you find forgiveness for yourself and forgive others.
111532 **    May you share freely, never taking more than you give.
111533 **
111534 *************************************************************************
111535 ** Main file for the SQLite library.  The routines in this file
111536 ** implement the programmer interface to the library.  Routines in
111537 ** other files are for internal use by SQLite and should not be
111538 ** accessed by users of the library.
111539 */
111540
111541 #ifdef SQLITE_ENABLE_FTS3
111542 /************** Include fts3.h in the middle of main.c ***********************/
111543 /************** Begin file fts3.h ********************************************/
111544 /*
111545 ** 2006 Oct 10
111546 **
111547 ** The author disclaims copyright to this source code.  In place of
111548 ** a legal notice, here is a blessing:
111549 **
111550 **    May you do good and not evil.
111551 **    May you find forgiveness for yourself and forgive others.
111552 **    May you share freely, never taking more than you give.
111553 **
111554 ******************************************************************************
111555 **
111556 ** This header file is used by programs that want to link against the
111557 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
111558 */
111559
111560 #if 0
111561 extern "C" {
111562 #endif  /* __cplusplus */
111563
111564 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
111565
111566 #if 0
111567 }  /* extern "C" */
111568 #endif  /* __cplusplus */
111569
111570 /************** End of fts3.h ************************************************/
111571 /************** Continuing where we left off in main.c ***********************/
111572 #endif
111573 #ifdef SQLITE_ENABLE_RTREE
111574 /************** Include rtree.h in the middle of main.c **********************/
111575 /************** Begin file rtree.h *******************************************/
111576 /*
111577 ** 2008 May 26
111578 **
111579 ** The author disclaims copyright to this source code.  In place of
111580 ** a legal notice, here is a blessing:
111581 **
111582 **    May you do good and not evil.
111583 **    May you find forgiveness for yourself and forgive others.
111584 **    May you share freely, never taking more than you give.
111585 **
111586 ******************************************************************************
111587 **
111588 ** This header file is used by programs that want to link against the
111589 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
111590 */
111591
111592 #if 0
111593 extern "C" {
111594 #endif  /* __cplusplus */
111595
111596 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
111597
111598 #if 0
111599 }  /* extern "C" */
111600 #endif  /* __cplusplus */
111601
111602 /************** End of rtree.h ***********************************************/
111603 /************** Continuing where we left off in main.c ***********************/
111604 #endif
111605 #ifdef SQLITE_ENABLE_ICU
111606 /************** Include sqliteicu.h in the middle of main.c ******************/
111607 /************** Begin file sqliteicu.h ***************************************/
111608 /*
111609 ** 2008 May 26
111610 **
111611 ** The author disclaims copyright to this source code.  In place of
111612 ** a legal notice, here is a blessing:
111613 **
111614 **    May you do good and not evil.
111615 **    May you find forgiveness for yourself and forgive others.
111616 **    May you share freely, never taking more than you give.
111617 **
111618 ******************************************************************************
111619 **
111620 ** This header file is used by programs that want to link against the
111621 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
111622 */
111623
111624 #if 0
111625 extern "C" {
111626 #endif  /* __cplusplus */
111627
111628 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
111629
111630 #if 0
111631 }  /* extern "C" */
111632 #endif  /* __cplusplus */
111633
111634
111635 /************** End of sqliteicu.h *******************************************/
111636 /************** Continuing where we left off in main.c ***********************/
111637 #endif
111638
111639 #ifndef SQLITE_AMALGAMATION
111640 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
111641 ** contains the text of SQLITE_VERSION macro. 
111642 */
111643 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
111644 #endif
111645
111646 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
111647 ** a pointer to the to the sqlite3_version[] string constant. 
111648 */
111649 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
111650
111651 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
111652 ** pointer to a string constant whose value is the same as the
111653 ** SQLITE_SOURCE_ID C preprocessor macro. 
111654 */
111655 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
111656
111657 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
111658 ** returns an integer equal to SQLITE_VERSION_NUMBER.
111659 */
111660 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
111661
111662 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
111663 ** zero if and only if SQLite was compiled with mutexing code omitted due to
111664 ** the SQLITE_THREADSAFE compile-time option being set to 0.
111665 */
111666 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
111667
111668 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
111669 /*
111670 ** If the following function pointer is not NULL and if
111671 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
111672 ** I/O active are written using this function.  These messages
111673 ** are intended for debugging activity only.
111674 */
111675 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
111676 #endif
111677
111678 /*
111679 ** If the following global variable points to a string which is the
111680 ** name of a directory, then that directory will be used to store
111681 ** temporary files.
111682 **
111683 ** See also the "PRAGMA temp_store_directory" SQL command.
111684 */
111685 SQLITE_API char *sqlite3_temp_directory = 0;
111686
111687 /*
111688 ** If the following global variable points to a string which is the
111689 ** name of a directory, then that directory will be used to store
111690 ** all database files specified with a relative pathname.
111691 **
111692 ** See also the "PRAGMA data_store_directory" SQL command.
111693 */
111694 SQLITE_API char *sqlite3_data_directory = 0;
111695
111696 /*
111697 ** Initialize SQLite.  
111698 **
111699 ** This routine must be called to initialize the memory allocation,
111700 ** VFS, and mutex subsystems prior to doing any serious work with
111701 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
111702 ** this routine will be called automatically by key routines such as
111703 ** sqlite3_open().  
111704 **
111705 ** This routine is a no-op except on its very first call for the process,
111706 ** or for the first call after a call to sqlite3_shutdown.
111707 **
111708 ** The first thread to call this routine runs the initialization to
111709 ** completion.  If subsequent threads call this routine before the first
111710 ** thread has finished the initialization process, then the subsequent
111711 ** threads must block until the first thread finishes with the initialization.
111712 **
111713 ** The first thread might call this routine recursively.  Recursive
111714 ** calls to this routine should not block, of course.  Otherwise the
111715 ** initialization process would never complete.
111716 **
111717 ** Let X be the first thread to enter this routine.  Let Y be some other
111718 ** thread.  Then while the initial invocation of this routine by X is
111719 ** incomplete, it is required that:
111720 **
111721 **    *  Calls to this routine from Y must block until the outer-most
111722 **       call by X completes.
111723 **
111724 **    *  Recursive calls to this routine from thread X return immediately
111725 **       without blocking.
111726 */
111727 SQLITE_API int sqlite3_initialize(void){
111728   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
111729   int rc;                                      /* Result code */
111730
111731 #ifdef SQLITE_OMIT_WSD
111732   rc = sqlite3_wsd_init(4096, 24);
111733   if( rc!=SQLITE_OK ){
111734     return rc;
111735   }
111736 #endif
111737
111738   /* If SQLite is already completely initialized, then this call
111739   ** to sqlite3_initialize() should be a no-op.  But the initialization
111740   ** must be complete.  So isInit must not be set until the very end
111741   ** of this routine.
111742   */
111743   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
111744
111745   /* Make sure the mutex subsystem is initialized.  If unable to 
111746   ** initialize the mutex subsystem, return early with the error.
111747   ** If the system is so sick that we are unable to allocate a mutex,
111748   ** there is not much SQLite is going to be able to do.
111749   **
111750   ** The mutex subsystem must take care of serializing its own
111751   ** initialization.
111752   */
111753   rc = sqlite3MutexInit();
111754   if( rc ) return rc;
111755
111756   /* Initialize the malloc() system and the recursive pInitMutex mutex.
111757   ** This operation is protected by the STATIC_MASTER mutex.  Note that
111758   ** MutexAlloc() is called for a static mutex prior to initializing the
111759   ** malloc subsystem - this implies that the allocation of a static
111760   ** mutex must not require support from the malloc subsystem.
111761   */
111762   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
111763   sqlite3_mutex_enter(pMaster);
111764   sqlite3GlobalConfig.isMutexInit = 1;
111765   if( !sqlite3GlobalConfig.isMallocInit ){
111766     rc = sqlite3MallocInit();
111767   }
111768   if( rc==SQLITE_OK ){
111769     sqlite3GlobalConfig.isMallocInit = 1;
111770     if( !sqlite3GlobalConfig.pInitMutex ){
111771       sqlite3GlobalConfig.pInitMutex =
111772            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
111773       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
111774         rc = SQLITE_NOMEM;
111775       }
111776     }
111777   }
111778   if( rc==SQLITE_OK ){
111779     sqlite3GlobalConfig.nRefInitMutex++;
111780   }
111781   sqlite3_mutex_leave(pMaster);
111782
111783   /* If rc is not SQLITE_OK at this point, then either the malloc
111784   ** subsystem could not be initialized or the system failed to allocate
111785   ** the pInitMutex mutex. Return an error in either case.  */
111786   if( rc!=SQLITE_OK ){
111787     return rc;
111788   }
111789
111790   /* Do the rest of the initialization under the recursive mutex so
111791   ** that we will be able to handle recursive calls into
111792   ** sqlite3_initialize().  The recursive calls normally come through
111793   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
111794   ** recursive calls might also be possible.
111795   **
111796   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
111797   ** to the xInit method, so the xInit method need not be threadsafe.
111798   **
111799   ** The following mutex is what serializes access to the appdef pcache xInit
111800   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
111801   ** call to sqlite3PcacheInitialize().
111802   */
111803   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
111804   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
111805     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
111806     sqlite3GlobalConfig.inProgress = 1;
111807     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
111808     sqlite3RegisterGlobalFunctions();
111809     if( sqlite3GlobalConfig.isPCacheInit==0 ){
111810       rc = sqlite3PcacheInitialize();
111811     }
111812     if( rc==SQLITE_OK ){
111813       sqlite3GlobalConfig.isPCacheInit = 1;
111814       rc = sqlite3OsInit();
111815     }
111816     if( rc==SQLITE_OK ){
111817       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
111818           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
111819       sqlite3GlobalConfig.isInit = 1;
111820     }
111821     sqlite3GlobalConfig.inProgress = 0;
111822   }
111823   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
111824
111825   /* Go back under the static mutex and clean up the recursive
111826   ** mutex to prevent a resource leak.
111827   */
111828   sqlite3_mutex_enter(pMaster);
111829   sqlite3GlobalConfig.nRefInitMutex--;
111830   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
111831     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
111832     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
111833     sqlite3GlobalConfig.pInitMutex = 0;
111834   }
111835   sqlite3_mutex_leave(pMaster);
111836
111837   /* The following is just a sanity check to make sure SQLite has
111838   ** been compiled correctly.  It is important to run this code, but
111839   ** we don't want to run it too often and soak up CPU cycles for no
111840   ** reason.  So we run it once during initialization.
111841   */
111842 #ifndef NDEBUG
111843 #ifndef SQLITE_OMIT_FLOATING_POINT
111844   /* This section of code's only "output" is via assert() statements. */
111845   if ( rc==SQLITE_OK ){
111846     u64 x = (((u64)1)<<63)-1;
111847     double y;
111848     assert(sizeof(x)==8);
111849     assert(sizeof(x)==sizeof(y));
111850     memcpy(&y, &x, 8);
111851     assert( sqlite3IsNaN(y) );
111852   }
111853 #endif
111854 #endif
111855
111856   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
111857   ** compile-time option.
111858   */
111859 #ifdef SQLITE_EXTRA_INIT
111860   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
111861     int SQLITE_EXTRA_INIT(const char*);
111862     rc = SQLITE_EXTRA_INIT(0);
111863   }
111864 #endif
111865
111866   return rc;
111867 }
111868
111869 /*
111870 ** Undo the effects of sqlite3_initialize().  Must not be called while
111871 ** there are outstanding database connections or memory allocations or
111872 ** while any part of SQLite is otherwise in use in any thread.  This
111873 ** routine is not threadsafe.  But it is safe to invoke this routine
111874 ** on when SQLite is already shut down.  If SQLite is already shut down
111875 ** when this routine is invoked, then this routine is a harmless no-op.
111876 */
111877 SQLITE_API int sqlite3_shutdown(void){
111878   if( sqlite3GlobalConfig.isInit ){
111879 #ifdef SQLITE_EXTRA_SHUTDOWN
111880     void SQLITE_EXTRA_SHUTDOWN(void);
111881     SQLITE_EXTRA_SHUTDOWN();
111882 #endif
111883     sqlite3_os_end();
111884     sqlite3_reset_auto_extension();
111885     sqlite3GlobalConfig.isInit = 0;
111886   }
111887   if( sqlite3GlobalConfig.isPCacheInit ){
111888     sqlite3PcacheShutdown();
111889     sqlite3GlobalConfig.isPCacheInit = 0;
111890   }
111891   if( sqlite3GlobalConfig.isMallocInit ){
111892     sqlite3MallocEnd();
111893     sqlite3GlobalConfig.isMallocInit = 0;
111894
111895 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
111896     /* The heap subsystem has now been shutdown and these values are supposed
111897     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
111898     ** which would rely on that heap subsystem; therefore, make sure these
111899     ** values cannot refer to heap memory that was just invalidated when the
111900     ** heap subsystem was shutdown.  This is only done if the current call to
111901     ** this function resulted in the heap subsystem actually being shutdown.
111902     */
111903     sqlite3_data_directory = 0;
111904     sqlite3_temp_directory = 0;
111905 #endif
111906   }
111907   if( sqlite3GlobalConfig.isMutexInit ){
111908     sqlite3MutexEnd();
111909     sqlite3GlobalConfig.isMutexInit = 0;
111910   }
111911
111912   return SQLITE_OK;
111913 }
111914
111915 /*
111916 ** This API allows applications to modify the global configuration of
111917 ** the SQLite library at run-time.
111918 **
111919 ** This routine should only be called when there are no outstanding
111920 ** database connections or memory allocations.  This routine is not
111921 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
111922 ** behavior.
111923 */
111924 SQLITE_API int sqlite3_config(int op, ...){
111925   va_list ap;
111926   int rc = SQLITE_OK;
111927
111928   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
111929   ** the SQLite library is in use. */
111930   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
111931
111932   va_start(ap, op);
111933   switch( op ){
111934
111935     /* Mutex configuration options are only available in a threadsafe
111936     ** compile. 
111937     */
111938 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
111939     case SQLITE_CONFIG_SINGLETHREAD: {
111940       /* Disable all mutexing */
111941       sqlite3GlobalConfig.bCoreMutex = 0;
111942       sqlite3GlobalConfig.bFullMutex = 0;
111943       break;
111944     }
111945     case SQLITE_CONFIG_MULTITHREAD: {
111946       /* Disable mutexing of database connections */
111947       /* Enable mutexing of core data structures */
111948       sqlite3GlobalConfig.bCoreMutex = 1;
111949       sqlite3GlobalConfig.bFullMutex = 0;
111950       break;
111951     }
111952     case SQLITE_CONFIG_SERIALIZED: {
111953       /* Enable all mutexing */
111954       sqlite3GlobalConfig.bCoreMutex = 1;
111955       sqlite3GlobalConfig.bFullMutex = 1;
111956       break;
111957     }
111958     case SQLITE_CONFIG_MUTEX: {
111959       /* Specify an alternative mutex implementation */
111960       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
111961       break;
111962     }
111963     case SQLITE_CONFIG_GETMUTEX: {
111964       /* Retrieve the current mutex implementation */
111965       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
111966       break;
111967     }
111968 #endif
111969
111970
111971     case SQLITE_CONFIG_MALLOC: {
111972       /* Specify an alternative malloc implementation */
111973       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
111974       break;
111975     }
111976     case SQLITE_CONFIG_GETMALLOC: {
111977       /* Retrieve the current malloc() implementation */
111978       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
111979       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
111980       break;
111981     }
111982     case SQLITE_CONFIG_MEMSTATUS: {
111983       /* Enable or disable the malloc status collection */
111984       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
111985       break;
111986     }
111987     case SQLITE_CONFIG_SCRATCH: {
111988       /* Designate a buffer for scratch memory space */
111989       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
111990       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
111991       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
111992       break;
111993     }
111994     case SQLITE_CONFIG_PAGECACHE: {
111995       /* Designate a buffer for page cache memory space */
111996       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
111997       sqlite3GlobalConfig.szPage = va_arg(ap, int);
111998       sqlite3GlobalConfig.nPage = va_arg(ap, int);
111999       break;
112000     }
112001
112002     case SQLITE_CONFIG_PCACHE: {
112003       /* no-op */
112004       break;
112005     }
112006     case SQLITE_CONFIG_GETPCACHE: {
112007       /* now an error */
112008       rc = SQLITE_ERROR;
112009       break;
112010     }
112011
112012     case SQLITE_CONFIG_PCACHE2: {
112013       /* Specify an alternative page cache implementation */
112014       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
112015       break;
112016     }
112017     case SQLITE_CONFIG_GETPCACHE2: {
112018       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
112019         sqlite3PCacheSetDefault();
112020       }
112021       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
112022       break;
112023     }
112024
112025 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
112026     case SQLITE_CONFIG_HEAP: {
112027       /* Designate a buffer for heap memory space */
112028       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
112029       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
112030       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
112031
112032       if( sqlite3GlobalConfig.mnReq<1 ){
112033         sqlite3GlobalConfig.mnReq = 1;
112034       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
112035         /* cap min request size at 2^12 */
112036         sqlite3GlobalConfig.mnReq = (1<<12);
112037       }
112038
112039       if( sqlite3GlobalConfig.pHeap==0 ){
112040         /* If the heap pointer is NULL, then restore the malloc implementation
112041         ** back to NULL pointers too.  This will cause the malloc to go
112042         ** back to its default implementation when sqlite3_initialize() is
112043         ** run.
112044         */
112045         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
112046       }else{
112047         /* The heap pointer is not NULL, then install one of the
112048         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
112049         ** ENABLE_MEMSYS5 is defined, return an error.
112050         */
112051 #ifdef SQLITE_ENABLE_MEMSYS3
112052         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
112053 #endif
112054 #ifdef SQLITE_ENABLE_MEMSYS5
112055         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
112056 #endif
112057       }
112058       break;
112059     }
112060 #endif
112061
112062     case SQLITE_CONFIG_LOOKASIDE: {
112063       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
112064       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
112065       break;
112066     }
112067     
112068     /* Record a pointer to the logger funcction and its first argument.
112069     ** The default is NULL.  Logging is disabled if the function pointer is
112070     ** NULL.
112071     */
112072     case SQLITE_CONFIG_LOG: {
112073       /* MSVC is picky about pulling func ptrs from va lists.
112074       ** http://support.microsoft.com/kb/47961
112075       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
112076       */
112077       typedef void(*LOGFUNC_t)(void*,int,const char*);
112078       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
112079       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
112080       break;
112081     }
112082
112083     case SQLITE_CONFIG_URI: {
112084       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
112085       break;
112086     }
112087
112088     default: {
112089       rc = SQLITE_ERROR;
112090       break;
112091     }
112092   }
112093   va_end(ap);
112094   return rc;
112095 }
112096
112097 /*
112098 ** Set up the lookaside buffers for a database connection.
112099 ** Return SQLITE_OK on success.  
112100 ** If lookaside is already active, return SQLITE_BUSY.
112101 **
112102 ** The sz parameter is the number of bytes in each lookaside slot.
112103 ** The cnt parameter is the number of slots.  If pStart is NULL the
112104 ** space for the lookaside memory is obtained from sqlite3_malloc().
112105 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
112106 ** the lookaside memory.
112107 */
112108 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
112109   void *pStart;
112110   if( db->lookaside.nOut ){
112111     return SQLITE_BUSY;
112112   }
112113   /* Free any existing lookaside buffer for this handle before
112114   ** allocating a new one so we don't have to have space for 
112115   ** both at the same time.
112116   */
112117   if( db->lookaside.bMalloced ){
112118     sqlite3_free(db->lookaside.pStart);
112119   }
112120   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
112121   ** than a pointer to be useful.
112122   */
112123   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
112124   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
112125   if( cnt<0 ) cnt = 0;
112126   if( sz==0 || cnt==0 ){
112127     sz = 0;
112128     pStart = 0;
112129   }else if( pBuf==0 ){
112130     sqlite3BeginBenignMalloc();
112131     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
112132     sqlite3EndBenignMalloc();
112133     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
112134   }else{
112135     pStart = pBuf;
112136   }
112137   db->lookaside.pStart = pStart;
112138   db->lookaside.pFree = 0;
112139   db->lookaside.sz = (u16)sz;
112140   if( pStart ){
112141     int i;
112142     LookasideSlot *p;
112143     assert( sz > (int)sizeof(LookasideSlot*) );
112144     p = (LookasideSlot*)pStart;
112145     for(i=cnt-1; i>=0; i--){
112146       p->pNext = db->lookaside.pFree;
112147       db->lookaside.pFree = p;
112148       p = (LookasideSlot*)&((u8*)p)[sz];
112149     }
112150     db->lookaside.pEnd = p;
112151     db->lookaside.bEnabled = 1;
112152     db->lookaside.bMalloced = pBuf==0 ?1:0;
112153   }else{
112154     db->lookaside.pEnd = 0;
112155     db->lookaside.bEnabled = 0;
112156     db->lookaside.bMalloced = 0;
112157   }
112158   return SQLITE_OK;
112159 }
112160
112161 /*
112162 ** Return the mutex associated with a database connection.
112163 */
112164 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
112165   return db->mutex;
112166 }
112167
112168 /*
112169 ** Free up as much memory as we can from the given database
112170 ** connection.
112171 */
112172 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
112173   int i;
112174   sqlite3_mutex_enter(db->mutex);
112175   sqlite3BtreeEnterAll(db);
112176   for(i=0; i<db->nDb; i++){
112177     Btree *pBt = db->aDb[i].pBt;
112178     if( pBt ){
112179       Pager *pPager = sqlite3BtreePager(pBt);
112180       sqlite3PagerShrink(pPager);
112181     }
112182   }
112183   sqlite3BtreeLeaveAll(db);
112184   sqlite3_mutex_leave(db->mutex);
112185   return SQLITE_OK;
112186 }
112187
112188 /*
112189 ** Configuration settings for an individual database connection
112190 */
112191 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
112192   va_list ap;
112193   int rc;
112194   va_start(ap, op);
112195   switch( op ){
112196     case SQLITE_DBCONFIG_LOOKASIDE: {
112197       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
112198       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
112199       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
112200       rc = setupLookaside(db, pBuf, sz, cnt);
112201       break;
112202     }
112203     default: {
112204       static const struct {
112205         int op;      /* The opcode */
112206         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
112207       } aFlagOp[] = {
112208         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
112209         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
112210       };
112211       unsigned int i;
112212       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
112213       for(i=0; i<ArraySize(aFlagOp); i++){
112214         if( aFlagOp[i].op==op ){
112215           int onoff = va_arg(ap, int);
112216           int *pRes = va_arg(ap, int*);
112217           int oldFlags = db->flags;
112218           if( onoff>0 ){
112219             db->flags |= aFlagOp[i].mask;
112220           }else if( onoff==0 ){
112221             db->flags &= ~aFlagOp[i].mask;
112222           }
112223           if( oldFlags!=db->flags ){
112224             sqlite3ExpirePreparedStatements(db);
112225           }
112226           if( pRes ){
112227             *pRes = (db->flags & aFlagOp[i].mask)!=0;
112228           }
112229           rc = SQLITE_OK;
112230           break;
112231         }
112232       }
112233       break;
112234     }
112235   }
112236   va_end(ap);
112237   return rc;
112238 }
112239
112240
112241 /*
112242 ** Return true if the buffer z[0..n-1] contains all spaces.
112243 */
112244 static int allSpaces(const char *z, int n){
112245   while( n>0 && z[n-1]==' ' ){ n--; }
112246   return n==0;
112247 }
112248
112249 /*
112250 ** This is the default collating function named "BINARY" which is always
112251 ** available.
112252 **
112253 ** If the padFlag argument is not NULL then space padding at the end
112254 ** of strings is ignored.  This implements the RTRIM collation.
112255 */
112256 static int binCollFunc(
112257   void *padFlag,
112258   int nKey1, const void *pKey1,
112259   int nKey2, const void *pKey2
112260 ){
112261   int rc, n;
112262   n = nKey1<nKey2 ? nKey1 : nKey2;
112263   rc = memcmp(pKey1, pKey2, n);
112264   if( rc==0 ){
112265     if( padFlag
112266      && allSpaces(((char*)pKey1)+n, nKey1-n)
112267      && allSpaces(((char*)pKey2)+n, nKey2-n)
112268     ){
112269       /* Leave rc unchanged at 0 */
112270     }else{
112271       rc = nKey1 - nKey2;
112272     }
112273   }
112274   return rc;
112275 }
112276
112277 /*
112278 ** Another built-in collating sequence: NOCASE. 
112279 **
112280 ** This collating sequence is intended to be used for "case independant
112281 ** comparison". SQLite's knowledge of upper and lower case equivalents
112282 ** extends only to the 26 characters used in the English language.
112283 **
112284 ** At the moment there is only a UTF-8 implementation.
112285 */
112286 static int nocaseCollatingFunc(
112287   void *NotUsed,
112288   int nKey1, const void *pKey1,
112289   int nKey2, const void *pKey2
112290 ){
112291   int r = sqlite3StrNICmp(
112292       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
112293   UNUSED_PARAMETER(NotUsed);
112294   if( 0==r ){
112295     r = nKey1-nKey2;
112296   }
112297   return r;
112298 }
112299
112300 /*
112301 ** Return the ROWID of the most recent insert
112302 */
112303 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
112304   return db->lastRowid;
112305 }
112306
112307 /*
112308 ** Return the number of changes in the most recent call to sqlite3_exec().
112309 */
112310 SQLITE_API int sqlite3_changes(sqlite3 *db){
112311   return db->nChange;
112312 }
112313
112314 /*
112315 ** Return the number of changes since the database handle was opened.
112316 */
112317 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
112318   return db->nTotalChange;
112319 }
112320
112321 /*
112322 ** Close all open savepoints. This function only manipulates fields of the
112323 ** database handle object, it does not close any savepoints that may be open
112324 ** at the b-tree/pager level.
112325 */
112326 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
112327   while( db->pSavepoint ){
112328     Savepoint *pTmp = db->pSavepoint;
112329     db->pSavepoint = pTmp->pNext;
112330     sqlite3DbFree(db, pTmp);
112331   }
112332   db->nSavepoint = 0;
112333   db->nStatement = 0;
112334   db->isTransactionSavepoint = 0;
112335 }
112336
112337 /*
112338 ** Invoke the destructor function associated with FuncDef p, if any. Except,
112339 ** if this is not the last copy of the function, do not invoke it. Multiple
112340 ** copies of a single function are created when create_function() is called
112341 ** with SQLITE_ANY as the encoding.
112342 */
112343 static void functionDestroy(sqlite3 *db, FuncDef *p){
112344   FuncDestructor *pDestructor = p->pDestructor;
112345   if( pDestructor ){
112346     pDestructor->nRef--;
112347     if( pDestructor->nRef==0 ){
112348       pDestructor->xDestroy(pDestructor->pUserData);
112349       sqlite3DbFree(db, pDestructor);
112350     }
112351   }
112352 }
112353
112354 /*
112355 ** Disconnect all sqlite3_vtab objects that belong to database connection
112356 ** db. This is called when db is being closed.
112357 */
112358 static void disconnectAllVtab(sqlite3 *db){
112359 #ifndef SQLITE_OMIT_VIRTUALTABLE
112360   int i;
112361   sqlite3BtreeEnterAll(db);
112362   for(i=0; i<db->nDb; i++){
112363     Schema *pSchema = db->aDb[i].pSchema;
112364     if( db->aDb[i].pSchema ){
112365       HashElem *p;
112366       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
112367         Table *pTab = (Table *)sqliteHashData(p);
112368         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
112369       }
112370     }
112371   }
112372   sqlite3BtreeLeaveAll(db);
112373 #else
112374   UNUSED_PARAMETER(db);
112375 #endif
112376 }
112377
112378 /*
112379 ** Return TRUE if database connection db has unfinalized prepared
112380 ** statements or unfinished sqlite3_backup objects.  
112381 */
112382 static int connectionIsBusy(sqlite3 *db){
112383   int j;
112384   assert( sqlite3_mutex_held(db->mutex) );
112385   if( db->pVdbe ) return 1;
112386   for(j=0; j<db->nDb; j++){
112387     Btree *pBt = db->aDb[j].pBt;
112388     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
112389   }
112390   return 0;
112391 }
112392
112393 /*
112394 ** Close an existing SQLite database
112395 */
112396 static int sqlite3Close(sqlite3 *db, int forceZombie){
112397   if( !db ){
112398     return SQLITE_OK;
112399   }
112400   if( !sqlite3SafetyCheckSickOrOk(db) ){
112401     return SQLITE_MISUSE_BKPT;
112402   }
112403   sqlite3_mutex_enter(db->mutex);
112404
112405   /* Force xDisconnect calls on all virtual tables */
112406   disconnectAllVtab(db);
112407
112408   /* If a transaction is open, the disconnectAllVtab() call above
112409   ** will not have called the xDisconnect() method on any virtual
112410   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
112411   ** call will do so. We need to do this before the check for active
112412   ** SQL statements below, as the v-table implementation may be storing
112413   ** some prepared statements internally.
112414   */
112415   sqlite3VtabRollback(db);
112416
112417   /* Legacy behavior (sqlite3_close() behavior) is to return
112418   ** SQLITE_BUSY if the connection can not be closed immediately.
112419   */
112420   if( !forceZombie && connectionIsBusy(db) ){
112421     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
112422        "statements or unfinished backups");
112423     sqlite3_mutex_leave(db->mutex);
112424     return SQLITE_BUSY;
112425   }
112426
112427   /* Convert the connection into a zombie and then close it.
112428   */
112429   db->magic = SQLITE_MAGIC_ZOMBIE;
112430   sqlite3LeaveMutexAndCloseZombie(db);
112431   return SQLITE_OK;
112432 }
112433
112434 /*
112435 ** Two variations on the public interface for closing a database
112436 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
112437 ** leaves the connection option if there are unfinalized prepared
112438 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
112439 ** version forces the connection to become a zombie if there are
112440 ** unclosed resources, and arranges for deallocation when the last
112441 ** prepare statement or sqlite3_backup closes.
112442 */
112443 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
112444 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
112445
112446
112447 /*
112448 ** Close the mutex on database connection db.
112449 **
112450 ** Furthermore, if database connection db is a zombie (meaning that there
112451 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
112452 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
112453 ** finished, then free all resources.
112454 */
112455 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
112456   HashElem *i;                    /* Hash table iterator */
112457   int j;
112458
112459   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
112460   ** or if the connection has not yet been closed by sqlite3_close_v2(),
112461   ** then just leave the mutex and return.
112462   */
112463   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
112464     sqlite3_mutex_leave(db->mutex);
112465     return;
112466   }
112467
112468   /* If we reach this point, it means that the database connection has
112469   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
112470   ** pased to sqlite3_close (meaning that it is a zombie).  Therefore,
112471   ** go ahead and free all resources.
112472   */
112473
112474   /* Free any outstanding Savepoint structures. */
112475   sqlite3CloseSavepoints(db);
112476
112477   /* Close all database connections */
112478   for(j=0; j<db->nDb; j++){
112479     struct Db *pDb = &db->aDb[j];
112480     if( pDb->pBt ){
112481       sqlite3BtreeClose(pDb->pBt);
112482       pDb->pBt = 0;
112483       if( j!=1 ){
112484         pDb->pSchema = 0;
112485       }
112486     }
112487   }
112488   /* Clear the TEMP schema separately and last */
112489   if( db->aDb[1].pSchema ){
112490     sqlite3SchemaClear(db->aDb[1].pSchema);
112491   }
112492   sqlite3VtabUnlockList(db);
112493
112494   /* Free up the array of auxiliary databases */
112495   sqlite3CollapseDatabaseArray(db);
112496   assert( db->nDb<=2 );
112497   assert( db->aDb==db->aDbStatic );
112498
112499   /* Tell the code in notify.c that the connection no longer holds any
112500   ** locks and does not require any further unlock-notify callbacks.
112501   */
112502   sqlite3ConnectionClosed(db);
112503
112504   for(j=0; j<ArraySize(db->aFunc.a); j++){
112505     FuncDef *pNext, *pHash, *p;
112506     for(p=db->aFunc.a[j]; p; p=pHash){
112507       pHash = p->pHash;
112508       while( p ){
112509         functionDestroy(db, p);
112510         pNext = p->pNext;
112511         sqlite3DbFree(db, p);
112512         p = pNext;
112513       }
112514     }
112515   }
112516   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
112517     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
112518     /* Invoke any destructors registered for collation sequence user data. */
112519     for(j=0; j<3; j++){
112520       if( pColl[j].xDel ){
112521         pColl[j].xDel(pColl[j].pUser);
112522       }
112523     }
112524     sqlite3DbFree(db, pColl);
112525   }
112526   sqlite3HashClear(&db->aCollSeq);
112527 #ifndef SQLITE_OMIT_VIRTUALTABLE
112528   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
112529     Module *pMod = (Module *)sqliteHashData(i);
112530     if( pMod->xDestroy ){
112531       pMod->xDestroy(pMod->pAux);
112532     }
112533     sqlite3DbFree(db, pMod);
112534   }
112535   sqlite3HashClear(&db->aModule);
112536 #endif
112537
112538   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
112539   if( db->pErr ){
112540     sqlite3ValueFree(db->pErr);
112541   }
112542   sqlite3CloseExtensions(db);
112543
112544   db->magic = SQLITE_MAGIC_ERROR;
112545
112546   /* The temp-database schema is allocated differently from the other schema
112547   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
112548   ** So it needs to be freed here. Todo: Why not roll the temp schema into
112549   ** the same sqliteMalloc() as the one that allocates the database 
112550   ** structure?
112551   */
112552   sqlite3DbFree(db, db->aDb[1].pSchema);
112553   sqlite3_mutex_leave(db->mutex);
112554   db->magic = SQLITE_MAGIC_CLOSED;
112555   sqlite3_mutex_free(db->mutex);
112556   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
112557   if( db->lookaside.bMalloced ){
112558     sqlite3_free(db->lookaside.pStart);
112559   }
112560   sqlite3_free(db);
112561 }
112562
112563 /*
112564 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
112565 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
112566 ** breaker") and made to return tripCode if there are any further
112567 ** attempts to use that cursor.
112568 */
112569 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
112570   int i;
112571   int inTrans = 0;
112572   assert( sqlite3_mutex_held(db->mutex) );
112573   sqlite3BeginBenignMalloc();
112574   for(i=0; i<db->nDb; i++){
112575     Btree *p = db->aDb[i].pBt;
112576     if( p ){
112577       if( sqlite3BtreeIsInTrans(p) ){
112578         inTrans = 1;
112579       }
112580       sqlite3BtreeRollback(p, tripCode);
112581       db->aDb[i].inTrans = 0;
112582     }
112583   }
112584   sqlite3VtabRollback(db);
112585   sqlite3EndBenignMalloc();
112586
112587   if( db->flags&SQLITE_InternChanges ){
112588     sqlite3ExpirePreparedStatements(db);
112589     sqlite3ResetAllSchemasOfConnection(db);
112590   }
112591
112592   /* Any deferred constraint violations have now been resolved. */
112593   db->nDeferredCons = 0;
112594
112595   /* If one has been configured, invoke the rollback-hook callback */
112596   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
112597     db->xRollbackCallback(db->pRollbackArg);
112598   }
112599 }
112600
112601 /*
112602 ** Return a static string that describes the kind of error specified in the
112603 ** argument.
112604 */
112605 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
112606   static const char* const aMsg[] = {
112607     /* SQLITE_OK          */ "not an error",
112608     /* SQLITE_ERROR       */ "SQL logic error or missing database",
112609     /* SQLITE_INTERNAL    */ 0,
112610     /* SQLITE_PERM        */ "access permission denied",
112611     /* SQLITE_ABORT       */ "callback requested query abort",
112612     /* SQLITE_BUSY        */ "database is locked",
112613     /* SQLITE_LOCKED      */ "database table is locked",
112614     /* SQLITE_NOMEM       */ "out of memory",
112615     /* SQLITE_READONLY    */ "attempt to write a readonly database",
112616     /* SQLITE_INTERRUPT   */ "interrupted",
112617     /* SQLITE_IOERR       */ "disk I/O error",
112618     /* SQLITE_CORRUPT     */ "database disk image is malformed",
112619     /* SQLITE_NOTFOUND    */ "unknown operation",
112620     /* SQLITE_FULL        */ "database or disk is full",
112621     /* SQLITE_CANTOPEN    */ "unable to open database file",
112622     /* SQLITE_PROTOCOL    */ "locking protocol",
112623     /* SQLITE_EMPTY       */ "table contains no data",
112624     /* SQLITE_SCHEMA      */ "database schema has changed",
112625     /* SQLITE_TOOBIG      */ "string or blob too big",
112626     /* SQLITE_CONSTRAINT  */ "constraint failed",
112627     /* SQLITE_MISMATCH    */ "datatype mismatch",
112628     /* SQLITE_MISUSE      */ "library routine called out of sequence",
112629     /* SQLITE_NOLFS       */ "large file support is disabled",
112630     /* SQLITE_AUTH        */ "authorization denied",
112631     /* SQLITE_FORMAT      */ "auxiliary database format error",
112632     /* SQLITE_RANGE       */ "bind or column index out of range",
112633     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
112634   };
112635   const char *zErr = "unknown error";
112636   switch( rc ){
112637     case SQLITE_ABORT_ROLLBACK: {
112638       zErr = "abort due to ROLLBACK";
112639       break;
112640     }
112641     default: {
112642       rc &= 0xff;
112643       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
112644         zErr = aMsg[rc];
112645       }
112646       break;
112647     }
112648   }
112649   return zErr;
112650 }
112651
112652 /*
112653 ** This routine implements a busy callback that sleeps and tries
112654 ** again until a timeout value is reached.  The timeout value is
112655 ** an integer number of milliseconds passed in as the first
112656 ** argument.
112657 */
112658 static int sqliteDefaultBusyCallback(
112659  void *ptr,               /* Database connection */
112660  int count                /* Number of times table has been busy */
112661 ){
112662 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
112663   static const u8 delays[] =
112664      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
112665   static const u8 totals[] =
112666      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
112667 # define NDELAY ArraySize(delays)
112668   sqlite3 *db = (sqlite3 *)ptr;
112669   int timeout = db->busyTimeout;
112670   int delay, prior;
112671
112672   assert( count>=0 );
112673   if( count < NDELAY ){
112674     delay = delays[count];
112675     prior = totals[count];
112676   }else{
112677     delay = delays[NDELAY-1];
112678     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
112679   }
112680   if( prior + delay > timeout ){
112681     delay = timeout - prior;
112682     if( delay<=0 ) return 0;
112683   }
112684   sqlite3OsSleep(db->pVfs, delay*1000);
112685   return 1;
112686 #else
112687   sqlite3 *db = (sqlite3 *)ptr;
112688   int timeout = ((sqlite3 *)ptr)->busyTimeout;
112689   if( (count+1)*1000 > timeout ){
112690     return 0;
112691   }
112692   sqlite3OsSleep(db->pVfs, 1000000);
112693   return 1;
112694 #endif
112695 }
112696
112697 /*
112698 ** Invoke the given busy handler.
112699 **
112700 ** This routine is called when an operation failed with a lock.
112701 ** If this routine returns non-zero, the lock is retried.  If it
112702 ** returns 0, the operation aborts with an SQLITE_BUSY error.
112703 */
112704 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
112705   int rc;
112706   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
112707   rc = p->xFunc(p->pArg, p->nBusy);
112708   if( rc==0 ){
112709     p->nBusy = -1;
112710   }else{
112711     p->nBusy++;
112712   }
112713   return rc; 
112714 }
112715
112716 /*
112717 ** This routine sets the busy callback for an Sqlite database to the
112718 ** given callback function with the given argument.
112719 */
112720 SQLITE_API int sqlite3_busy_handler(
112721   sqlite3 *db,
112722   int (*xBusy)(void*,int),
112723   void *pArg
112724 ){
112725   sqlite3_mutex_enter(db->mutex);
112726   db->busyHandler.xFunc = xBusy;
112727   db->busyHandler.pArg = pArg;
112728   db->busyHandler.nBusy = 0;
112729   sqlite3_mutex_leave(db->mutex);
112730   return SQLITE_OK;
112731 }
112732
112733 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
112734 /*
112735 ** This routine sets the progress callback for an Sqlite database to the
112736 ** given callback function with the given argument. The progress callback will
112737 ** be invoked every nOps opcodes.
112738 */
112739 SQLITE_API void sqlite3_progress_handler(
112740   sqlite3 *db, 
112741   int nOps,
112742   int (*xProgress)(void*), 
112743   void *pArg
112744 ){
112745   sqlite3_mutex_enter(db->mutex);
112746   if( nOps>0 ){
112747     db->xProgress = xProgress;
112748     db->nProgressOps = nOps;
112749     db->pProgressArg = pArg;
112750   }else{
112751     db->xProgress = 0;
112752     db->nProgressOps = 0;
112753     db->pProgressArg = 0;
112754   }
112755   sqlite3_mutex_leave(db->mutex);
112756 }
112757 #endif
112758
112759
112760 /*
112761 ** This routine installs a default busy handler that waits for the
112762 ** specified number of milliseconds before returning 0.
112763 */
112764 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
112765   if( ms>0 ){
112766     db->busyTimeout = ms;
112767     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
112768   }else{
112769     sqlite3_busy_handler(db, 0, 0);
112770   }
112771   return SQLITE_OK;
112772 }
112773
112774 /*
112775 ** Cause any pending operation to stop at its earliest opportunity.
112776 */
112777 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
112778   db->u1.isInterrupted = 1;
112779 }
112780
112781
112782 /*
112783 ** This function is exactly the same as sqlite3_create_function(), except
112784 ** that it is designed to be called by internal code. The difference is
112785 ** that if a malloc() fails in sqlite3_create_function(), an error code
112786 ** is returned and the mallocFailed flag cleared. 
112787 */
112788 SQLITE_PRIVATE int sqlite3CreateFunc(
112789   sqlite3 *db,
112790   const char *zFunctionName,
112791   int nArg,
112792   int enc,
112793   void *pUserData,
112794   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
112795   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
112796   void (*xFinal)(sqlite3_context*),
112797   FuncDestructor *pDestructor
112798 ){
112799   FuncDef *p;
112800   int nName;
112801
112802   assert( sqlite3_mutex_held(db->mutex) );
112803   if( zFunctionName==0 ||
112804       (xFunc && (xFinal || xStep)) || 
112805       (!xFunc && (xFinal && !xStep)) ||
112806       (!xFunc && (!xFinal && xStep)) ||
112807       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
112808       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
112809     return SQLITE_MISUSE_BKPT;
112810   }
112811   
112812 #ifndef SQLITE_OMIT_UTF16
112813   /* If SQLITE_UTF16 is specified as the encoding type, transform this
112814   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
112815   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
112816   **
112817   ** If SQLITE_ANY is specified, add three versions of the function
112818   ** to the hash table.
112819   */
112820   if( enc==SQLITE_UTF16 ){
112821     enc = SQLITE_UTF16NATIVE;
112822   }else if( enc==SQLITE_ANY ){
112823     int rc;
112824     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
112825          pUserData, xFunc, xStep, xFinal, pDestructor);
112826     if( rc==SQLITE_OK ){
112827       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
112828           pUserData, xFunc, xStep, xFinal, pDestructor);
112829     }
112830     if( rc!=SQLITE_OK ){
112831       return rc;
112832     }
112833     enc = SQLITE_UTF16BE;
112834   }
112835 #else
112836   enc = SQLITE_UTF8;
112837 #endif
112838   
112839   /* Check if an existing function is being overridden or deleted. If so,
112840   ** and there are active VMs, then return SQLITE_BUSY. If a function
112841   ** is being overridden/deleted but there are no active VMs, allow the
112842   ** operation to continue but invalidate all precompiled statements.
112843   */
112844   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
112845   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
112846     if( db->activeVdbeCnt ){
112847       sqlite3Error(db, SQLITE_BUSY, 
112848         "unable to delete/modify user-function due to active statements");
112849       assert( !db->mallocFailed );
112850       return SQLITE_BUSY;
112851     }else{
112852       sqlite3ExpirePreparedStatements(db);
112853     }
112854   }
112855
112856   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
112857   assert(p || db->mallocFailed);
112858   if( !p ){
112859     return SQLITE_NOMEM;
112860   }
112861
112862   /* If an older version of the function with a configured destructor is
112863   ** being replaced invoke the destructor function here. */
112864   functionDestroy(db, p);
112865
112866   if( pDestructor ){
112867     pDestructor->nRef++;
112868   }
112869   p->pDestructor = pDestructor;
112870   p->flags = 0;
112871   p->xFunc = xFunc;
112872   p->xStep = xStep;
112873   p->xFinalize = xFinal;
112874   p->pUserData = pUserData;
112875   p->nArg = (u16)nArg;
112876   return SQLITE_OK;
112877 }
112878
112879 /*
112880 ** Create new user functions.
112881 */
112882 SQLITE_API int sqlite3_create_function(
112883   sqlite3 *db,
112884   const char *zFunc,
112885   int nArg,
112886   int enc,
112887   void *p,
112888   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
112889   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
112890   void (*xFinal)(sqlite3_context*)
112891 ){
112892   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
112893                                     xFinal, 0);
112894 }
112895
112896 SQLITE_API int sqlite3_create_function_v2(
112897   sqlite3 *db,
112898   const char *zFunc,
112899   int nArg,
112900   int enc,
112901   void *p,
112902   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
112903   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
112904   void (*xFinal)(sqlite3_context*),
112905   void (*xDestroy)(void *)
112906 ){
112907   int rc = SQLITE_ERROR;
112908   FuncDestructor *pArg = 0;
112909   sqlite3_mutex_enter(db->mutex);
112910   if( xDestroy ){
112911     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
112912     if( !pArg ){
112913       xDestroy(p);
112914       goto out;
112915     }
112916     pArg->xDestroy = xDestroy;
112917     pArg->pUserData = p;
112918   }
112919   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
112920   if( pArg && pArg->nRef==0 ){
112921     assert( rc!=SQLITE_OK );
112922     xDestroy(p);
112923     sqlite3DbFree(db, pArg);
112924   }
112925
112926  out:
112927   rc = sqlite3ApiExit(db, rc);
112928   sqlite3_mutex_leave(db->mutex);
112929   return rc;
112930 }
112931
112932 #ifndef SQLITE_OMIT_UTF16
112933 SQLITE_API int sqlite3_create_function16(
112934   sqlite3 *db,
112935   const void *zFunctionName,
112936   int nArg,
112937   int eTextRep,
112938   void *p,
112939   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112940   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112941   void (*xFinal)(sqlite3_context*)
112942 ){
112943   int rc;
112944   char *zFunc8;
112945   sqlite3_mutex_enter(db->mutex);
112946   assert( !db->mallocFailed );
112947   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
112948   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
112949   sqlite3DbFree(db, zFunc8);
112950   rc = sqlite3ApiExit(db, rc);
112951   sqlite3_mutex_leave(db->mutex);
112952   return rc;
112953 }
112954 #endif
112955
112956
112957 /*
112958 ** Declare that a function has been overloaded by a virtual table.
112959 **
112960 ** If the function already exists as a regular global function, then
112961 ** this routine is a no-op.  If the function does not exist, then create
112962 ** a new one that always throws a run-time error.  
112963 **
112964 ** When virtual tables intend to provide an overloaded function, they
112965 ** should call this routine to make sure the global function exists.
112966 ** A global function must exist in order for name resolution to work
112967 ** properly.
112968 */
112969 SQLITE_API int sqlite3_overload_function(
112970   sqlite3 *db,
112971   const char *zName,
112972   int nArg
112973 ){
112974   int nName = sqlite3Strlen30(zName);
112975   int rc = SQLITE_OK;
112976   sqlite3_mutex_enter(db->mutex);
112977   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
112978     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
112979                            0, sqlite3InvalidFunction, 0, 0, 0);
112980   }
112981   rc = sqlite3ApiExit(db, rc);
112982   sqlite3_mutex_leave(db->mutex);
112983   return rc;
112984 }
112985
112986 #ifndef SQLITE_OMIT_TRACE
112987 /*
112988 ** Register a trace function.  The pArg from the previously registered trace
112989 ** is returned.  
112990 **
112991 ** A NULL trace function means that no tracing is executes.  A non-NULL
112992 ** trace is a pointer to a function that is invoked at the start of each
112993 ** SQL statement.
112994 */
112995 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
112996   void *pOld;
112997   sqlite3_mutex_enter(db->mutex);
112998   pOld = db->pTraceArg;
112999   db->xTrace = xTrace;
113000   db->pTraceArg = pArg;
113001   sqlite3_mutex_leave(db->mutex);
113002   return pOld;
113003 }
113004 /*
113005 ** Register a profile function.  The pArg from the previously registered 
113006 ** profile function is returned.  
113007 **
113008 ** A NULL profile function means that no profiling is executes.  A non-NULL
113009 ** profile is a pointer to a function that is invoked at the conclusion of
113010 ** each SQL statement that is run.
113011 */
113012 SQLITE_API void *sqlite3_profile(
113013   sqlite3 *db,
113014   void (*xProfile)(void*,const char*,sqlite_uint64),
113015   void *pArg
113016 ){
113017   void *pOld;
113018   sqlite3_mutex_enter(db->mutex);
113019   pOld = db->pProfileArg;
113020   db->xProfile = xProfile;
113021   db->pProfileArg = pArg;
113022   sqlite3_mutex_leave(db->mutex);
113023   return pOld;
113024 }
113025 #endif /* SQLITE_OMIT_TRACE */
113026
113027 /*
113028 ** Register a function to be invoked when a transaction commits.
113029 ** If the invoked function returns non-zero, then the commit becomes a
113030 ** rollback.
113031 */
113032 SQLITE_API void *sqlite3_commit_hook(
113033   sqlite3 *db,              /* Attach the hook to this database */
113034   int (*xCallback)(void*),  /* Function to invoke on each commit */
113035   void *pArg                /* Argument to the function */
113036 ){
113037   void *pOld;
113038   sqlite3_mutex_enter(db->mutex);
113039   pOld = db->pCommitArg;
113040   db->xCommitCallback = xCallback;
113041   db->pCommitArg = pArg;
113042   sqlite3_mutex_leave(db->mutex);
113043   return pOld;
113044 }
113045
113046 /*
113047 ** Register a callback to be invoked each time a row is updated,
113048 ** inserted or deleted using this database connection.
113049 */
113050 SQLITE_API void *sqlite3_update_hook(
113051   sqlite3 *db,              /* Attach the hook to this database */
113052   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
113053   void *pArg                /* Argument to the function */
113054 ){
113055   void *pRet;
113056   sqlite3_mutex_enter(db->mutex);
113057   pRet = db->pUpdateArg;
113058   db->xUpdateCallback = xCallback;
113059   db->pUpdateArg = pArg;
113060   sqlite3_mutex_leave(db->mutex);
113061   return pRet;
113062 }
113063
113064 /*
113065 ** Register a callback to be invoked each time a transaction is rolled
113066 ** back by this database connection.
113067 */
113068 SQLITE_API void *sqlite3_rollback_hook(
113069   sqlite3 *db,              /* Attach the hook to this database */
113070   void (*xCallback)(void*), /* Callback function */
113071   void *pArg                /* Argument to the function */
113072 ){
113073   void *pRet;
113074   sqlite3_mutex_enter(db->mutex);
113075   pRet = db->pRollbackArg;
113076   db->xRollbackCallback = xCallback;
113077   db->pRollbackArg = pArg;
113078   sqlite3_mutex_leave(db->mutex);
113079   return pRet;
113080 }
113081
113082 #ifndef SQLITE_OMIT_WAL
113083 /*
113084 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
113085 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
113086 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
113087 ** wal_autocheckpoint()).
113088 */ 
113089 SQLITE_PRIVATE int sqlite3WalDefaultHook(
113090   void *pClientData,     /* Argument */
113091   sqlite3 *db,           /* Connection */
113092   const char *zDb,       /* Database */
113093   int nFrame             /* Size of WAL */
113094 ){
113095   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
113096     sqlite3BeginBenignMalloc();
113097     sqlite3_wal_checkpoint(db, zDb);
113098     sqlite3EndBenignMalloc();
113099   }
113100   return SQLITE_OK;
113101 }
113102 #endif /* SQLITE_OMIT_WAL */
113103
113104 /*
113105 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
113106 ** a database after committing a transaction if there are nFrame or
113107 ** more frames in the log file. Passing zero or a negative value as the
113108 ** nFrame parameter disables automatic checkpoints entirely.
113109 **
113110 ** The callback registered by this function replaces any existing callback
113111 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
113112 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
113113 ** configured by this function.
113114 */
113115 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
113116 #ifdef SQLITE_OMIT_WAL
113117   UNUSED_PARAMETER(db);
113118   UNUSED_PARAMETER(nFrame);
113119 #else
113120   if( nFrame>0 ){
113121     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
113122   }else{
113123     sqlite3_wal_hook(db, 0, 0);
113124   }
113125 #endif
113126   return SQLITE_OK;
113127 }
113128
113129 /*
113130 ** Register a callback to be invoked each time a transaction is written
113131 ** into the write-ahead-log by this database connection.
113132 */
113133 SQLITE_API void *sqlite3_wal_hook(
113134   sqlite3 *db,                    /* Attach the hook to this db handle */
113135   int(*xCallback)(void *, sqlite3*, const char*, int),
113136   void *pArg                      /* First argument passed to xCallback() */
113137 ){
113138 #ifndef SQLITE_OMIT_WAL
113139   void *pRet;
113140   sqlite3_mutex_enter(db->mutex);
113141   pRet = db->pWalArg;
113142   db->xWalCallback = xCallback;
113143   db->pWalArg = pArg;
113144   sqlite3_mutex_leave(db->mutex);
113145   return pRet;
113146 #else
113147   return 0;
113148 #endif
113149 }
113150
113151 /*
113152 ** Checkpoint database zDb.
113153 */
113154 SQLITE_API int sqlite3_wal_checkpoint_v2(
113155   sqlite3 *db,                    /* Database handle */
113156   const char *zDb,                /* Name of attached database (or NULL) */
113157   int eMode,                      /* SQLITE_CHECKPOINT_* value */
113158   int *pnLog,                     /* OUT: Size of WAL log in frames */
113159   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
113160 ){
113161 #ifdef SQLITE_OMIT_WAL
113162   return SQLITE_OK;
113163 #else
113164   int rc;                         /* Return code */
113165   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
113166
113167   /* Initialize the output variables to -1 in case an error occurs. */
113168   if( pnLog ) *pnLog = -1;
113169   if( pnCkpt ) *pnCkpt = -1;
113170
113171   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
113172   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
113173   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
113174   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
113175     return SQLITE_MISUSE;
113176   }
113177
113178   sqlite3_mutex_enter(db->mutex);
113179   if( zDb && zDb[0] ){
113180     iDb = sqlite3FindDbName(db, zDb);
113181   }
113182   if( iDb<0 ){
113183     rc = SQLITE_ERROR;
113184     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
113185   }else{
113186     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
113187     sqlite3Error(db, rc, 0);
113188   }
113189   rc = sqlite3ApiExit(db, rc);
113190   sqlite3_mutex_leave(db->mutex);
113191   return rc;
113192 #endif
113193 }
113194
113195
113196 /*
113197 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
113198 ** to contains a zero-length string, all attached databases are 
113199 ** checkpointed.
113200 */
113201 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
113202   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
113203 }
113204
113205 #ifndef SQLITE_OMIT_WAL
113206 /*
113207 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
113208 ** not currently open in WAL mode.
113209 **
113210 ** If a transaction is open on the database being checkpointed, this 
113211 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
113212 ** an error occurs while running the checkpoint, an SQLite error code is 
113213 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
113214 **
113215 ** The mutex on database handle db should be held by the caller. The mutex
113216 ** associated with the specific b-tree being checkpointed is taken by
113217 ** this function while the checkpoint is running.
113218 **
113219 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
113220 ** checkpointed. If an error is encountered it is returned immediately -
113221 ** no attempt is made to checkpoint any remaining databases.
113222 **
113223 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
113224 */
113225 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
113226   int rc = SQLITE_OK;             /* Return code */
113227   int i;                          /* Used to iterate through attached dbs */
113228   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
113229
113230   assert( sqlite3_mutex_held(db->mutex) );
113231   assert( !pnLog || *pnLog==-1 );
113232   assert( !pnCkpt || *pnCkpt==-1 );
113233
113234   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
113235     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
113236       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
113237       pnLog = 0;
113238       pnCkpt = 0;
113239       if( rc==SQLITE_BUSY ){
113240         bBusy = 1;
113241         rc = SQLITE_OK;
113242       }
113243     }
113244   }
113245
113246   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
113247 }
113248 #endif /* SQLITE_OMIT_WAL */
113249
113250 /*
113251 ** This function returns true if main-memory should be used instead of
113252 ** a temporary file for transient pager files and statement journals.
113253 ** The value returned depends on the value of db->temp_store (runtime
113254 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
113255 ** following table describes the relationship between these two values
113256 ** and this functions return value.
113257 **
113258 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
113259 **   -----------------     --------------     ------------------------------
113260 **   0                     any                file      (return 0)
113261 **   1                     1                  file      (return 0)
113262 **   1                     2                  memory    (return 1)
113263 **   1                     0                  file      (return 0)
113264 **   2                     1                  file      (return 0)
113265 **   2                     2                  memory    (return 1)
113266 **   2                     0                  memory    (return 1)
113267 **   3                     any                memory    (return 1)
113268 */
113269 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
113270 #if SQLITE_TEMP_STORE==1
113271   return ( db->temp_store==2 );
113272 #endif
113273 #if SQLITE_TEMP_STORE==2
113274   return ( db->temp_store!=1 );
113275 #endif
113276 #if SQLITE_TEMP_STORE==3
113277   return 1;
113278 #endif
113279 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
113280   return 0;
113281 #endif
113282 }
113283
113284 /*
113285 ** Return UTF-8 encoded English language explanation of the most recent
113286 ** error.
113287 */
113288 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
113289   const char *z;
113290   if( !db ){
113291     return sqlite3ErrStr(SQLITE_NOMEM);
113292   }
113293   if( !sqlite3SafetyCheckSickOrOk(db) ){
113294     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
113295   }
113296   sqlite3_mutex_enter(db->mutex);
113297   if( db->mallocFailed ){
113298     z = sqlite3ErrStr(SQLITE_NOMEM);
113299   }else{
113300     z = (char*)sqlite3_value_text(db->pErr);
113301     assert( !db->mallocFailed );
113302     if( z==0 ){
113303       z = sqlite3ErrStr(db->errCode);
113304     }
113305   }
113306   sqlite3_mutex_leave(db->mutex);
113307   return z;
113308 }
113309
113310 #ifndef SQLITE_OMIT_UTF16
113311 /*
113312 ** Return UTF-16 encoded English language explanation of the most recent
113313 ** error.
113314 */
113315 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
113316   static const u16 outOfMem[] = {
113317     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
113318   };
113319   static const u16 misuse[] = {
113320     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
113321     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
113322     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
113323     'o', 'u', 't', ' ', 
113324     'o', 'f', ' ', 
113325     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
113326   };
113327
113328   const void *z;
113329   if( !db ){
113330     return (void *)outOfMem;
113331   }
113332   if( !sqlite3SafetyCheckSickOrOk(db) ){
113333     return (void *)misuse;
113334   }
113335   sqlite3_mutex_enter(db->mutex);
113336   if( db->mallocFailed ){
113337     z = (void *)outOfMem;
113338   }else{
113339     z = sqlite3_value_text16(db->pErr);
113340     if( z==0 ){
113341       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
113342            SQLITE_UTF8, SQLITE_STATIC);
113343       z = sqlite3_value_text16(db->pErr);
113344     }
113345     /* A malloc() may have failed within the call to sqlite3_value_text16()
113346     ** above. If this is the case, then the db->mallocFailed flag needs to
113347     ** be cleared before returning. Do this directly, instead of via
113348     ** sqlite3ApiExit(), to avoid setting the database handle error message.
113349     */
113350     db->mallocFailed = 0;
113351   }
113352   sqlite3_mutex_leave(db->mutex);
113353   return z;
113354 }
113355 #endif /* SQLITE_OMIT_UTF16 */
113356
113357 /*
113358 ** Return the most recent error code generated by an SQLite routine. If NULL is
113359 ** passed to this function, we assume a malloc() failed during sqlite3_open().
113360 */
113361 SQLITE_API int sqlite3_errcode(sqlite3 *db){
113362   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
113363     return SQLITE_MISUSE_BKPT;
113364   }
113365   if( !db || db->mallocFailed ){
113366     return SQLITE_NOMEM;
113367   }
113368   return db->errCode & db->errMask;
113369 }
113370 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
113371   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
113372     return SQLITE_MISUSE_BKPT;
113373   }
113374   if( !db || db->mallocFailed ){
113375     return SQLITE_NOMEM;
113376   }
113377   return db->errCode;
113378 }
113379
113380 /*
113381 ** Create a new collating function for database "db".  The name is zName
113382 ** and the encoding is enc.
113383 */
113384 static int createCollation(
113385   sqlite3* db,
113386   const char *zName, 
113387   u8 enc,
113388   void* pCtx,
113389   int(*xCompare)(void*,int,const void*,int,const void*),
113390   void(*xDel)(void*)
113391 ){
113392   CollSeq *pColl;
113393   int enc2;
113394   int nName = sqlite3Strlen30(zName);
113395   
113396   assert( sqlite3_mutex_held(db->mutex) );
113397
113398   /* If SQLITE_UTF16 is specified as the encoding type, transform this
113399   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
113400   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
113401   */
113402   enc2 = enc;
113403   testcase( enc2==SQLITE_UTF16 );
113404   testcase( enc2==SQLITE_UTF16_ALIGNED );
113405   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
113406     enc2 = SQLITE_UTF16NATIVE;
113407   }
113408   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
113409     return SQLITE_MISUSE_BKPT;
113410   }
113411
113412   /* Check if this call is removing or replacing an existing collation 
113413   ** sequence. If so, and there are active VMs, return busy. If there
113414   ** are no active VMs, invalidate any pre-compiled statements.
113415   */
113416   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
113417   if( pColl && pColl->xCmp ){
113418     if( db->activeVdbeCnt ){
113419       sqlite3Error(db, SQLITE_BUSY, 
113420         "unable to delete/modify collation sequence due to active statements");
113421       return SQLITE_BUSY;
113422     }
113423     sqlite3ExpirePreparedStatements(db);
113424
113425     /* If collation sequence pColl was created directly by a call to
113426     ** sqlite3_create_collation, and not generated by synthCollSeq(),
113427     ** then any copies made by synthCollSeq() need to be invalidated.
113428     ** Also, collation destructor - CollSeq.xDel() - function may need
113429     ** to be called.
113430     */ 
113431     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
113432       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
113433       int j;
113434       for(j=0; j<3; j++){
113435         CollSeq *p = &aColl[j];
113436         if( p->enc==pColl->enc ){
113437           if( p->xDel ){
113438             p->xDel(p->pUser);
113439           }
113440           p->xCmp = 0;
113441         }
113442       }
113443     }
113444   }
113445
113446   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
113447   if( pColl==0 ) return SQLITE_NOMEM;
113448   pColl->xCmp = xCompare;
113449   pColl->pUser = pCtx;
113450   pColl->xDel = xDel;
113451   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
113452   sqlite3Error(db, SQLITE_OK, 0);
113453   return SQLITE_OK;
113454 }
113455
113456
113457 /*
113458 ** This array defines hard upper bounds on limit values.  The
113459 ** initializer must be kept in sync with the SQLITE_LIMIT_*
113460 ** #defines in sqlite3.h.
113461 */
113462 static const int aHardLimit[] = {
113463   SQLITE_MAX_LENGTH,
113464   SQLITE_MAX_SQL_LENGTH,
113465   SQLITE_MAX_COLUMN,
113466   SQLITE_MAX_EXPR_DEPTH,
113467   SQLITE_MAX_COMPOUND_SELECT,
113468   SQLITE_MAX_VDBE_OP,
113469   SQLITE_MAX_FUNCTION_ARG,
113470   SQLITE_MAX_ATTACHED,
113471   SQLITE_MAX_LIKE_PATTERN_LENGTH,
113472   SQLITE_MAX_VARIABLE_NUMBER,
113473   SQLITE_MAX_TRIGGER_DEPTH,
113474 };
113475
113476 /*
113477 ** Make sure the hard limits are set to reasonable values
113478 */
113479 #if SQLITE_MAX_LENGTH<100
113480 # error SQLITE_MAX_LENGTH must be at least 100
113481 #endif
113482 #if SQLITE_MAX_SQL_LENGTH<100
113483 # error SQLITE_MAX_SQL_LENGTH must be at least 100
113484 #endif
113485 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
113486 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
113487 #endif
113488 #if SQLITE_MAX_COMPOUND_SELECT<2
113489 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
113490 #endif
113491 #if SQLITE_MAX_VDBE_OP<40
113492 # error SQLITE_MAX_VDBE_OP must be at least 40
113493 #endif
113494 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
113495 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
113496 #endif
113497 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
113498 # error SQLITE_MAX_ATTACHED must be between 0 and 62
113499 #endif
113500 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
113501 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
113502 #endif
113503 #if SQLITE_MAX_COLUMN>32767
113504 # error SQLITE_MAX_COLUMN must not exceed 32767
113505 #endif
113506 #if SQLITE_MAX_TRIGGER_DEPTH<1
113507 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
113508 #endif
113509
113510
113511 /*
113512 ** Change the value of a limit.  Report the old value.
113513 ** If an invalid limit index is supplied, report -1.
113514 ** Make no changes but still report the old value if the
113515 ** new limit is negative.
113516 **
113517 ** A new lower limit does not shrink existing constructs.
113518 ** It merely prevents new constructs that exceed the limit
113519 ** from forming.
113520 */
113521 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
113522   int oldLimit;
113523
113524
113525   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
113526   ** there is a hard upper bound set at compile-time by a C preprocessor
113527   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
113528   ** "_MAX_".)
113529   */
113530   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
113531   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
113532   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
113533   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
113534   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
113535   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
113536   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
113537   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
113538   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
113539                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
113540   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
113541   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
113542   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
113543
113544
113545   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
113546     return -1;
113547   }
113548   oldLimit = db->aLimit[limitId];
113549   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
113550     if( newLimit>aHardLimit[limitId] ){
113551       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
113552     }
113553     db->aLimit[limitId] = newLimit;
113554   }
113555   return oldLimit;                     /* IMP: R-53341-35419 */
113556 }
113557
113558 /*
113559 ** This function is used to parse both URIs and non-URI filenames passed by the
113560 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
113561 ** URIs specified as part of ATTACH statements.
113562 **
113563 ** The first argument to this function is the name of the VFS to use (or
113564 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
113565 ** query parameter. The second argument contains the URI (or non-URI filename)
113566 ** itself. When this function is called the *pFlags variable should contain
113567 ** the default flags to open the database handle with. The value stored in
113568 ** *pFlags may be updated before returning if the URI filename contains 
113569 ** "cache=xxx" or "mode=xxx" query parameters.
113570 **
113571 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
113572 ** the VFS that should be used to open the database file. *pzFile is set to
113573 ** point to a buffer containing the name of the file to open. It is the 
113574 ** responsibility of the caller to eventually call sqlite3_free() to release
113575 ** this buffer.
113576 **
113577 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
113578 ** may be set to point to a buffer containing an English language error 
113579 ** message. It is the responsibility of the caller to eventually release
113580 ** this buffer by calling sqlite3_free().
113581 */
113582 SQLITE_PRIVATE int sqlite3ParseUri(
113583   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
113584   const char *zUri,               /* Nul-terminated URI to parse */
113585   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
113586   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
113587   char **pzFile,                  /* OUT: Filename component of URI */
113588   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
113589 ){
113590   int rc = SQLITE_OK;
113591   unsigned int flags = *pFlags;
113592   const char *zVfs = zDefaultVfs;
113593   char *zFile;
113594   char c;
113595   int nUri = sqlite3Strlen30(zUri);
113596
113597   assert( *pzErrMsg==0 );
113598
113599   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
113600    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
113601   ){
113602     char *zOpt;
113603     int eState;                   /* Parser state when parsing URI */
113604     int iIn;                      /* Input character index */
113605     int iOut = 0;                 /* Output character index */
113606     int nByte = nUri+2;           /* Bytes of space to allocate */
113607
113608     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
113609     ** method that there may be extra parameters following the file-name.  */
113610     flags |= SQLITE_OPEN_URI;
113611
113612     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
113613     zFile = sqlite3_malloc(nByte);
113614     if( !zFile ) return SQLITE_NOMEM;
113615
113616     /* Discard the scheme and authority segments of the URI. */
113617     if( zUri[5]=='/' && zUri[6]=='/' ){
113618       iIn = 7;
113619       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
113620
113621       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
113622         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
113623             iIn-7, &zUri[7]);
113624         rc = SQLITE_ERROR;
113625         goto parse_uri_out;
113626       }
113627     }else{
113628       iIn = 5;
113629     }
113630
113631     /* Copy the filename and any query parameters into the zFile buffer. 
113632     ** Decode %HH escape codes along the way. 
113633     **
113634     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
113635     ** on the parsing context. As follows:
113636     **
113637     **   0: Parsing file-name.
113638     **   1: Parsing name section of a name=value query parameter.
113639     **   2: Parsing value section of a name=value query parameter.
113640     */
113641     eState = 0;
113642     while( (c = zUri[iIn])!=0 && c!='#' ){
113643       iIn++;
113644       if( c=='%' 
113645        && sqlite3Isxdigit(zUri[iIn]) 
113646        && sqlite3Isxdigit(zUri[iIn+1]) 
113647       ){
113648         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
113649         octet += sqlite3HexToInt(zUri[iIn++]);
113650
113651         assert( octet>=0 && octet<256 );
113652         if( octet==0 ){
113653           /* This branch is taken when "%00" appears within the URI. In this
113654           ** case we ignore all text in the remainder of the path, name or
113655           ** value currently being parsed. So ignore the current character
113656           ** and skip to the next "?", "=" or "&", as appropriate. */
113657           while( (c = zUri[iIn])!=0 && c!='#' 
113658               && (eState!=0 || c!='?')
113659               && (eState!=1 || (c!='=' && c!='&'))
113660               && (eState!=2 || c!='&')
113661           ){
113662             iIn++;
113663           }
113664           continue;
113665         }
113666         c = octet;
113667       }else if( eState==1 && (c=='&' || c=='=') ){
113668         if( zFile[iOut-1]==0 ){
113669           /* An empty option name. Ignore this option altogether. */
113670           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
113671           continue;
113672         }
113673         if( c=='&' ){
113674           zFile[iOut++] = '\0';
113675         }else{
113676           eState = 2;
113677         }
113678         c = 0;
113679       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
113680         c = 0;
113681         eState = 1;
113682       }
113683       zFile[iOut++] = c;
113684     }
113685     if( eState==1 ) zFile[iOut++] = '\0';
113686     zFile[iOut++] = '\0';
113687     zFile[iOut++] = '\0';
113688
113689     /* Check if there were any options specified that should be interpreted 
113690     ** here. Options that are interpreted here include "vfs" and those that
113691     ** correspond to flags that may be passed to the sqlite3_open_v2()
113692     ** method. */
113693     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
113694     while( zOpt[0] ){
113695       int nOpt = sqlite3Strlen30(zOpt);
113696       char *zVal = &zOpt[nOpt+1];
113697       int nVal = sqlite3Strlen30(zVal);
113698
113699       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
113700         zVfs = zVal;
113701       }else{
113702         struct OpenMode {
113703           const char *z;
113704           int mode;
113705         } *aMode = 0;
113706         char *zModeType = 0;
113707         int mask = 0;
113708         int limit = 0;
113709
113710         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
113711           static struct OpenMode aCacheMode[] = {
113712             { "shared",  SQLITE_OPEN_SHAREDCACHE },
113713             { "private", SQLITE_OPEN_PRIVATECACHE },
113714             { 0, 0 }
113715           };
113716
113717           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
113718           aMode = aCacheMode;
113719           limit = mask;
113720           zModeType = "cache";
113721         }
113722         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
113723           static struct OpenMode aOpenMode[] = {
113724             { "ro",  SQLITE_OPEN_READONLY },
113725             { "rw",  SQLITE_OPEN_READWRITE }, 
113726             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
113727             { "memory", SQLITE_OPEN_MEMORY },
113728             { 0, 0 }
113729           };
113730
113731           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
113732                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
113733           aMode = aOpenMode;
113734           limit = mask & flags;
113735           zModeType = "access";
113736         }
113737
113738         if( aMode ){
113739           int i;
113740           int mode = 0;
113741           for(i=0; aMode[i].z; i++){
113742             const char *z = aMode[i].z;
113743             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
113744               mode = aMode[i].mode;
113745               break;
113746             }
113747           }
113748           if( mode==0 ){
113749             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
113750             rc = SQLITE_ERROR;
113751             goto parse_uri_out;
113752           }
113753           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
113754             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
113755                                         zModeType, zVal);
113756             rc = SQLITE_PERM;
113757             goto parse_uri_out;
113758           }
113759           flags = (flags & ~mask) | mode;
113760         }
113761       }
113762
113763       zOpt = &zVal[nVal+1];
113764     }
113765
113766   }else{
113767     zFile = sqlite3_malloc(nUri+2);
113768     if( !zFile ) return SQLITE_NOMEM;
113769     memcpy(zFile, zUri, nUri);
113770     zFile[nUri] = '\0';
113771     zFile[nUri+1] = '\0';
113772     flags &= ~SQLITE_OPEN_URI;
113773   }
113774
113775   *ppVfs = sqlite3_vfs_find(zVfs);
113776   if( *ppVfs==0 ){
113777     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
113778     rc = SQLITE_ERROR;
113779   }
113780  parse_uri_out:
113781   if( rc!=SQLITE_OK ){
113782     sqlite3_free(zFile);
113783     zFile = 0;
113784   }
113785   *pFlags = flags;
113786   *pzFile = zFile;
113787   return rc;
113788 }
113789
113790
113791 /*
113792 ** This routine does the work of opening a database on behalf of
113793 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
113794 ** is UTF-8 encoded.
113795 */
113796 static int openDatabase(
113797   const char *zFilename, /* Database filename UTF-8 encoded */
113798   sqlite3 **ppDb,        /* OUT: Returned database handle */
113799   unsigned int flags,    /* Operational flags */
113800   const char *zVfs       /* Name of the VFS to use */
113801 ){
113802   sqlite3 *db;                    /* Store allocated handle here */
113803   int rc;                         /* Return code */
113804   int isThreadsafe;               /* True for threadsafe connections */
113805   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
113806   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
113807
113808   *ppDb = 0;
113809 #ifndef SQLITE_OMIT_AUTOINIT
113810   rc = sqlite3_initialize();
113811   if( rc ) return rc;
113812 #endif
113813
113814   /* Only allow sensible combinations of bits in the flags argument.  
113815   ** Throw an error if any non-sense combination is used.  If we
113816   ** do not block illegal combinations here, it could trigger
113817   ** assert() statements in deeper layers.  Sensible combinations
113818   ** are:
113819   **
113820   **  1:  SQLITE_OPEN_READONLY
113821   **  2:  SQLITE_OPEN_READWRITE
113822   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
113823   */
113824   assert( SQLITE_OPEN_READONLY  == 0x01 );
113825   assert( SQLITE_OPEN_READWRITE == 0x02 );
113826   assert( SQLITE_OPEN_CREATE    == 0x04 );
113827   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
113828   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
113829   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
113830   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
113831
113832   if( sqlite3GlobalConfig.bCoreMutex==0 ){
113833     isThreadsafe = 0;
113834   }else if( flags & SQLITE_OPEN_NOMUTEX ){
113835     isThreadsafe = 0;
113836   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
113837     isThreadsafe = 1;
113838   }else{
113839     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
113840   }
113841   if( flags & SQLITE_OPEN_PRIVATECACHE ){
113842     flags &= ~SQLITE_OPEN_SHAREDCACHE;
113843   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
113844     flags |= SQLITE_OPEN_SHAREDCACHE;
113845   }
113846
113847   /* Remove harmful bits from the flags parameter
113848   **
113849   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
113850   ** dealt with in the previous code block.  Besides these, the only
113851   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
113852   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
113853   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
113854   ** off all other flags.
113855   */
113856   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
113857                SQLITE_OPEN_EXCLUSIVE |
113858                SQLITE_OPEN_MAIN_DB |
113859                SQLITE_OPEN_TEMP_DB | 
113860                SQLITE_OPEN_TRANSIENT_DB | 
113861                SQLITE_OPEN_MAIN_JOURNAL | 
113862                SQLITE_OPEN_TEMP_JOURNAL | 
113863                SQLITE_OPEN_SUBJOURNAL | 
113864                SQLITE_OPEN_MASTER_JOURNAL |
113865                SQLITE_OPEN_NOMUTEX |
113866                SQLITE_OPEN_FULLMUTEX |
113867                SQLITE_OPEN_WAL
113868              );
113869
113870   /* Allocate the sqlite data structure */
113871   db = sqlite3MallocZero( sizeof(sqlite3) );
113872   if( db==0 ) goto opendb_out;
113873   if( isThreadsafe ){
113874     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
113875     if( db->mutex==0 ){
113876       sqlite3_free(db);
113877       db = 0;
113878       goto opendb_out;
113879     }
113880   }
113881   sqlite3_mutex_enter(db->mutex);
113882   db->errMask = 0xff;
113883   db->nDb = 2;
113884   db->magic = SQLITE_MAGIC_BUSY;
113885   db->aDb = db->aDbStatic;
113886
113887   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
113888   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
113889   db->autoCommit = 1;
113890   db->nextAutovac = -1;
113891   db->nextPagesize = 0;
113892   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
113893 #if SQLITE_DEFAULT_FILE_FORMAT<4
113894                  | SQLITE_LegacyFileFmt
113895 #endif
113896 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
113897                  | SQLITE_LoadExtension
113898 #endif
113899 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
113900                  | SQLITE_RecTriggers
113901 #endif
113902 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
113903                  | SQLITE_ForeignKeys
113904 #endif
113905       ;
113906   sqlite3HashInit(&db->aCollSeq);
113907 #ifndef SQLITE_OMIT_VIRTUALTABLE
113908   sqlite3HashInit(&db->aModule);
113909 #endif
113910
113911   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
113912   ** and UTF-16, so add a version for each to avoid any unnecessary
113913   ** conversions. The only error that can occur here is a malloc() failure.
113914   */
113915   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
113916   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
113917   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
113918   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
113919   if( db->mallocFailed ){
113920     goto opendb_out;
113921   }
113922   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
113923   assert( db->pDfltColl!=0 );
113924
113925   /* Also add a UTF-8 case-insensitive collation sequence. */
113926   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
113927
113928   /* Parse the filename/URI argument. */
113929   db->openFlags = flags;
113930   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
113931   if( rc!=SQLITE_OK ){
113932     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
113933     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
113934     sqlite3_free(zErrMsg);
113935     goto opendb_out;
113936   }
113937
113938   /* Open the backend database driver */
113939   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
113940                         flags | SQLITE_OPEN_MAIN_DB);
113941   if( rc!=SQLITE_OK ){
113942     if( rc==SQLITE_IOERR_NOMEM ){
113943       rc = SQLITE_NOMEM;
113944     }
113945     sqlite3Error(db, rc, 0);
113946     goto opendb_out;
113947   }
113948   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
113949   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
113950
113951
113952   /* The default safety_level for the main database is 'full'; for the temp
113953   ** database it is 'NONE'. This matches the pager layer defaults.  
113954   */
113955   db->aDb[0].zName = "main";
113956   db->aDb[0].safety_level = 3;
113957   db->aDb[1].zName = "temp";
113958   db->aDb[1].safety_level = 1;
113959
113960   db->magic = SQLITE_MAGIC_OPEN;
113961   if( db->mallocFailed ){
113962     goto opendb_out;
113963   }
113964
113965   /* Register all built-in functions, but do not attempt to read the
113966   ** database schema yet. This is delayed until the first time the database
113967   ** is accessed.
113968   */
113969   sqlite3Error(db, SQLITE_OK, 0);
113970   sqlite3RegisterBuiltinFunctions(db);
113971
113972   /* Load automatic extensions - extensions that have been registered
113973   ** using the sqlite3_automatic_extension() API.
113974   */
113975   rc = sqlite3_errcode(db);
113976   if( rc==SQLITE_OK ){
113977     sqlite3AutoLoadExtensions(db);
113978     rc = sqlite3_errcode(db);
113979     if( rc!=SQLITE_OK ){
113980       goto opendb_out;
113981     }
113982   }
113983
113984 #ifdef SQLITE_ENABLE_FTS1
113985   if( !db->mallocFailed ){
113986     extern int sqlite3Fts1Init(sqlite3*);
113987     rc = sqlite3Fts1Init(db);
113988   }
113989 #endif
113990
113991 #ifdef SQLITE_ENABLE_FTS2
113992   if( !db->mallocFailed && rc==SQLITE_OK ){
113993     extern int sqlite3Fts2Init(sqlite3*);
113994     rc = sqlite3Fts2Init(db);
113995   }
113996 #endif
113997
113998 #ifdef SQLITE_ENABLE_FTS3
113999   if( !db->mallocFailed && rc==SQLITE_OK ){
114000     rc = sqlite3Fts3Init(db);
114001   }
114002 #endif
114003
114004 #ifdef SQLITE_ENABLE_ICU
114005   if( !db->mallocFailed && rc==SQLITE_OK ){
114006     rc = sqlite3IcuInit(db);
114007   }
114008 #endif
114009
114010 #ifdef SQLITE_ENABLE_RTREE
114011   if( !db->mallocFailed && rc==SQLITE_OK){
114012     rc = sqlite3RtreeInit(db);
114013   }
114014 #endif
114015
114016   sqlite3Error(db, rc, 0);
114017
114018   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
114019   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
114020   ** mode.  Doing nothing at all also makes NORMAL the default.
114021   */
114022 #ifdef SQLITE_DEFAULT_LOCKING_MODE
114023   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
114024   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
114025                           SQLITE_DEFAULT_LOCKING_MODE);
114026 #endif
114027
114028   /* Enable the lookaside-malloc subsystem */
114029   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
114030                         sqlite3GlobalConfig.nLookaside);
114031
114032   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
114033
114034 opendb_out:
114035   sqlite3_free(zOpen);
114036   if( db ){
114037     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
114038     sqlite3_mutex_leave(db->mutex);
114039   }
114040   rc = sqlite3_errcode(db);
114041   assert( db!=0 || rc==SQLITE_NOMEM );
114042   if( rc==SQLITE_NOMEM ){
114043     sqlite3_close(db);
114044     db = 0;
114045   }else if( rc!=SQLITE_OK ){
114046     db->magic = SQLITE_MAGIC_SICK;
114047   }
114048   *ppDb = db;
114049   return sqlite3ApiExit(0, rc);
114050 }
114051
114052 /*
114053 ** Open a new database handle.
114054 */
114055 SQLITE_API int sqlite3_open(
114056   const char *zFilename, 
114057   sqlite3 **ppDb 
114058 ){
114059   return openDatabase(zFilename, ppDb,
114060                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114061 }
114062 SQLITE_API int sqlite3_open_v2(
114063   const char *filename,   /* Database filename (UTF-8) */
114064   sqlite3 **ppDb,         /* OUT: SQLite db handle */
114065   int flags,              /* Flags */
114066   const char *zVfs        /* Name of VFS module to use */
114067 ){
114068   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
114069 }
114070
114071 #ifndef SQLITE_OMIT_UTF16
114072 /*
114073 ** Open a new database handle.
114074 */
114075 SQLITE_API int sqlite3_open16(
114076   const void *zFilename, 
114077   sqlite3 **ppDb
114078 ){
114079   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
114080   sqlite3_value *pVal;
114081   int rc;
114082
114083   assert( zFilename );
114084   assert( ppDb );
114085   *ppDb = 0;
114086 #ifndef SQLITE_OMIT_AUTOINIT
114087   rc = sqlite3_initialize();
114088   if( rc ) return rc;
114089 #endif
114090   pVal = sqlite3ValueNew(0);
114091   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114092   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114093   if( zFilename8 ){
114094     rc = openDatabase(zFilename8, ppDb,
114095                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114096     assert( *ppDb || rc==SQLITE_NOMEM );
114097     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
114098       ENC(*ppDb) = SQLITE_UTF16NATIVE;
114099     }
114100   }else{
114101     rc = SQLITE_NOMEM;
114102   }
114103   sqlite3ValueFree(pVal);
114104
114105   return sqlite3ApiExit(0, rc);
114106 }
114107 #endif /* SQLITE_OMIT_UTF16 */
114108
114109 /*
114110 ** Register a new collation sequence with the database handle db.
114111 */
114112 SQLITE_API int sqlite3_create_collation(
114113   sqlite3* db, 
114114   const char *zName, 
114115   int enc, 
114116   void* pCtx,
114117   int(*xCompare)(void*,int,const void*,int,const void*)
114118 ){
114119   int rc;
114120   sqlite3_mutex_enter(db->mutex);
114121   assert( !db->mallocFailed );
114122   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
114123   rc = sqlite3ApiExit(db, rc);
114124   sqlite3_mutex_leave(db->mutex);
114125   return rc;
114126 }
114127
114128 /*
114129 ** Register a new collation sequence with the database handle db.
114130 */
114131 SQLITE_API int sqlite3_create_collation_v2(
114132   sqlite3* db, 
114133   const char *zName, 
114134   int enc, 
114135   void* pCtx,
114136   int(*xCompare)(void*,int,const void*,int,const void*),
114137   void(*xDel)(void*)
114138 ){
114139   int rc;
114140   sqlite3_mutex_enter(db->mutex);
114141   assert( !db->mallocFailed );
114142   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
114143   rc = sqlite3ApiExit(db, rc);
114144   sqlite3_mutex_leave(db->mutex);
114145   return rc;
114146 }
114147
114148 #ifndef SQLITE_OMIT_UTF16
114149 /*
114150 ** Register a new collation sequence with the database handle db.
114151 */
114152 SQLITE_API int sqlite3_create_collation16(
114153   sqlite3* db, 
114154   const void *zName,
114155   int enc, 
114156   void* pCtx,
114157   int(*xCompare)(void*,int,const void*,int,const void*)
114158 ){
114159   int rc = SQLITE_OK;
114160   char *zName8;
114161   sqlite3_mutex_enter(db->mutex);
114162   assert( !db->mallocFailed );
114163   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
114164   if( zName8 ){
114165     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
114166     sqlite3DbFree(db, zName8);
114167   }
114168   rc = sqlite3ApiExit(db, rc);
114169   sqlite3_mutex_leave(db->mutex);
114170   return rc;
114171 }
114172 #endif /* SQLITE_OMIT_UTF16 */
114173
114174 /*
114175 ** Register a collation sequence factory callback with the database handle
114176 ** db. Replace any previously installed collation sequence factory.
114177 */
114178 SQLITE_API int sqlite3_collation_needed(
114179   sqlite3 *db, 
114180   void *pCollNeededArg, 
114181   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
114182 ){
114183   sqlite3_mutex_enter(db->mutex);
114184   db->xCollNeeded = xCollNeeded;
114185   db->xCollNeeded16 = 0;
114186   db->pCollNeededArg = pCollNeededArg;
114187   sqlite3_mutex_leave(db->mutex);
114188   return SQLITE_OK;
114189 }
114190
114191 #ifndef SQLITE_OMIT_UTF16
114192 /*
114193 ** Register a collation sequence factory callback with the database handle
114194 ** db. Replace any previously installed collation sequence factory.
114195 */
114196 SQLITE_API int sqlite3_collation_needed16(
114197   sqlite3 *db, 
114198   void *pCollNeededArg, 
114199   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
114200 ){
114201   sqlite3_mutex_enter(db->mutex);
114202   db->xCollNeeded = 0;
114203   db->xCollNeeded16 = xCollNeeded16;
114204   db->pCollNeededArg = pCollNeededArg;
114205   sqlite3_mutex_leave(db->mutex);
114206   return SQLITE_OK;
114207 }
114208 #endif /* SQLITE_OMIT_UTF16 */
114209
114210 #ifndef SQLITE_OMIT_DEPRECATED
114211 /*
114212 ** This function is now an anachronism. It used to be used to recover from a
114213 ** malloc() failure, but SQLite now does this automatically.
114214 */
114215 SQLITE_API int sqlite3_global_recover(void){
114216   return SQLITE_OK;
114217 }
114218 #endif
114219
114220 /*
114221 ** Test to see whether or not the database connection is in autocommit
114222 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
114223 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
114224 ** by the next COMMIT or ROLLBACK.
114225 **
114226 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
114227 */
114228 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
114229   return db->autoCommit;
114230 }
114231
114232 /*
114233 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
114234 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
114235 ** constants.  They server two purposes:
114236 **
114237 **   1.  Serve as a convenient place to set a breakpoint in a debugger
114238 **       to detect when version error conditions occurs.
114239 **
114240 **   2.  Invoke sqlite3_log() to provide the source code location where
114241 **       a low-level error is first detected.
114242 */
114243 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
114244   testcase( sqlite3GlobalConfig.xLog!=0 );
114245   sqlite3_log(SQLITE_CORRUPT,
114246               "database corruption at line %d of [%.10s]",
114247               lineno, 20+sqlite3_sourceid());
114248   return SQLITE_CORRUPT;
114249 }
114250 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
114251   testcase( sqlite3GlobalConfig.xLog!=0 );
114252   sqlite3_log(SQLITE_MISUSE, 
114253               "misuse at line %d of [%.10s]",
114254               lineno, 20+sqlite3_sourceid());
114255   return SQLITE_MISUSE;
114256 }
114257 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
114258   testcase( sqlite3GlobalConfig.xLog!=0 );
114259   sqlite3_log(SQLITE_CANTOPEN, 
114260               "cannot open file at line %d of [%.10s]",
114261               lineno, 20+sqlite3_sourceid());
114262   return SQLITE_CANTOPEN;
114263 }
114264
114265
114266 #ifndef SQLITE_OMIT_DEPRECATED
114267 /*
114268 ** This is a convenience routine that makes sure that all thread-specific
114269 ** data for this thread has been deallocated.
114270 **
114271 ** SQLite no longer uses thread-specific data so this routine is now a
114272 ** no-op.  It is retained for historical compatibility.
114273 */
114274 SQLITE_API void sqlite3_thread_cleanup(void){
114275 }
114276 #endif
114277
114278 /*
114279 ** Return meta information about a specific column of a database table.
114280 ** See comment in sqlite3.h (sqlite.h.in) for details.
114281 */
114282 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114283 SQLITE_API int sqlite3_table_column_metadata(
114284   sqlite3 *db,                /* Connection handle */
114285   const char *zDbName,        /* Database name or NULL */
114286   const char *zTableName,     /* Table name */
114287   const char *zColumnName,    /* Column name */
114288   char const **pzDataType,    /* OUTPUT: Declared data type */
114289   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
114290   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
114291   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
114292   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
114293 ){
114294   int rc;
114295   char *zErrMsg = 0;
114296   Table *pTab = 0;
114297   Column *pCol = 0;
114298   int iCol;
114299
114300   char const *zDataType = 0;
114301   char const *zCollSeq = 0;
114302   int notnull = 0;
114303   int primarykey = 0;
114304   int autoinc = 0;
114305
114306   /* Ensure the database schema has been loaded */
114307   sqlite3_mutex_enter(db->mutex);
114308   sqlite3BtreeEnterAll(db);
114309   rc = sqlite3Init(db, &zErrMsg);
114310   if( SQLITE_OK!=rc ){
114311     goto error_out;
114312   }
114313
114314   /* Locate the table in question */
114315   pTab = sqlite3FindTable(db, zTableName, zDbName);
114316   if( !pTab || pTab->pSelect ){
114317     pTab = 0;
114318     goto error_out;
114319   }
114320
114321   /* Find the column for which info is requested */
114322   if( sqlite3IsRowid(zColumnName) ){
114323     iCol = pTab->iPKey;
114324     if( iCol>=0 ){
114325       pCol = &pTab->aCol[iCol];
114326     }
114327   }else{
114328     for(iCol=0; iCol<pTab->nCol; iCol++){
114329       pCol = &pTab->aCol[iCol];
114330       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
114331         break;
114332       }
114333     }
114334     if( iCol==pTab->nCol ){
114335       pTab = 0;
114336       goto error_out;
114337     }
114338   }
114339
114340   /* The following block stores the meta information that will be returned
114341   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
114342   ** and autoinc. At this point there are two possibilities:
114343   ** 
114344   **     1. The specified column name was rowid", "oid" or "_rowid_" 
114345   **        and there is no explicitly declared IPK column. 
114346   **
114347   **     2. The table is not a view and the column name identified an 
114348   **        explicitly declared column. Copy meta information from *pCol.
114349   */ 
114350   if( pCol ){
114351     zDataType = pCol->zType;
114352     zCollSeq = pCol->zColl;
114353     notnull = pCol->notNull!=0;
114354     primarykey  = pCol->isPrimKey!=0;
114355     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
114356   }else{
114357     zDataType = "INTEGER";
114358     primarykey = 1;
114359   }
114360   if( !zCollSeq ){
114361     zCollSeq = "BINARY";
114362   }
114363
114364 error_out:
114365   sqlite3BtreeLeaveAll(db);
114366
114367   /* Whether the function call succeeded or failed, set the output parameters
114368   ** to whatever their local counterparts contain. If an error did occur,
114369   ** this has the effect of zeroing all output parameters.
114370   */
114371   if( pzDataType ) *pzDataType = zDataType;
114372   if( pzCollSeq ) *pzCollSeq = zCollSeq;
114373   if( pNotNull ) *pNotNull = notnull;
114374   if( pPrimaryKey ) *pPrimaryKey = primarykey;
114375   if( pAutoinc ) *pAutoinc = autoinc;
114376
114377   if( SQLITE_OK==rc && !pTab ){
114378     sqlite3DbFree(db, zErrMsg);
114379     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
114380         zColumnName);
114381     rc = SQLITE_ERROR;
114382   }
114383   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
114384   sqlite3DbFree(db, zErrMsg);
114385   rc = sqlite3ApiExit(db, rc);
114386   sqlite3_mutex_leave(db->mutex);
114387   return rc;
114388 }
114389 #endif
114390
114391 /*
114392 ** Sleep for a little while.  Return the amount of time slept.
114393 */
114394 SQLITE_API int sqlite3_sleep(int ms){
114395   sqlite3_vfs *pVfs;
114396   int rc;
114397   pVfs = sqlite3_vfs_find(0);
114398   if( pVfs==0 ) return 0;
114399
114400   /* This function works in milliseconds, but the underlying OsSleep() 
114401   ** API uses microseconds. Hence the 1000's.
114402   */
114403   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
114404   return rc;
114405 }
114406
114407 /*
114408 ** Enable or disable the extended result codes.
114409 */
114410 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
114411   sqlite3_mutex_enter(db->mutex);
114412   db->errMask = onoff ? 0xffffffff : 0xff;
114413   sqlite3_mutex_leave(db->mutex);
114414   return SQLITE_OK;
114415 }
114416
114417 /*
114418 ** Invoke the xFileControl method on a particular database.
114419 */
114420 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
114421   int rc = SQLITE_ERROR;
114422   Btree *pBtree;
114423
114424   sqlite3_mutex_enter(db->mutex);
114425   pBtree = sqlite3DbNameToBtree(db, zDbName);
114426   if( pBtree ){
114427     Pager *pPager;
114428     sqlite3_file *fd;
114429     sqlite3BtreeEnter(pBtree);
114430     pPager = sqlite3BtreePager(pBtree);
114431     assert( pPager!=0 );
114432     fd = sqlite3PagerFile(pPager);
114433     assert( fd!=0 );
114434     if( op==SQLITE_FCNTL_FILE_POINTER ){
114435       *(sqlite3_file**)pArg = fd;
114436       rc = SQLITE_OK;
114437     }else if( fd->pMethods ){
114438       rc = sqlite3OsFileControl(fd, op, pArg);
114439     }else{
114440       rc = SQLITE_NOTFOUND;
114441     }
114442     sqlite3BtreeLeave(pBtree);
114443   }
114444   sqlite3_mutex_leave(db->mutex);
114445   return rc;   
114446 }
114447
114448 /*
114449 ** Interface to the testing logic.
114450 */
114451 SQLITE_API int sqlite3_test_control(int op, ...){
114452   int rc = 0;
114453 #ifndef SQLITE_OMIT_BUILTIN_TEST
114454   va_list ap;
114455   va_start(ap, op);
114456   switch( op ){
114457
114458     /*
114459     ** Save the current state of the PRNG.
114460     */
114461     case SQLITE_TESTCTRL_PRNG_SAVE: {
114462       sqlite3PrngSaveState();
114463       break;
114464     }
114465
114466     /*
114467     ** Restore the state of the PRNG to the last state saved using
114468     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
114469     ** this verb acts like PRNG_RESET.
114470     */
114471     case SQLITE_TESTCTRL_PRNG_RESTORE: {
114472       sqlite3PrngRestoreState();
114473       break;
114474     }
114475
114476     /*
114477     ** Reset the PRNG back to its uninitialized state.  The next call
114478     ** to sqlite3_randomness() will reseed the PRNG using a single call
114479     ** to the xRandomness method of the default VFS.
114480     */
114481     case SQLITE_TESTCTRL_PRNG_RESET: {
114482       sqlite3PrngResetState();
114483       break;
114484     }
114485
114486     /*
114487     **  sqlite3_test_control(BITVEC_TEST, size, program)
114488     **
114489     ** Run a test against a Bitvec object of size.  The program argument
114490     ** is an array of integers that defines the test.  Return -1 on a
114491     ** memory allocation error, 0 on success, or non-zero for an error.
114492     ** See the sqlite3BitvecBuiltinTest() for additional information.
114493     */
114494     case SQLITE_TESTCTRL_BITVEC_TEST: {
114495       int sz = va_arg(ap, int);
114496       int *aProg = va_arg(ap, int*);
114497       rc = sqlite3BitvecBuiltinTest(sz, aProg);
114498       break;
114499     }
114500
114501     /*
114502     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
114503     **
114504     ** Register hooks to call to indicate which malloc() failures 
114505     ** are benign.
114506     */
114507     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
114508       typedef void (*void_function)(void);
114509       void_function xBenignBegin;
114510       void_function xBenignEnd;
114511       xBenignBegin = va_arg(ap, void_function);
114512       xBenignEnd = va_arg(ap, void_function);
114513       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
114514       break;
114515     }
114516
114517     /*
114518     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
114519     **
114520     ** Set the PENDING byte to the value in the argument, if X>0.
114521     ** Make no changes if X==0.  Return the value of the pending byte
114522     ** as it existing before this routine was called.
114523     **
114524     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
114525     ** an incompatible database file format.  Changing the PENDING byte
114526     ** while any database connection is open results in undefined and
114527     ** dileterious behavior.
114528     */
114529     case SQLITE_TESTCTRL_PENDING_BYTE: {
114530       rc = PENDING_BYTE;
114531 #ifndef SQLITE_OMIT_WSD
114532       {
114533         unsigned int newVal = va_arg(ap, unsigned int);
114534         if( newVal ) sqlite3PendingByte = newVal;
114535       }
114536 #endif
114537       break;
114538     }
114539
114540     /*
114541     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
114542     **
114543     ** This action provides a run-time test to see whether or not
114544     ** assert() was enabled at compile-time.  If X is true and assert()
114545     ** is enabled, then the return value is true.  If X is true and
114546     ** assert() is disabled, then the return value is zero.  If X is
114547     ** false and assert() is enabled, then the assertion fires and the
114548     ** process aborts.  If X is false and assert() is disabled, then the
114549     ** return value is zero.
114550     */
114551     case SQLITE_TESTCTRL_ASSERT: {
114552       volatile int x = 0;
114553       assert( (x = va_arg(ap,int))!=0 );
114554       rc = x;
114555       break;
114556     }
114557
114558
114559     /*
114560     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
114561     **
114562     ** This action provides a run-time test to see how the ALWAYS and
114563     ** NEVER macros were defined at compile-time.
114564     **
114565     ** The return value is ALWAYS(X).  
114566     **
114567     ** The recommended test is X==2.  If the return value is 2, that means
114568     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
114569     ** default setting.  If the return value is 1, then ALWAYS() is either
114570     ** hard-coded to true or else it asserts if its argument is false.
114571     ** The first behavior (hard-coded to true) is the case if
114572     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
114573     ** behavior (assert if the argument to ALWAYS() is false) is the case if
114574     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
114575     **
114576     ** The run-time test procedure might look something like this:
114577     **
114578     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
114579     **      // ALWAYS() and NEVER() are no-op pass-through macros
114580     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
114581     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
114582     **    }else{
114583     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
114584     **    }
114585     */
114586     case SQLITE_TESTCTRL_ALWAYS: {
114587       int x = va_arg(ap,int);
114588       rc = ALWAYS(x);
114589       break;
114590     }
114591
114592     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
114593     **
114594     ** Set the nReserve size to N for the main database on the database
114595     ** connection db.
114596     */
114597     case SQLITE_TESTCTRL_RESERVE: {
114598       sqlite3 *db = va_arg(ap, sqlite3*);
114599       int x = va_arg(ap,int);
114600       sqlite3_mutex_enter(db->mutex);
114601       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
114602       sqlite3_mutex_leave(db->mutex);
114603       break;
114604     }
114605
114606     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
114607     **
114608     ** Enable or disable various optimizations for testing purposes.  The 
114609     ** argument N is a bitmask of optimizations to be disabled.  For normal
114610     ** operation N should be 0.  The idea is that a test program (like the
114611     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
114612     ** with various optimizations disabled to verify that the same answer
114613     ** is obtained in every case.
114614     */
114615     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
114616       sqlite3 *db = va_arg(ap, sqlite3*);
114617       int x = va_arg(ap,int);
114618       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
114619       break;
114620     }
114621
114622 #ifdef SQLITE_N_KEYWORD
114623     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
114624     **
114625     ** If zWord is a keyword recognized by the parser, then return the
114626     ** number of keywords.  Or if zWord is not a keyword, return 0.
114627     ** 
114628     ** This test feature is only available in the amalgamation since
114629     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
114630     ** is built using separate source files.
114631     */
114632     case SQLITE_TESTCTRL_ISKEYWORD: {
114633       const char *zWord = va_arg(ap, const char*);
114634       int n = sqlite3Strlen30(zWord);
114635       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
114636       break;
114637     }
114638 #endif 
114639
114640     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
114641     **
114642     ** Pass pFree into sqlite3ScratchFree(). 
114643     ** If sz>0 then allocate a scratch buffer into pNew.  
114644     */
114645     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
114646       void *pFree, **ppNew;
114647       int sz;
114648       sz = va_arg(ap, int);
114649       ppNew = va_arg(ap, void**);
114650       pFree = va_arg(ap, void*);
114651       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
114652       sqlite3ScratchFree(pFree);
114653       break;
114654     }
114655
114656     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
114657     **
114658     ** If parameter onoff is non-zero, configure the wrappers so that all
114659     ** subsequent calls to localtime() and variants fail. If onoff is zero,
114660     ** undo this setting.
114661     */
114662     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
114663       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
114664       break;
114665     }
114666
114667 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
114668     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
114669     **                        sqlite3_stmt*,const char**);
114670     **
114671     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
114672     ** a string that describes the optimized parse tree.  This test-control
114673     ** returns a pointer to that string.
114674     */
114675     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
114676       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
114677       const char **pzRet = va_arg(ap, const char**);
114678       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
114679       break;
114680     }
114681 #endif
114682
114683   }
114684   va_end(ap);
114685 #endif /* SQLITE_OMIT_BUILTIN_TEST */
114686   return rc;
114687 }
114688
114689 /*
114690 ** This is a utility routine, useful to VFS implementations, that checks
114691 ** to see if a database file was a URI that contained a specific query 
114692 ** parameter, and if so obtains the value of the query parameter.
114693 **
114694 ** The zFilename argument is the filename pointer passed into the xOpen()
114695 ** method of a VFS implementation.  The zParam argument is the name of the
114696 ** query parameter we seek.  This routine returns the value of the zParam
114697 ** parameter if it exists.  If the parameter does not exist, this routine
114698 ** returns a NULL pointer.
114699 */
114700 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
114701   if( zFilename==0 ) return 0;
114702   zFilename += sqlite3Strlen30(zFilename) + 1;
114703   while( zFilename[0] ){
114704     int x = strcmp(zFilename, zParam);
114705     zFilename += sqlite3Strlen30(zFilename) + 1;
114706     if( x==0 ) return zFilename;
114707     zFilename += sqlite3Strlen30(zFilename) + 1;
114708   }
114709   return 0;
114710 }
114711
114712 /*
114713 ** Return a boolean value for a query parameter.
114714 */
114715 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
114716   const char *z = sqlite3_uri_parameter(zFilename, zParam);
114717   bDflt = bDflt!=0;
114718   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
114719 }
114720
114721 /*
114722 ** Return a 64-bit integer value for a query parameter.
114723 */
114724 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
114725   const char *zFilename,    /* Filename as passed to xOpen */
114726   const char *zParam,       /* URI parameter sought */
114727   sqlite3_int64 bDflt       /* return if parameter is missing */
114728 ){
114729   const char *z = sqlite3_uri_parameter(zFilename, zParam);
114730   sqlite3_int64 v;
114731   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
114732     bDflt = v;
114733   }
114734   return bDflt;
114735 }
114736
114737 /*
114738 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
114739 */
114740 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
114741   int i;
114742   for(i=0; i<db->nDb; i++){
114743     if( db->aDb[i].pBt
114744      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
114745     ){
114746       return db->aDb[i].pBt;
114747     }
114748   }
114749   return 0;
114750 }
114751
114752 /*
114753 ** Return the filename of the database associated with a database
114754 ** connection.
114755 */
114756 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
114757   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
114758   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
114759 }
114760
114761 /*
114762 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
114763 ** no such database exists.
114764 */
114765 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
114766   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
114767   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
114768 }
114769
114770 /************** End of main.c ************************************************/
114771 /************** Begin file notify.c ******************************************/
114772 /*
114773 ** 2009 March 3
114774 **
114775 ** The author disclaims copyright to this source code.  In place of
114776 ** a legal notice, here is a blessing:
114777 **
114778 **    May you do good and not evil.
114779 **    May you find forgiveness for yourself and forgive others.
114780 **    May you share freely, never taking more than you give.
114781 **
114782 *************************************************************************
114783 **
114784 ** This file contains the implementation of the sqlite3_unlock_notify()
114785 ** API method and its associated functionality.
114786 */
114787
114788 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
114789 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
114790
114791 /*
114792 ** Public interfaces:
114793 **
114794 **   sqlite3ConnectionBlocked()
114795 **   sqlite3ConnectionUnlocked()
114796 **   sqlite3ConnectionClosed()
114797 **   sqlite3_unlock_notify()
114798 */
114799
114800 #define assertMutexHeld() \
114801   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
114802
114803 /*
114804 ** Head of a linked list of all sqlite3 objects created by this process
114805 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
114806 ** is not NULL. This variable may only accessed while the STATIC_MASTER
114807 ** mutex is held.
114808 */
114809 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
114810
114811 #ifndef NDEBUG
114812 /*
114813 ** This function is a complex assert() that verifies the following 
114814 ** properties of the blocked connections list:
114815 **
114816 **   1) Each entry in the list has a non-NULL value for either 
114817 **      pUnlockConnection or pBlockingConnection, or both.
114818 **
114819 **   2) All entries in the list that share a common value for 
114820 **      xUnlockNotify are grouped together.
114821 **
114822 **   3) If the argument db is not NULL, then none of the entries in the
114823 **      blocked connections list have pUnlockConnection or pBlockingConnection
114824 **      set to db. This is used when closing connection db.
114825 */
114826 static void checkListProperties(sqlite3 *db){
114827   sqlite3 *p;
114828   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
114829     int seen = 0;
114830     sqlite3 *p2;
114831
114832     /* Verify property (1) */
114833     assert( p->pUnlockConnection || p->pBlockingConnection );
114834
114835     /* Verify property (2) */
114836     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
114837       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
114838       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
114839       assert( db==0 || p->pUnlockConnection!=db );
114840       assert( db==0 || p->pBlockingConnection!=db );
114841     }
114842   }
114843 }
114844 #else
114845 # define checkListProperties(x)
114846 #endif
114847
114848 /*
114849 ** Remove connection db from the blocked connections list. If connection
114850 ** db is not currently a part of the list, this function is a no-op.
114851 */
114852 static void removeFromBlockedList(sqlite3 *db){
114853   sqlite3 **pp;
114854   assertMutexHeld();
114855   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
114856     if( *pp==db ){
114857       *pp = (*pp)->pNextBlocked;
114858       break;
114859     }
114860   }
114861 }
114862
114863 /*
114864 ** Add connection db to the blocked connections list. It is assumed
114865 ** that it is not already a part of the list.
114866 */
114867 static void addToBlockedList(sqlite3 *db){
114868   sqlite3 **pp;
114869   assertMutexHeld();
114870   for(
114871     pp=&sqlite3BlockedList; 
114872     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
114873     pp=&(*pp)->pNextBlocked
114874   );
114875   db->pNextBlocked = *pp;
114876   *pp = db;
114877 }
114878
114879 /*
114880 ** Obtain the STATIC_MASTER mutex.
114881 */
114882 static void enterMutex(void){
114883   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
114884   checkListProperties(0);
114885 }
114886
114887 /*
114888 ** Release the STATIC_MASTER mutex.
114889 */
114890 static void leaveMutex(void){
114891   assertMutexHeld();
114892   checkListProperties(0);
114893   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
114894 }
114895
114896 /*
114897 ** Register an unlock-notify callback.
114898 **
114899 ** This is called after connection "db" has attempted some operation
114900 ** but has received an SQLITE_LOCKED error because another connection
114901 ** (call it pOther) in the same process was busy using the same shared
114902 ** cache.  pOther is found by looking at db->pBlockingConnection.
114903 **
114904 ** If there is no blocking connection, the callback is invoked immediately,
114905 ** before this routine returns.
114906 **
114907 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
114908 ** a deadlock.
114909 **
114910 ** Otherwise, make arrangements to invoke xNotify when pOther drops
114911 ** its locks.
114912 **
114913 ** Each call to this routine overrides any prior callbacks registered
114914 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
114915 ** cancelled.
114916 */
114917 SQLITE_API int sqlite3_unlock_notify(
114918   sqlite3 *db,
114919   void (*xNotify)(void **, int),
114920   void *pArg
114921 ){
114922   int rc = SQLITE_OK;
114923
114924   sqlite3_mutex_enter(db->mutex);
114925   enterMutex();
114926
114927   if( xNotify==0 ){
114928     removeFromBlockedList(db);
114929     db->pBlockingConnection = 0;
114930     db->pUnlockConnection = 0;
114931     db->xUnlockNotify = 0;
114932     db->pUnlockArg = 0;
114933   }else if( 0==db->pBlockingConnection ){
114934     /* The blocking transaction has been concluded. Or there never was a 
114935     ** blocking transaction. In either case, invoke the notify callback
114936     ** immediately. 
114937     */
114938     xNotify(&pArg, 1);
114939   }else{
114940     sqlite3 *p;
114941
114942     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
114943     if( p ){
114944       rc = SQLITE_LOCKED;              /* Deadlock detected. */
114945     }else{
114946       db->pUnlockConnection = db->pBlockingConnection;
114947       db->xUnlockNotify = xNotify;
114948       db->pUnlockArg = pArg;
114949       removeFromBlockedList(db);
114950       addToBlockedList(db);
114951     }
114952   }
114953
114954   leaveMutex();
114955   assert( !db->mallocFailed );
114956   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
114957   sqlite3_mutex_leave(db->mutex);
114958   return rc;
114959 }
114960
114961 /*
114962 ** This function is called while stepping or preparing a statement 
114963 ** associated with connection db. The operation will return SQLITE_LOCKED
114964 ** to the user because it requires a lock that will not be available
114965 ** until connection pBlocker concludes its current transaction.
114966 */
114967 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
114968   enterMutex();
114969   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
114970     addToBlockedList(db);
114971   }
114972   db->pBlockingConnection = pBlocker;
114973   leaveMutex();
114974 }
114975
114976 /*
114977 ** This function is called when
114978 ** the transaction opened by database db has just finished. Locks held 
114979 ** by database connection db have been released.
114980 **
114981 ** This function loops through each entry in the blocked connections
114982 ** list and does the following:
114983 **
114984 **   1) If the sqlite3.pBlockingConnection member of a list entry is
114985 **      set to db, then set pBlockingConnection=0.
114986 **
114987 **   2) If the sqlite3.pUnlockConnection member of a list entry is
114988 **      set to db, then invoke the configured unlock-notify callback and
114989 **      set pUnlockConnection=0.
114990 **
114991 **   3) If the two steps above mean that pBlockingConnection==0 and
114992 **      pUnlockConnection==0, remove the entry from the blocked connections
114993 **      list.
114994 */
114995 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
114996   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
114997   int nArg = 0;                            /* Number of entries in aArg[] */
114998   sqlite3 **pp;                            /* Iterator variable */
114999   void **aArg;               /* Arguments to the unlock callback */
115000   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
115001   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
115002
115003   aArg = aStatic;
115004   enterMutex();         /* Enter STATIC_MASTER mutex */
115005
115006   /* This loop runs once for each entry in the blocked-connections list. */
115007   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
115008     sqlite3 *p = *pp;
115009
115010     /* Step 1. */
115011     if( p->pBlockingConnection==db ){
115012       p->pBlockingConnection = 0;
115013     }
115014
115015     /* Step 2. */
115016     if( p->pUnlockConnection==db ){
115017       assert( p->xUnlockNotify );
115018       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
115019         xUnlockNotify(aArg, nArg);
115020         nArg = 0;
115021       }
115022
115023       sqlite3BeginBenignMalloc();
115024       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
115025       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
115026       if( (!aDyn && nArg==(int)ArraySize(aStatic))
115027        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
115028       ){
115029         /* The aArg[] array needs to grow. */
115030         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
115031         if( pNew ){
115032           memcpy(pNew, aArg, nArg*sizeof(void *));
115033           sqlite3_free(aDyn);
115034           aDyn = aArg = pNew;
115035         }else{
115036           /* This occurs when the array of context pointers that need to
115037           ** be passed to the unlock-notify callback is larger than the
115038           ** aStatic[] array allocated on the stack and the attempt to 
115039           ** allocate a larger array from the heap has failed.
115040           **
115041           ** This is a difficult situation to handle. Returning an error
115042           ** code to the caller is insufficient, as even if an error code
115043           ** is returned the transaction on connection db will still be
115044           ** closed and the unlock-notify callbacks on blocked connections
115045           ** will go unissued. This might cause the application to wait
115046           ** indefinitely for an unlock-notify callback that will never 
115047           ** arrive.
115048           **
115049           ** Instead, invoke the unlock-notify callback with the context
115050           ** array already accumulated. We can then clear the array and
115051           ** begin accumulating any further context pointers without 
115052           ** requiring any dynamic allocation. This is sub-optimal because
115053           ** it means that instead of one callback with a large array of
115054           ** context pointers the application will receive two or more
115055           ** callbacks with smaller arrays of context pointers, which will
115056           ** reduce the applications ability to prioritize multiple 
115057           ** connections. But it is the best that can be done under the
115058           ** circumstances.
115059           */
115060           xUnlockNotify(aArg, nArg);
115061           nArg = 0;
115062         }
115063       }
115064       sqlite3EndBenignMalloc();
115065
115066       aArg[nArg++] = p->pUnlockArg;
115067       xUnlockNotify = p->xUnlockNotify;
115068       p->pUnlockConnection = 0;
115069       p->xUnlockNotify = 0;
115070       p->pUnlockArg = 0;
115071     }
115072
115073     /* Step 3. */
115074     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
115075       /* Remove connection p from the blocked connections list. */
115076       *pp = p->pNextBlocked;
115077       p->pNextBlocked = 0;
115078     }else{
115079       pp = &p->pNextBlocked;
115080     }
115081   }
115082
115083   if( nArg!=0 ){
115084     xUnlockNotify(aArg, nArg);
115085   }
115086   sqlite3_free(aDyn);
115087   leaveMutex();         /* Leave STATIC_MASTER mutex */
115088 }
115089
115090 /*
115091 ** This is called when the database connection passed as an argument is 
115092 ** being closed. The connection is removed from the blocked list.
115093 */
115094 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
115095   sqlite3ConnectionUnlocked(db);
115096   enterMutex();
115097   removeFromBlockedList(db);
115098   checkListProperties(db);
115099   leaveMutex();
115100 }
115101 #endif
115102
115103 /************** End of notify.c **********************************************/
115104 /************** Begin file fts3.c ********************************************/
115105 /*
115106 ** 2006 Oct 10
115107 **
115108 ** The author disclaims copyright to this source code.  In place of
115109 ** a legal notice, here is a blessing:
115110 **
115111 **    May you do good and not evil.
115112 **    May you find forgiveness for yourself and forgive others.
115113 **    May you share freely, never taking more than you give.
115114 **
115115 ******************************************************************************
115116 **
115117 ** This is an SQLite module implementing full-text search.
115118 */
115119
115120 /*
115121 ** The code in this file is only compiled if:
115122 **
115123 **     * The FTS3 module is being built as an extension
115124 **       (in which case SQLITE_CORE is not defined), or
115125 **
115126 **     * The FTS3 module is being built into the core of
115127 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
115128 */
115129
115130 /* The full-text index is stored in a series of b+tree (-like)
115131 ** structures called segments which map terms to doclists.  The
115132 ** structures are like b+trees in layout, but are constructed from the
115133 ** bottom up in optimal fashion and are not updatable.  Since trees
115134 ** are built from the bottom up, things will be described from the
115135 ** bottom up.
115136 **
115137 **
115138 **** Varints ****
115139 ** The basic unit of encoding is a variable-length integer called a
115140 ** varint.  We encode variable-length integers in little-endian order
115141 ** using seven bits * per byte as follows:
115142 **
115143 ** KEY:
115144 **         A = 0xxxxxxx    7 bits of data and one flag bit
115145 **         B = 1xxxxxxx    7 bits of data and one flag bit
115146 **
115147 **  7 bits - A
115148 ** 14 bits - BA
115149 ** 21 bits - BBA
115150 ** and so on.
115151 **
115152 ** This is similar in concept to how sqlite encodes "varints" but
115153 ** the encoding is not the same.  SQLite varints are big-endian
115154 ** are are limited to 9 bytes in length whereas FTS3 varints are
115155 ** little-endian and can be up to 10 bytes in length (in theory).
115156 **
115157 ** Example encodings:
115158 **
115159 **     1:    0x01
115160 **   127:    0x7f
115161 **   128:    0x81 0x00
115162 **
115163 **
115164 **** Document lists ****
115165 ** A doclist (document list) holds a docid-sorted list of hits for a
115166 ** given term.  Doclists hold docids and associated token positions.
115167 ** A docid is the unique integer identifier for a single document.
115168 ** A position is the index of a word within the document.  The first 
115169 ** word of the document has a position of 0.
115170 **
115171 ** FTS3 used to optionally store character offsets using a compile-time
115172 ** option.  But that functionality is no longer supported.
115173 **
115174 ** A doclist is stored like this:
115175 **
115176 ** array {
115177 **   varint docid;          (delta from previous doclist)
115178 **   array {                (position list for column 0)
115179 **     varint position;     (2 more than the delta from previous position)
115180 **   }
115181 **   array {
115182 **     varint POS_COLUMN;   (marks start of position list for new column)
115183 **     varint column;       (index of new column)
115184 **     array {
115185 **       varint position;   (2 more than the delta from previous position)
115186 **     }
115187 **   }
115188 **   varint POS_END;        (marks end of positions for this document.
115189 ** }
115190 **
115191 ** Here, array { X } means zero or more occurrences of X, adjacent in
115192 ** memory.  A "position" is an index of a token in the token stream
115193 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
115194 ** in the same logical place as the position element, and act as sentinals
115195 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
115196 ** The positions numbers are not stored literally but rather as two more
115197 ** than the difference from the prior position, or the just the position plus
115198 ** 2 for the first position.  Example:
115199 **
115200 **   label:       A B C D E  F  G H   I  J K
115201 **   value:     123 5 9 1 1 14 35 0 234 72 0
115202 **
115203 ** The 123 value is the first docid.  For column zero in this document
115204 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
115205 ** at D signals the start of a new column; the 1 at E indicates that the
115206 ** new column is column number 1.  There are two positions at 12 and 45
115207 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
115208 ** 234 at I is the delta to next docid (357).  It has one position 70
115209 ** (72-2) and then terminates with the 0 at K.
115210 **
115211 ** A "position-list" is the list of positions for multiple columns for
115212 ** a single docid.  A "column-list" is the set of positions for a single
115213 ** column.  Hence, a position-list consists of one or more column-lists,
115214 ** a document record consists of a docid followed by a position-list and
115215 ** a doclist consists of one or more document records.
115216 **
115217 ** A bare doclist omits the position information, becoming an 
115218 ** array of varint-encoded docids.
115219 **
115220 **** Segment leaf nodes ****
115221 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
115222 ** nodes are written using LeafWriter, and read using LeafReader (to
115223 ** iterate through a single leaf node's data) and LeavesReader (to
115224 ** iterate through a segment's entire leaf layer).  Leaf nodes have
115225 ** the format:
115226 **
115227 ** varint iHeight;             (height from leaf level, always 0)
115228 ** varint nTerm;               (length of first term)
115229 ** char pTerm[nTerm];          (content of first term)
115230 ** varint nDoclist;            (length of term's associated doclist)
115231 ** char pDoclist[nDoclist];    (content of doclist)
115232 ** array {
115233 **                             (further terms are delta-encoded)
115234 **   varint nPrefix;           (length of prefix shared with previous term)
115235 **   varint nSuffix;           (length of unshared suffix)
115236 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
115237 **   varint nDoclist;          (length of term's associated doclist)
115238 **   char pDoclist[nDoclist];  (content of doclist)
115239 ** }
115240 **
115241 ** Here, array { X } means zero or more occurrences of X, adjacent in
115242 ** memory.
115243 **
115244 ** Leaf nodes are broken into blocks which are stored contiguously in
115245 ** the %_segments table in sorted order.  This means that when the end
115246 ** of a node is reached, the next term is in the node with the next
115247 ** greater node id.
115248 **
115249 ** New data is spilled to a new leaf node when the current node
115250 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
115251 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
115252 ** node (a leaf node with a single term and doclist).  The goal of
115253 ** these settings is to pack together groups of small doclists while
115254 ** making it efficient to directly access large doclists.  The
115255 ** assumption is that large doclists represent terms which are more
115256 ** likely to be query targets.
115257 **
115258 ** TODO(shess) It may be useful for blocking decisions to be more
115259 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
115260 ** node rather than splitting into 2k and .5k nodes.  My intuition is
115261 ** that this might extend through 2x or 4x the pagesize.
115262 **
115263 **
115264 **** Segment interior nodes ****
115265 ** Segment interior nodes store blockids for subtree nodes and terms
115266 ** to describe what data is stored by the each subtree.  Interior
115267 ** nodes are written using InteriorWriter, and read using
115268 ** InteriorReader.  InteriorWriters are created as needed when
115269 ** SegmentWriter creates new leaf nodes, or when an interior node
115270 ** itself grows too big and must be split.  The format of interior
115271 ** nodes:
115272 **
115273 ** varint iHeight;           (height from leaf level, always >0)
115274 ** varint iBlockid;          (block id of node's leftmost subtree)
115275 ** optional {
115276 **   varint nTerm;           (length of first term)
115277 **   char pTerm[nTerm];      (content of first term)
115278 **   array {
115279 **                                (further terms are delta-encoded)
115280 **     varint nPrefix;            (length of shared prefix with previous term)
115281 **     varint nSuffix;            (length of unshared suffix)
115282 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
115283 **   }
115284 ** }
115285 **
115286 ** Here, optional { X } means an optional element, while array { X }
115287 ** means zero or more occurrences of X, adjacent in memory.
115288 **
115289 ** An interior node encodes n terms separating n+1 subtrees.  The
115290 ** subtree blocks are contiguous, so only the first subtree's blockid
115291 ** is encoded.  The subtree at iBlockid will contain all terms less
115292 ** than the first term encoded (or all terms if no term is encoded).
115293 ** Otherwise, for terms greater than or equal to pTerm[i] but less
115294 ** than pTerm[i+1], the subtree for that term will be rooted at
115295 ** iBlockid+i.  Interior nodes only store enough term data to
115296 ** distinguish adjacent children (if the rightmost term of the left
115297 ** child is "something", and the leftmost term of the right child is
115298 ** "wicked", only "w" is stored).
115299 **
115300 ** New data is spilled to a new interior node at the same height when
115301 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
115302 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
115303 ** interior nodes and making the tree too skinny.  The interior nodes
115304 ** at a given height are naturally tracked by interior nodes at
115305 ** height+1, and so on.
115306 **
115307 **
115308 **** Segment directory ****
115309 ** The segment directory in table %_segdir stores meta-information for
115310 ** merging and deleting segments, and also the root node of the
115311 ** segment's tree.
115312 **
115313 ** The root node is the top node of the segment's tree after encoding
115314 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
115315 ** This could be either a leaf node or an interior node.  If the top
115316 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
115317 ** and a new root interior node is generated (which should always fit
115318 ** within ROOT_MAX because it only needs space for 2 varints, the
115319 ** height and the blockid of the previous root).
115320 **
115321 ** The meta-information in the segment directory is:
115322 **   level               - segment level (see below)
115323 **   idx                 - index within level
115324 **                       - (level,idx uniquely identify a segment)
115325 **   start_block         - first leaf node
115326 **   leaves_end_block    - last leaf node
115327 **   end_block           - last block (including interior nodes)
115328 **   root                - contents of root node
115329 **
115330 ** If the root node is a leaf node, then start_block,
115331 ** leaves_end_block, and end_block are all 0.
115332 **
115333 **
115334 **** Segment merging ****
115335 ** To amortize update costs, segments are grouped into levels and
115336 ** merged in batches.  Each increase in level represents exponentially
115337 ** more documents.
115338 **
115339 ** New documents (actually, document updates) are tokenized and
115340 ** written individually (using LeafWriter) to a level 0 segment, with
115341 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
115342 ** level 0 segments are merged into a single level 1 segment.  Level 1
115343 ** is populated like level 0, and eventually MERGE_COUNT level 1
115344 ** segments are merged to a single level 2 segment (representing
115345 ** MERGE_COUNT^2 updates), and so on.
115346 **
115347 ** A segment merge traverses all segments at a given level in
115348 ** parallel, performing a straightforward sorted merge.  Since segment
115349 ** leaf nodes are written in to the %_segments table in order, this
115350 ** merge traverses the underlying sqlite disk structures efficiently.
115351 ** After the merge, all segment blocks from the merged level are
115352 ** deleted.
115353 **
115354 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
115355 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
115356 ** very similar performance numbers to 16 on insertion, though they're
115357 ** a tiny bit slower (perhaps due to more overhead in merge-time
115358 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
115359 ** 16, 2 about 66% slower than 16.
115360 **
115361 ** At query time, high MERGE_COUNT increases the number of segments
115362 ** which need to be scanned and merged.  For instance, with 100k docs
115363 ** inserted:
115364 **
115365 **    MERGE_COUNT   segments
115366 **       16           25
115367 **        8           12
115368 **        4           10
115369 **        2            6
115370 **
115371 ** This appears to have only a moderate impact on queries for very
115372 ** frequent terms (which are somewhat dominated by segment merge
115373 ** costs), and infrequent and non-existent terms still seem to be fast
115374 ** even with many segments.
115375 **
115376 ** TODO(shess) That said, it would be nice to have a better query-side
115377 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
115378 ** optimizations to things like doclist merging will swing the sweet
115379 ** spot around.
115380 **
115381 **
115382 **
115383 **** Handling of deletions and updates ****
115384 ** Since we're using a segmented structure, with no docid-oriented
115385 ** index into the term index, we clearly cannot simply update the term
115386 ** index when a document is deleted or updated.  For deletions, we
115387 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
115388 ** we simply write the new doclist.  Segment merges overwrite older
115389 ** data for a particular docid with newer data, so deletes or updates
115390 ** will eventually overtake the earlier data and knock it out.  The
115391 ** query logic likewise merges doclists so that newer data knocks out
115392 ** older data.
115393 */
115394
115395 /************** Include fts3Int.h in the middle of fts3.c ********************/
115396 /************** Begin file fts3Int.h *****************************************/
115397 /*
115398 ** 2009 Nov 12
115399 **
115400 ** The author disclaims copyright to this source code.  In place of
115401 ** a legal notice, here is a blessing:
115402 **
115403 **    May you do good and not evil.
115404 **    May you find forgiveness for yourself and forgive others.
115405 **    May you share freely, never taking more than you give.
115406 **
115407 ******************************************************************************
115408 **
115409 */
115410 #ifndef _FTSINT_H
115411 #define _FTSINT_H
115412
115413 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
115414 # define NDEBUG 1
115415 #endif
115416
115417 /*
115418 ** FTS4 is really an extension for FTS3.  It is enabled using the
115419 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
115420 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
115421 */
115422 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
115423 # define SQLITE_ENABLE_FTS3
115424 #endif
115425
115426 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
115427
115428 /* If not building as part of the core, include sqlite3ext.h. */
115429 #ifndef SQLITE_CORE
115430 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
115431 #endif
115432
115433 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
115434 /************** Begin file fts3_tokenizer.h **********************************/
115435 /*
115436 ** 2006 July 10
115437 **
115438 ** The author disclaims copyright to this source code.
115439 **
115440 *************************************************************************
115441 ** Defines the interface to tokenizers used by fulltext-search.  There
115442 ** are three basic components:
115443 **
115444 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
115445 ** interface functions.  This is essentially the class structure for
115446 ** tokenizers.
115447 **
115448 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
115449 ** including customization information defined at creation time.
115450 **
115451 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
115452 ** tokens from a particular input.
115453 */
115454 #ifndef _FTS3_TOKENIZER_H_
115455 #define _FTS3_TOKENIZER_H_
115456
115457 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
115458 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
115459 ** we will need a way to register the API consistently.
115460 */
115461
115462 /*
115463 ** Structures used by the tokenizer interface. When a new tokenizer
115464 ** implementation is registered, the caller provides a pointer to
115465 ** an sqlite3_tokenizer_module containing pointers to the callback
115466 ** functions that make up an implementation.
115467 **
115468 ** When an fts3 table is created, it passes any arguments passed to
115469 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
115470 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
115471 ** implementation. The xCreate() function in turn returns an 
115472 ** sqlite3_tokenizer structure representing the specific tokenizer to
115473 ** be used for the fts3 table (customized by the tokenizer clause arguments).
115474 **
115475 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
115476 ** method is called. It returns an sqlite3_tokenizer_cursor object
115477 ** that may be used to tokenize a specific input buffer based on
115478 ** the tokenization rules supplied by a specific sqlite3_tokenizer
115479 ** object.
115480 */
115481 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
115482 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
115483 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
115484
115485 struct sqlite3_tokenizer_module {
115486
115487   /*
115488   ** Structure version. Should always be set to 0 or 1.
115489   */
115490   int iVersion;
115491
115492   /*
115493   ** Create a new tokenizer. The values in the argv[] array are the
115494   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
115495   ** TABLE statement that created the fts3 table. For example, if
115496   ** the following SQL is executed:
115497   **
115498   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
115499   **
115500   ** then argc is set to 2, and the argv[] array contains pointers
115501   ** to the strings "arg1" and "arg2".
115502   **
115503   ** This method should return either SQLITE_OK (0), or an SQLite error 
115504   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
115505   ** to point at the newly created tokenizer structure. The generic
115506   ** sqlite3_tokenizer.pModule variable should not be initialised by
115507   ** this callback. The caller will do so.
115508   */
115509   int (*xCreate)(
115510     int argc,                           /* Size of argv array */
115511     const char *const*argv,             /* Tokenizer argument strings */
115512     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
115513   );
115514
115515   /*
115516   ** Destroy an existing tokenizer. The fts3 module calls this method
115517   ** exactly once for each successful call to xCreate().
115518   */
115519   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
115520
115521   /*
115522   ** Create a tokenizer cursor to tokenize an input buffer. The caller
115523   ** is responsible for ensuring that the input buffer remains valid
115524   ** until the cursor is closed (using the xClose() method). 
115525   */
115526   int (*xOpen)(
115527     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
115528     const char *pInput, int nBytes,      /* Input buffer */
115529     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
115530   );
115531
115532   /*
115533   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
115534   ** method exactly once for each successful call to xOpen().
115535   */
115536   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
115537
115538   /*
115539   ** Retrieve the next token from the tokenizer cursor pCursor. This
115540   ** method should either return SQLITE_OK and set the values of the
115541   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
115542   ** the end of the buffer has been reached, or an SQLite error code.
115543   **
115544   ** *ppToken should be set to point at a buffer containing the 
115545   ** normalized version of the token (i.e. after any case-folding and/or
115546   ** stemming has been performed). *pnBytes should be set to the length
115547   ** of this buffer in bytes. The input text that generated the token is
115548   ** identified by the byte offsets returned in *piStartOffset and
115549   ** *piEndOffset. *piStartOffset should be set to the index of the first
115550   ** byte of the token in the input buffer. *piEndOffset should be set
115551   ** to the index of the first byte just past the end of the token in
115552   ** the input buffer.
115553   **
115554   ** The buffer *ppToken is set to point at is managed by the tokenizer
115555   ** implementation. It is only required to be valid until the next call
115556   ** to xNext() or xClose(). 
115557   */
115558   /* TODO(shess) current implementation requires pInput to be
115559   ** nul-terminated.  This should either be fixed, or pInput/nBytes
115560   ** should be converted to zInput.
115561   */
115562   int (*xNext)(
115563     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
115564     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
115565     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
115566     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
115567     int *piPosition      /* OUT: Number of tokens returned before this one */
115568   );
115569
115570   /***********************************************************************
115571   ** Methods below this point are only available if iVersion>=1.
115572   */
115573
115574   /* 
115575   ** Configure the language id of a tokenizer cursor.
115576   */
115577   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
115578 };
115579
115580 struct sqlite3_tokenizer {
115581   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
115582   /* Tokenizer implementations will typically add additional fields */
115583 };
115584
115585 struct sqlite3_tokenizer_cursor {
115586   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
115587   /* Tokenizer implementations will typically add additional fields */
115588 };
115589
115590 int fts3_global_term_cnt(int iTerm, int iCol);
115591 int fts3_term_cnt(int iTerm, int iCol);
115592
115593
115594 #endif /* _FTS3_TOKENIZER_H_ */
115595
115596 /************** End of fts3_tokenizer.h **************************************/
115597 /************** Continuing where we left off in fts3Int.h ********************/
115598 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
115599 /************** Begin file fts3_hash.h ***************************************/
115600 /*
115601 ** 2001 September 22
115602 **
115603 ** The author disclaims copyright to this source code.  In place of
115604 ** a legal notice, here is a blessing:
115605 **
115606 **    May you do good and not evil.
115607 **    May you find forgiveness for yourself and forgive others.
115608 **    May you share freely, never taking more than you give.
115609 **
115610 *************************************************************************
115611 ** This is the header file for the generic hash-table implemenation
115612 ** used in SQLite.  We've modified it slightly to serve as a standalone
115613 ** hash table implementation for the full-text indexing module.
115614 **
115615 */
115616 #ifndef _FTS3_HASH_H_
115617 #define _FTS3_HASH_H_
115618
115619 /* Forward declarations of structures. */
115620 typedef struct Fts3Hash Fts3Hash;
115621 typedef struct Fts3HashElem Fts3HashElem;
115622
115623 /* A complete hash table is an instance of the following structure.
115624 ** The internals of this structure are intended to be opaque -- client
115625 ** code should not attempt to access or modify the fields of this structure
115626 ** directly.  Change this structure only by using the routines below.
115627 ** However, many of the "procedures" and "functions" for modifying and
115628 ** accessing this structure are really macros, so we can't really make
115629 ** this structure opaque.
115630 */
115631 struct Fts3Hash {
115632   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
115633   char copyKey;           /* True if copy of key made on insert */
115634   int count;              /* Number of entries in this table */
115635   Fts3HashElem *first;    /* The first element of the array */
115636   int htsize;             /* Number of buckets in the hash table */
115637   struct _fts3ht {        /* the hash table */
115638     int count;               /* Number of entries with this hash */
115639     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
115640   } *ht;
115641 };
115642
115643 /* Each element in the hash table is an instance of the following 
115644 ** structure.  All elements are stored on a single doubly-linked list.
115645 **
115646 ** Again, this structure is intended to be opaque, but it can't really
115647 ** be opaque because it is used by macros.
115648 */
115649 struct Fts3HashElem {
115650   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
115651   void *data;                /* Data associated with this element */
115652   void *pKey; int nKey;      /* Key associated with this element */
115653 };
115654
115655 /*
115656 ** There are 2 different modes of operation for a hash table:
115657 **
115658 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
115659 **                           (including the null-terminator, if any).  Case
115660 **                           is respected in comparisons.
115661 **
115662 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
115663 **                           memcmp() is used to compare keys.
115664 **
115665 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
115666 */
115667 #define FTS3_HASH_STRING    1
115668 #define FTS3_HASH_BINARY    2
115669
115670 /*
115671 ** Access routines.  To delete, insert a NULL pointer.
115672 */
115673 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
115674 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
115675 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
115676 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
115677 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
115678
115679 /*
115680 ** Shorthand for the functions above
115681 */
115682 #define fts3HashInit     sqlite3Fts3HashInit
115683 #define fts3HashInsert   sqlite3Fts3HashInsert
115684 #define fts3HashFind     sqlite3Fts3HashFind
115685 #define fts3HashClear    sqlite3Fts3HashClear
115686 #define fts3HashFindElem sqlite3Fts3HashFindElem
115687
115688 /*
115689 ** Macros for looping over all elements of a hash table.  The idiom is
115690 ** like this:
115691 **
115692 **   Fts3Hash h;
115693 **   Fts3HashElem *p;
115694 **   ...
115695 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
115696 **     SomeStructure *pData = fts3HashData(p);
115697 **     // do something with pData
115698 **   }
115699 */
115700 #define fts3HashFirst(H)  ((H)->first)
115701 #define fts3HashNext(E)   ((E)->next)
115702 #define fts3HashData(E)   ((E)->data)
115703 #define fts3HashKey(E)    ((E)->pKey)
115704 #define fts3HashKeysize(E) ((E)->nKey)
115705
115706 /*
115707 ** Number of entries in a hash table
115708 */
115709 #define fts3HashCount(H)  ((H)->count)
115710
115711 #endif /* _FTS3_HASH_H_ */
115712
115713 /************** End of fts3_hash.h *******************************************/
115714 /************** Continuing where we left off in fts3Int.h ********************/
115715
115716 /*
115717 ** This constant controls how often segments are merged. Once there are
115718 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
115719 ** segment of level N+1.
115720 */
115721 #define FTS3_MERGE_COUNT 16
115722
115723 /*
115724 ** This is the maximum amount of data (in bytes) to store in the 
115725 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
115726 ** populated as documents are inserted/updated/deleted in a transaction
115727 ** and used to create a new segment when the transaction is committed.
115728 ** However if this limit is reached midway through a transaction, a new 
115729 ** segment is created and the hash table cleared immediately.
115730 */
115731 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
115732
115733 /*
115734 ** Macro to return the number of elements in an array. SQLite has a
115735 ** similar macro called ArraySize(). Use a different name to avoid
115736 ** a collision when building an amalgamation with built-in FTS3.
115737 */
115738 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
115739
115740
115741 #ifndef MIN
115742 # define MIN(x,y) ((x)<(y)?(x):(y))
115743 #endif
115744 #ifndef MAX
115745 # define MAX(x,y) ((x)>(y)?(x):(y))
115746 #endif
115747
115748 /*
115749 ** Maximum length of a varint encoded integer. The varint format is different
115750 ** from that used by SQLite, so the maximum length is 10, not 9.
115751 */
115752 #define FTS3_VARINT_MAX 10
115753
115754 /*
115755 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
115756 ** in the document set and zero or more prefix indexes. All indexes are stored
115757 ** as one or more b+-trees in the %_segments and %_segdir tables. 
115758 **
115759 ** It is possible to determine which index a b+-tree belongs to based on the
115760 ** value stored in the "%_segdir.level" column. Given this value L, the index
115761 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
115762 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
115763 ** between 1024 and 2047 to index 1, and so on.
115764 **
115765 ** It is considered impossible for an index to use more than 1024 levels. In 
115766 ** theory though this may happen, but only after at least 
115767 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
115768 */
115769 #define FTS3_SEGDIR_MAXLEVEL      1024
115770 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
115771
115772 /*
115773 ** The testcase() macro is only used by the amalgamation.  If undefined,
115774 ** make it a no-op.
115775 */
115776 #ifndef testcase
115777 # define testcase(X)
115778 #endif
115779
115780 /*
115781 ** Terminator values for position-lists and column-lists.
115782 */
115783 #define POS_COLUMN  (1)     /* Column-list terminator */
115784 #define POS_END     (0)     /* Position-list terminator */ 
115785
115786 /*
115787 ** This section provides definitions to allow the
115788 ** FTS3 extension to be compiled outside of the 
115789 ** amalgamation.
115790 */
115791 #ifndef SQLITE_AMALGAMATION
115792 /*
115793 ** Macros indicating that conditional expressions are always true or
115794 ** false.
115795 */
115796 #ifdef SQLITE_COVERAGE_TEST
115797 # define ALWAYS(x) (1)
115798 # define NEVER(X)  (0)
115799 #else
115800 # define ALWAYS(x) (x)
115801 # define NEVER(x)  (x)
115802 #endif
115803
115804 /*
115805 ** Internal types used by SQLite.
115806 */
115807 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
115808 typedef short int i16;            /* 2-byte (or larger) signed integer */
115809 typedef unsigned int u32;         /* 4-byte unsigned integer */
115810 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
115811 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
115812
115813 /*
115814 ** Macro used to suppress compiler warnings for unused parameters.
115815 */
115816 #define UNUSED_PARAMETER(x) (void)(x)
115817
115818 /*
115819 ** Activate assert() only if SQLITE_TEST is enabled.
115820 */
115821 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
115822 # define NDEBUG 1
115823 #endif
115824
115825 /*
115826 ** The TESTONLY macro is used to enclose variable declarations or
115827 ** other bits of code that are needed to support the arguments
115828 ** within testcase() and assert() macros.
115829 */
115830 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
115831 # define TESTONLY(X)  X
115832 #else
115833 # define TESTONLY(X)
115834 #endif
115835
115836 #endif /* SQLITE_AMALGAMATION */
115837
115838 #ifdef SQLITE_DEBUG
115839 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
115840 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
115841 #else
115842 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
115843 #endif
115844
115845 typedef struct Fts3Table Fts3Table;
115846 typedef struct Fts3Cursor Fts3Cursor;
115847 typedef struct Fts3Expr Fts3Expr;
115848 typedef struct Fts3Phrase Fts3Phrase;
115849 typedef struct Fts3PhraseToken Fts3PhraseToken;
115850
115851 typedef struct Fts3Doclist Fts3Doclist;
115852 typedef struct Fts3SegFilter Fts3SegFilter;
115853 typedef struct Fts3DeferredToken Fts3DeferredToken;
115854 typedef struct Fts3SegReader Fts3SegReader;
115855 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
115856
115857 /*
115858 ** A connection to a fulltext index is an instance of the following
115859 ** structure. The xCreate and xConnect methods create an instance
115860 ** of this structure and xDestroy and xDisconnect free that instance.
115861 ** All other methods receive a pointer to the structure as one of their
115862 ** arguments.
115863 */
115864 struct Fts3Table {
115865   sqlite3_vtab base;              /* Base class used by SQLite core */
115866   sqlite3 *db;                    /* The database connection */
115867   const char *zDb;                /* logical database name */
115868   const char *zName;              /* virtual table name */
115869   int nColumn;                    /* number of named columns in virtual table */
115870   char **azColumn;                /* column names.  malloced */
115871   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
115872   char *zContentTbl;              /* content=xxx option, or NULL */
115873   char *zLanguageid;              /* languageid=xxx option, or NULL */
115874   u8 bAutoincrmerge;              /* True if automerge=1 */
115875   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
115876
115877   /* Precompiled statements used by the implementation. Each of these 
115878   ** statements is run and reset within a single virtual table API call. 
115879   */
115880   sqlite3_stmt *aStmt[37];
115881
115882   char *zReadExprlist;
115883   char *zWriteExprlist;
115884
115885   int nNodeSize;                  /* Soft limit for node size */
115886   u8 bFts4;                       /* True for FTS4, false for FTS3 */
115887   u8 bHasStat;                    /* True if %_stat table exists */
115888   u8 bHasDocsize;                 /* True if %_docsize table exists */
115889   u8 bDescIdx;                    /* True if doclists are in reverse order */
115890   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
115891   int nPgsz;                      /* Page size for host database */
115892   char *zSegmentsTbl;             /* Name of %_segments table */
115893   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
115894
115895   /* 
115896   ** The following array of hash tables is used to buffer pending index 
115897   ** updates during transactions. All pending updates buffered at any one
115898   ** time must share a common language-id (see the FTS4 langid= feature).
115899   ** The current language id is stored in variable iPrevLangid.
115900   **
115901   ** A single FTS4 table may have multiple full-text indexes. For each index
115902   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
115903   ** terms that appear in the document set. Each subsequent index in aIndex[]
115904   ** is an index of prefixes of a specific length.
115905   **
115906   ** Variable nPendingData contains an estimate the memory consumed by the 
115907   ** pending data structures, including hash table overhead, but not including
115908   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
115909   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
115910   ** recently inserted record.
115911   */
115912   int nIndex;                     /* Size of aIndex[] */
115913   struct Fts3Index {
115914     int nPrefix;                  /* Prefix length (0 for main terms index) */
115915     Fts3Hash hPending;            /* Pending terms table for this index */
115916   } *aIndex;
115917   int nMaxPendingData;            /* Max pending data before flush to disk */
115918   int nPendingData;               /* Current bytes of pending data */
115919   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
115920   int iPrevLangid;                /* Langid of recently inserted document */
115921
115922 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
115923   /* State variables used for validating that the transaction control
115924   ** methods of the virtual table are called at appropriate times.  These
115925   ** values do not contribute to FTS functionality; they are used for
115926   ** verifying the operation of the SQLite core.
115927   */
115928   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
115929   int mxSavepoint;       /* Largest valid xSavepoint integer */
115930 #endif
115931 };
115932
115933 /*
115934 ** When the core wants to read from the virtual table, it creates a
115935 ** virtual table cursor (an instance of the following structure) using
115936 ** the xOpen method. Cursors are destroyed using the xClose method.
115937 */
115938 struct Fts3Cursor {
115939   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
115940   i16 eSearch;                    /* Search strategy (see below) */
115941   u8 isEof;                       /* True if at End Of Results */
115942   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
115943   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
115944   Fts3Expr *pExpr;                /* Parsed MATCH query string */
115945   int iLangid;                    /* Language being queried for */
115946   int nPhrase;                    /* Number of matchable phrases in query */
115947   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
115948   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
115949   char *pNextId;                  /* Pointer into the body of aDoclist */
115950   char *aDoclist;                 /* List of docids for full-text queries */
115951   int nDoclist;                   /* Size of buffer at aDoclist */
115952   u8 bDesc;                       /* True to sort in descending order */
115953   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
115954   int nRowAvg;                    /* Average size of database rows, in pages */
115955   sqlite3_int64 nDoc;             /* Documents in table */
115956
115957   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
115958   u32 *aMatchinfo;                /* Information about most recent match */
115959   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
115960   char *zMatchinfo;               /* Matchinfo specification */
115961 };
115962
115963 #define FTS3_EVAL_FILTER    0
115964 #define FTS3_EVAL_NEXT      1
115965 #define FTS3_EVAL_MATCHINFO 2
115966
115967 /*
115968 ** The Fts3Cursor.eSearch member is always set to one of the following.
115969 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
115970 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
115971 ** of the column to be searched.  For example, in
115972 **
115973 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
115974 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
115975 ** 
115976 ** Because the LHS of the MATCH operator is 2nd column "b",
115977 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
115978 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
115979 ** indicating that all columns should be searched,
115980 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
115981 */
115982 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
115983 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
115984 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
115985
115986
115987 struct Fts3Doclist {
115988   char *aAll;                    /* Array containing doclist (or NULL) */
115989   int nAll;                      /* Size of a[] in bytes */
115990   char *pNextDocid;              /* Pointer to next docid */
115991
115992   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
115993   int bFreeList;                 /* True if pList should be sqlite3_free()d */
115994   char *pList;                   /* Pointer to position list following iDocid */
115995   int nList;                     /* Length of position list */
115996 };
115997
115998 /*
115999 ** A "phrase" is a sequence of one or more tokens that must match in
116000 ** sequence.  A single token is the base case and the most common case.
116001 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
116002 ** nToken will be the number of tokens in the string.
116003 */
116004 struct Fts3PhraseToken {
116005   char *z;                        /* Text of the token */
116006   int n;                          /* Number of bytes in buffer z */
116007   int isPrefix;                   /* True if token ends with a "*" character */
116008   int bFirst;                     /* True if token must appear at position 0 */
116009
116010   /* Variables above this point are populated when the expression is
116011   ** parsed (by code in fts3_expr.c). Below this point the variables are
116012   ** used when evaluating the expression. */
116013   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
116014   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
116015 };
116016
116017 struct Fts3Phrase {
116018   /* Cache of doclist for this phrase. */
116019   Fts3Doclist doclist;
116020   int bIncr;                 /* True if doclist is loaded incrementally */
116021   int iDoclistToken;
116022
116023   /* Variables below this point are populated by fts3_expr.c when parsing 
116024   ** a MATCH expression. Everything above is part of the evaluation phase. 
116025   */
116026   int nToken;                /* Number of tokens in the phrase */
116027   int iColumn;               /* Index of column this phrase must match */
116028   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
116029 };
116030
116031 /*
116032 ** A tree of these objects forms the RHS of a MATCH operator.
116033 **
116034 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
116035 ** points to a malloced buffer, size nDoclist bytes, containing the results 
116036 ** of this phrase query in FTS3 doclist format. As usual, the initial 
116037 ** "Length" field found in doclists stored on disk is omitted from this 
116038 ** buffer.
116039 **
116040 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
116041 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
116042 ** where nCol is the number of columns in the queried FTS table. The array
116043 ** is populated as follows:
116044 **
116045 **   aMI[iCol*3 + 0] = Undefined
116046 **   aMI[iCol*3 + 1] = Number of occurrences
116047 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
116048 **
116049 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
116050 ** when the expression node is.
116051 */
116052 struct Fts3Expr {
116053   int eType;                 /* One of the FTSQUERY_XXX values defined below */
116054   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
116055   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
116056   Fts3Expr *pLeft;           /* Left operand */
116057   Fts3Expr *pRight;          /* Right operand */
116058   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
116059
116060   /* The following are used by the fts3_eval.c module. */
116061   sqlite3_int64 iDocid;      /* Current docid */
116062   u8 bEof;                   /* True this expression is at EOF already */
116063   u8 bStart;                 /* True if iDocid is valid */
116064   u8 bDeferred;              /* True if this expression is entirely deferred */
116065
116066   u32 *aMI;
116067 };
116068
116069 /*
116070 ** Candidate values for Fts3Query.eType. Note that the order of the first
116071 ** four values is in order of precedence when parsing expressions. For 
116072 ** example, the following:
116073 **
116074 **   "a OR b AND c NOT d NEAR e"
116075 **
116076 ** is equivalent to:
116077 **
116078 **   "a OR (b AND (c NOT (d NEAR e)))"
116079 */
116080 #define FTSQUERY_NEAR   1
116081 #define FTSQUERY_NOT    2
116082 #define FTSQUERY_AND    3
116083 #define FTSQUERY_OR     4
116084 #define FTSQUERY_PHRASE 5
116085
116086
116087 /* fts3_write.c */
116088 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
116089 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
116090 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
116091 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
116092 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
116093   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
116094 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
116095   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
116096 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
116097 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
116098 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
116099 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
116100
116101 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
116102 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
116103
116104 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
116105 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
116106 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
116107 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
116108 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
116109 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
116110 #else
116111 # define sqlite3Fts3FreeDeferredTokens(x)
116112 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
116113 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
116114 # define sqlite3Fts3FreeDeferredDoclists(x)
116115 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
116116 #endif
116117
116118 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
116119 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
116120
116121 /* Special values interpreted by sqlite3SegReaderCursor() */
116122 #define FTS3_SEGCURSOR_PENDING        -1
116123 #define FTS3_SEGCURSOR_ALL            -2
116124
116125 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
116126 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
116127 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
116128
116129 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
116130     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
116131
116132 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
116133 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
116134 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
116135 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
116136 #define FTS3_SEGMENT_PREFIX        0x00000008
116137 #define FTS3_SEGMENT_SCAN          0x00000010
116138 #define FTS3_SEGMENT_FIRST         0x00000020
116139
116140 /* Type passed as 4th argument to SegmentReaderIterate() */
116141 struct Fts3SegFilter {
116142   const char *zTerm;
116143   int nTerm;
116144   int iCol;
116145   int flags;
116146 };
116147
116148 struct Fts3MultiSegReader {
116149   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
116150   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
116151   int nSegment;                   /* Size of apSegment array */
116152   int nAdvance;                   /* How many seg-readers to advance */
116153   Fts3SegFilter *pFilter;         /* Pointer to filter object */
116154   char *aBuffer;                  /* Buffer to merge doclists in */
116155   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
116156
116157   int iColFilter;                 /* If >=0, filter for this column */
116158   int bRestart;
116159
116160   /* Used by fts3.c only. */
116161   int nCost;                      /* Cost of running iterator */
116162   int bLookup;                    /* True if a lookup of a single entry. */
116163
116164   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
116165   char *zTerm;                    /* Pointer to term buffer */
116166   int nTerm;                      /* Size of zTerm in bytes */
116167   char *aDoclist;                 /* Pointer to doclist buffer */
116168   int nDoclist;                   /* Size of aDoclist[] in bytes */
116169 };
116170
116171 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
116172
116173 /* fts3.c */
116174 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
116175 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
116176 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
116177 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
116178 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
116179 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
116180 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
116181 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
116182 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
116183
116184 /* fts3_tokenizer.c */
116185 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
116186 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
116187 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
116188     sqlite3_tokenizer **, char **
116189 );
116190 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
116191
116192 /* fts3_snippet.c */
116193 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
116194 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
116195   const char *, const char *, int, int
116196 );
116197 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
116198
116199 /* fts3_expr.c */
116200 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
116201   char **, int, int, int, const char *, int, Fts3Expr **
116202 );
116203 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
116204 #ifdef SQLITE_TEST
116205 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
116206 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
116207 #endif
116208
116209 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
116210   sqlite3_tokenizer_cursor **
116211 );
116212
116213 /* fts3_aux.c */
116214 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
116215
116216 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
116217
116218 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
116219     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
116220 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
116221     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
116222 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
116223 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
116224 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
116225
116226 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
116227 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
116228 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
116229 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
116230 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
116231 #endif
116232
116233 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
116234 #endif /* _FTSINT_H */
116235
116236 /************** End of fts3Int.h *********************************************/
116237 /************** Continuing where we left off in fts3.c ***********************/
116238 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116239
116240 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
116241 # define SQLITE_CORE 1
116242 #endif
116243
116244 /* #include <assert.h> */
116245 /* #include <stdlib.h> */
116246 /* #include <stddef.h> */
116247 /* #include <stdio.h> */
116248 /* #include <string.h> */
116249 /* #include <stdarg.h> */
116250
116251 #ifndef SQLITE_CORE 
116252   SQLITE_EXTENSION_INIT1
116253 #endif
116254
116255 static int fts3EvalNext(Fts3Cursor *pCsr);
116256 static int fts3EvalStart(Fts3Cursor *pCsr);
116257 static int fts3TermSegReaderCursor(
116258     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
116259
116260 /* 
116261 ** Write a 64-bit variable-length integer to memory starting at p[0].
116262 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
116263 ** The number of bytes written is returned.
116264 */
116265 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
116266   unsigned char *q = (unsigned char *) p;
116267   sqlite_uint64 vu = v;
116268   do{
116269     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
116270     vu >>= 7;
116271   }while( vu!=0 );
116272   q[-1] &= 0x7f;  /* turn off high bit in final byte */
116273   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
116274   return (int) (q - (unsigned char *)p);
116275 }
116276
116277 /* 
116278 ** Read a 64-bit variable-length integer from memory starting at p[0].
116279 ** Return the number of bytes read, or 0 on error.
116280 ** The value is stored in *v.
116281 */
116282 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
116283   const unsigned char *q = (const unsigned char *) p;
116284   sqlite_uint64 x = 0, y = 1;
116285   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
116286     x += y * (*q++ & 0x7f);
116287     y <<= 7;
116288   }
116289   x += y * (*q++);
116290   *v = (sqlite_int64) x;
116291   return (int) (q - (unsigned char *)p);
116292 }
116293
116294 /*
116295 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
116296 ** 32-bit integer before it is returned.
116297 */
116298 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
116299  sqlite_int64 i;
116300  int ret = sqlite3Fts3GetVarint(p, &i);
116301  *pi = (int) i;
116302  return ret;
116303 }
116304
116305 /*
116306 ** Return the number of bytes required to encode v as a varint
116307 */
116308 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
116309   int i = 0;
116310   do{
116311     i++;
116312     v >>= 7;
116313   }while( v!=0 );
116314   return i;
116315 }
116316
116317 /*
116318 ** Convert an SQL-style quoted string into a normal string by removing
116319 ** the quote characters.  The conversion is done in-place.  If the
116320 ** input does not begin with a quote character, then this routine
116321 ** is a no-op.
116322 **
116323 ** Examples:
116324 **
116325 **     "abc"   becomes   abc
116326 **     'xyz'   becomes   xyz
116327 **     [pqr]   becomes   pqr
116328 **     `mno`   becomes   mno
116329 **
116330 */
116331 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
116332   char quote;                     /* Quote character (if any ) */
116333
116334   quote = z[0];
116335   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
116336     int iIn = 1;                  /* Index of next byte to read from input */
116337     int iOut = 0;                 /* Index of next byte to write to output */
116338
116339     /* If the first byte was a '[', then the close-quote character is a ']' */
116340     if( quote=='[' ) quote = ']';  
116341
116342     while( ALWAYS(z[iIn]) ){
116343       if( z[iIn]==quote ){
116344         if( z[iIn+1]!=quote ) break;
116345         z[iOut++] = quote;
116346         iIn += 2;
116347       }else{
116348         z[iOut++] = z[iIn++];
116349       }
116350     }
116351     z[iOut] = '\0';
116352   }
116353 }
116354
116355 /*
116356 ** Read a single varint from the doclist at *pp and advance *pp to point
116357 ** to the first byte past the end of the varint.  Add the value of the varint
116358 ** to *pVal.
116359 */
116360 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
116361   sqlite3_int64 iVal;
116362   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
116363   *pVal += iVal;
116364 }
116365
116366 /*
116367 ** When this function is called, *pp points to the first byte following a
116368 ** varint that is part of a doclist (or position-list, or any other list
116369 ** of varints). This function moves *pp to point to the start of that varint,
116370 ** and sets *pVal by the varint value.
116371 **
116372 ** Argument pStart points to the first byte of the doclist that the
116373 ** varint is part of.
116374 */
116375 static void fts3GetReverseVarint(
116376   char **pp, 
116377   char *pStart, 
116378   sqlite3_int64 *pVal
116379 ){
116380   sqlite3_int64 iVal;
116381   char *p;
116382
116383   /* Pointer p now points at the first byte past the varint we are 
116384   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
116385   ** clear on character p[-1]. */
116386   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
116387   p++;
116388   *pp = p;
116389
116390   sqlite3Fts3GetVarint(p, &iVal);
116391   *pVal = iVal;
116392 }
116393
116394 /*
116395 ** The xDisconnect() virtual table method.
116396 */
116397 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
116398   Fts3Table *p = (Fts3Table *)pVtab;
116399   int i;
116400
116401   assert( p->nPendingData==0 );
116402   assert( p->pSegments==0 );
116403
116404   /* Free any prepared statements held */
116405   for(i=0; i<SizeofArray(p->aStmt); i++){
116406     sqlite3_finalize(p->aStmt[i]);
116407   }
116408   sqlite3_free(p->zSegmentsTbl);
116409   sqlite3_free(p->zReadExprlist);
116410   sqlite3_free(p->zWriteExprlist);
116411   sqlite3_free(p->zContentTbl);
116412   sqlite3_free(p->zLanguageid);
116413
116414   /* Invoke the tokenizer destructor to free the tokenizer. */
116415   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
116416
116417   sqlite3_free(p);
116418   return SQLITE_OK;
116419 }
116420
116421 /*
116422 ** Construct one or more SQL statements from the format string given
116423 ** and then evaluate those statements. The success code is written
116424 ** into *pRc.
116425 **
116426 ** If *pRc is initially non-zero then this routine is a no-op.
116427 */
116428 static void fts3DbExec(
116429   int *pRc,              /* Success code */
116430   sqlite3 *db,           /* Database in which to run SQL */
116431   const char *zFormat,   /* Format string for SQL */
116432   ...                    /* Arguments to the format string */
116433 ){
116434   va_list ap;
116435   char *zSql;
116436   if( *pRc ) return;
116437   va_start(ap, zFormat);
116438   zSql = sqlite3_vmprintf(zFormat, ap);
116439   va_end(ap);
116440   if( zSql==0 ){
116441     *pRc = SQLITE_NOMEM;
116442   }else{
116443     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
116444     sqlite3_free(zSql);
116445   }
116446 }
116447
116448 /*
116449 ** The xDestroy() virtual table method.
116450 */
116451 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
116452   Fts3Table *p = (Fts3Table *)pVtab;
116453   int rc = SQLITE_OK;              /* Return code */
116454   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
116455   sqlite3 *db = p->db;             /* Database handle */
116456
116457   /* Drop the shadow tables */
116458   if( p->zContentTbl==0 ){
116459     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
116460   }
116461   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
116462   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
116463   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
116464   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
116465
116466   /* If everything has worked, invoke fts3DisconnectMethod() to free the
116467   ** memory associated with the Fts3Table structure and return SQLITE_OK.
116468   ** Otherwise, return an SQLite error code.
116469   */
116470   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
116471 }
116472
116473
116474 /*
116475 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
116476 ** passed as the first argument. This is done as part of the xConnect()
116477 ** and xCreate() methods.
116478 **
116479 ** If *pRc is non-zero when this function is called, it is a no-op. 
116480 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116481 ** before returning.
116482 */
116483 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
116484   if( *pRc==SQLITE_OK ){
116485     int i;                        /* Iterator variable */
116486     int rc;                       /* Return code */
116487     char *zSql;                   /* SQL statement passed to declare_vtab() */
116488     char *zCols;                  /* List of user defined columns */
116489     const char *zLanguageid;
116490
116491     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
116492     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
116493
116494     /* Create a list of user columns for the virtual table */
116495     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
116496     for(i=1; zCols && i<p->nColumn; i++){
116497       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
116498     }
116499
116500     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
116501     zSql = sqlite3_mprintf(
116502         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
116503         zCols, p->zName, zLanguageid
116504     );
116505     if( !zCols || !zSql ){
116506       rc = SQLITE_NOMEM;
116507     }else{
116508       rc = sqlite3_declare_vtab(p->db, zSql);
116509     }
116510
116511     sqlite3_free(zSql);
116512     sqlite3_free(zCols);
116513     *pRc = rc;
116514   }
116515 }
116516
116517 /*
116518 ** Create the %_stat table if it does not already exist.
116519 */
116520 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
116521   fts3DbExec(pRc, p->db, 
116522       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
116523           "(id INTEGER PRIMARY KEY, value BLOB);",
116524       p->zDb, p->zName
116525   );
116526   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
116527 }
116528
116529 /*
116530 ** Create the backing store tables (%_content, %_segments and %_segdir)
116531 ** required by the FTS3 table passed as the only argument. This is done
116532 ** as part of the vtab xCreate() method.
116533 **
116534 ** If the p->bHasDocsize boolean is true (indicating that this is an
116535 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
116536 ** %_stat tables required by FTS4.
116537 */
116538 static int fts3CreateTables(Fts3Table *p){
116539   int rc = SQLITE_OK;             /* Return code */
116540   int i;                          /* Iterator variable */
116541   sqlite3 *db = p->db;            /* The database connection */
116542
116543   if( p->zContentTbl==0 ){
116544     const char *zLanguageid = p->zLanguageid;
116545     char *zContentCols;           /* Columns of %_content table */
116546
116547     /* Create a list of user columns for the content table */
116548     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
116549     for(i=0; zContentCols && i<p->nColumn; i++){
116550       char *z = p->azColumn[i];
116551       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
116552     }
116553     if( zLanguageid && zContentCols ){
116554       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
116555     }
116556     if( zContentCols==0 ) rc = SQLITE_NOMEM;
116557   
116558     /* Create the content table */
116559     fts3DbExec(&rc, db, 
116560        "CREATE TABLE %Q.'%q_content'(%s)",
116561        p->zDb, p->zName, zContentCols
116562     );
116563     sqlite3_free(zContentCols);
116564   }
116565
116566   /* Create other tables */
116567   fts3DbExec(&rc, db, 
116568       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
116569       p->zDb, p->zName
116570   );
116571   fts3DbExec(&rc, db, 
116572       "CREATE TABLE %Q.'%q_segdir'("
116573         "level INTEGER,"
116574         "idx INTEGER,"
116575         "start_block INTEGER,"
116576         "leaves_end_block INTEGER,"
116577         "end_block INTEGER,"
116578         "root BLOB,"
116579         "PRIMARY KEY(level, idx)"
116580       ");",
116581       p->zDb, p->zName
116582   );
116583   if( p->bHasDocsize ){
116584     fts3DbExec(&rc, db, 
116585         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
116586         p->zDb, p->zName
116587     );
116588   }
116589   assert( p->bHasStat==p->bFts4 );
116590   if( p->bHasStat ){
116591     sqlite3Fts3CreateStatTable(&rc, p);
116592   }
116593   return rc;
116594 }
116595
116596 /*
116597 ** Store the current database page-size in bytes in p->nPgsz.
116598 **
116599 ** If *pRc is non-zero when this function is called, it is a no-op. 
116600 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116601 ** before returning.
116602 */
116603 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
116604   if( *pRc==SQLITE_OK ){
116605     int rc;                       /* Return code */
116606     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
116607     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
116608   
116609     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
116610     if( !zSql ){
116611       rc = SQLITE_NOMEM;
116612     }else{
116613       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
116614       if( rc==SQLITE_OK ){
116615         sqlite3_step(pStmt);
116616         p->nPgsz = sqlite3_column_int(pStmt, 0);
116617         rc = sqlite3_finalize(pStmt);
116618       }else if( rc==SQLITE_AUTH ){
116619         p->nPgsz = 1024;
116620         rc = SQLITE_OK;
116621       }
116622     }
116623     assert( p->nPgsz>0 || rc!=SQLITE_OK );
116624     sqlite3_free(zSql);
116625     *pRc = rc;
116626   }
116627 }
116628
116629 /*
116630 ** "Special" FTS4 arguments are column specifications of the following form:
116631 **
116632 **   <key> = <value>
116633 **
116634 ** There may not be whitespace surrounding the "=" character. The <value> 
116635 ** term may be quoted, but the <key> may not.
116636 */
116637 static int fts3IsSpecialColumn(
116638   const char *z, 
116639   int *pnKey,
116640   char **pzValue
116641 ){
116642   char *zValue;
116643   const char *zCsr = z;
116644
116645   while( *zCsr!='=' ){
116646     if( *zCsr=='\0' ) return 0;
116647     zCsr++;
116648   }
116649
116650   *pnKey = (int)(zCsr-z);
116651   zValue = sqlite3_mprintf("%s", &zCsr[1]);
116652   if( zValue ){
116653     sqlite3Fts3Dequote(zValue);
116654   }
116655   *pzValue = zValue;
116656   return 1;
116657 }
116658
116659 /*
116660 ** Append the output of a printf() style formatting to an existing string.
116661 */
116662 static void fts3Appendf(
116663   int *pRc,                       /* IN/OUT: Error code */
116664   char **pz,                      /* IN/OUT: Pointer to string buffer */
116665   const char *zFormat,            /* Printf format string to append */
116666   ...                             /* Arguments for printf format string */
116667 ){
116668   if( *pRc==SQLITE_OK ){
116669     va_list ap;
116670     char *z;
116671     va_start(ap, zFormat);
116672     z = sqlite3_vmprintf(zFormat, ap);
116673     va_end(ap);
116674     if( z && *pz ){
116675       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
116676       sqlite3_free(z);
116677       z = z2;
116678     }
116679     if( z==0 ) *pRc = SQLITE_NOMEM;
116680     sqlite3_free(*pz);
116681     *pz = z;
116682   }
116683 }
116684
116685 /*
116686 ** Return a copy of input string zInput enclosed in double-quotes (") and
116687 ** with all double quote characters escaped. For example:
116688 **
116689 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
116690 **
116691 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
116692 ** is the callers responsibility to call sqlite3_free() to release this
116693 ** memory.
116694 */
116695 static char *fts3QuoteId(char const *zInput){
116696   int nRet;
116697   char *zRet;
116698   nRet = 2 + (int)strlen(zInput)*2 + 1;
116699   zRet = sqlite3_malloc(nRet);
116700   if( zRet ){
116701     int i;
116702     char *z = zRet;
116703     *(z++) = '"';
116704     for(i=0; zInput[i]; i++){
116705       if( zInput[i]=='"' ) *(z++) = '"';
116706       *(z++) = zInput[i];
116707     }
116708     *(z++) = '"';
116709     *(z++) = '\0';
116710   }
116711   return zRet;
116712 }
116713
116714 /*
116715 ** Return a list of comma separated SQL expressions and a FROM clause that 
116716 ** could be used in a SELECT statement such as the following:
116717 **
116718 **     SELECT <list of expressions> FROM %_content AS x ...
116719 **
116720 ** to return the docid, followed by each column of text data in order
116721 ** from left to write. If parameter zFunc is not NULL, then instead of
116722 ** being returned directly each column of text data is passed to an SQL
116723 ** function named zFunc first. For example, if zFunc is "unzip" and the
116724 ** table has the three user-defined columns "a", "b", and "c", the following
116725 ** string is returned:
116726 **
116727 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
116728 **
116729 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
116730 ** is the responsibility of the caller to eventually free it.
116731 **
116732 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
116733 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116734 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
116735 ** no error occurs, *pRc is left unmodified.
116736 */
116737 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
116738   char *zRet = 0;
116739   char *zFree = 0;
116740   char *zFunction;
116741   int i;
116742
116743   if( p->zContentTbl==0 ){
116744     if( !zFunc ){
116745       zFunction = "";
116746     }else{
116747       zFree = zFunction = fts3QuoteId(zFunc);
116748     }
116749     fts3Appendf(pRc, &zRet, "docid");
116750     for(i=0; i<p->nColumn; i++){
116751       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
116752     }
116753     if( p->zLanguageid ){
116754       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
116755     }
116756     sqlite3_free(zFree);
116757   }else{
116758     fts3Appendf(pRc, &zRet, "rowid");
116759     for(i=0; i<p->nColumn; i++){
116760       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
116761     }
116762     if( p->zLanguageid ){
116763       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
116764     }
116765   }
116766   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
116767       p->zDb,
116768       (p->zContentTbl ? p->zContentTbl : p->zName),
116769       (p->zContentTbl ? "" : "_content")
116770   );
116771   return zRet;
116772 }
116773
116774 /*
116775 ** Return a list of N comma separated question marks, where N is the number
116776 ** of columns in the %_content table (one for the docid plus one for each
116777 ** user-defined text column).
116778 **
116779 ** If argument zFunc is not NULL, then all but the first question mark
116780 ** is preceded by zFunc and an open bracket, and followed by a closed
116781 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
116782 ** user-defined text columns, the following string is returned:
116783 **
116784 **     "?, zip(?), zip(?), zip(?)"
116785 **
116786 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
116787 ** is the responsibility of the caller to eventually free it.
116788 **
116789 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
116790 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116791 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
116792 ** no error occurs, *pRc is left unmodified.
116793 */
116794 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
116795   char *zRet = 0;
116796   char *zFree = 0;
116797   char *zFunction;
116798   int i;
116799
116800   if( !zFunc ){
116801     zFunction = "";
116802   }else{
116803     zFree = zFunction = fts3QuoteId(zFunc);
116804   }
116805   fts3Appendf(pRc, &zRet, "?");
116806   for(i=0; i<p->nColumn; i++){
116807     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
116808   }
116809   if( p->zLanguageid ){
116810     fts3Appendf(pRc, &zRet, ", ?");
116811   }
116812   sqlite3_free(zFree);
116813   return zRet;
116814 }
116815
116816 /*
116817 ** This function interprets the string at (*pp) as a non-negative integer
116818 ** value. It reads the integer and sets *pnOut to the value read, then 
116819 ** sets *pp to point to the byte immediately following the last byte of
116820 ** the integer value.
116821 **
116822 ** Only decimal digits ('0'..'9') may be part of an integer value. 
116823 **
116824 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
116825 ** the output value undefined. Otherwise SQLITE_OK is returned.
116826 **
116827 ** This function is used when parsing the "prefix=" FTS4 parameter.
116828 */
116829 static int fts3GobbleInt(const char **pp, int *pnOut){
116830   const char *p;                  /* Iterator pointer */
116831   int nInt = 0;                   /* Output value */
116832
116833   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
116834     nInt = nInt * 10 + (p[0] - '0');
116835   }
116836   if( p==*pp ) return SQLITE_ERROR;
116837   *pnOut = nInt;
116838   *pp = p;
116839   return SQLITE_OK;
116840 }
116841
116842 /*
116843 ** This function is called to allocate an array of Fts3Index structures
116844 ** representing the indexes maintained by the current FTS table. FTS tables
116845 ** always maintain the main "terms" index, but may also maintain one or
116846 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
116847 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
116848 **
116849 ** Argument zParam is passed the value of the "prefix=" option if one was
116850 ** specified, or NULL otherwise.
116851 **
116852 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
116853 ** the allocated array. *pnIndex is set to the number of elements in the
116854 ** array. If an error does occur, an SQLite error code is returned.
116855 **
116856 ** Regardless of whether or not an error is returned, it is the responsibility
116857 ** of the caller to call sqlite3_free() on the output array to free it.
116858 */
116859 static int fts3PrefixParameter(
116860   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
116861   int *pnIndex,                   /* OUT: size of *apIndex[] array */
116862   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
116863 ){
116864   struct Fts3Index *aIndex;       /* Allocated array */
116865   int nIndex = 1;                 /* Number of entries in array */
116866
116867   if( zParam && zParam[0] ){
116868     const char *p;
116869     nIndex++;
116870     for(p=zParam; *p; p++){
116871       if( *p==',' ) nIndex++;
116872     }
116873   }
116874
116875   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
116876   *apIndex = aIndex;
116877   *pnIndex = nIndex;
116878   if( !aIndex ){
116879     return SQLITE_NOMEM;
116880   }
116881
116882   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
116883   if( zParam ){
116884     const char *p = zParam;
116885     int i;
116886     for(i=1; i<nIndex; i++){
116887       int nPrefix;
116888       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
116889       aIndex[i].nPrefix = nPrefix;
116890       p++;
116891     }
116892   }
116893
116894   return SQLITE_OK;
116895 }
116896
116897 /*
116898 ** This function is called when initializing an FTS4 table that uses the
116899 ** content=xxx option. It determines the number of and names of the columns
116900 ** of the new FTS4 table.
116901 **
116902 ** The third argument passed to this function is the value passed to the
116903 ** config=xxx option (i.e. "xxx"). This function queries the database for
116904 ** a table of that name. If found, the output variables are populated
116905 ** as follows:
116906 **
116907 **   *pnCol:   Set to the number of columns table xxx has,
116908 **
116909 **   *pnStr:   Set to the total amount of space required to store a copy
116910 **             of each columns name, including the nul-terminator.
116911 **
116912 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
116913 **             the name of the corresponding column in table xxx. The array
116914 **             and its contents are allocated using a single allocation. It
116915 **             is the responsibility of the caller to free this allocation
116916 **             by eventually passing the *pazCol value to sqlite3_free().
116917 **
116918 ** If the table cannot be found, an error code is returned and the output
116919 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
116920 ** returned (and the output variables are undefined).
116921 */
116922 static int fts3ContentColumns(
116923   sqlite3 *db,                    /* Database handle */
116924   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
116925   const char *zTbl,               /* Name of content table */
116926   const char ***pazCol,           /* OUT: Malloc'd array of column names */
116927   int *pnCol,                     /* OUT: Size of array *pazCol */
116928   int *pnStr                      /* OUT: Bytes of string content */
116929 ){
116930   int rc = SQLITE_OK;             /* Return code */
116931   char *zSql;                     /* "SELECT *" statement on zTbl */  
116932   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
116933
116934   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
116935   if( !zSql ){
116936     rc = SQLITE_NOMEM;
116937   }else{
116938     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
116939   }
116940   sqlite3_free(zSql);
116941
116942   if( rc==SQLITE_OK ){
116943     const char **azCol;           /* Output array */
116944     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
116945     int nCol;                     /* Number of table columns */
116946     int i;                        /* Used to iterate through columns */
116947
116948     /* Loop through the returned columns. Set nStr to the number of bytes of
116949     ** space required to store a copy of each column name, including the
116950     ** nul-terminator byte.  */
116951     nCol = sqlite3_column_count(pStmt);
116952     for(i=0; i<nCol; i++){
116953       const char *zCol = sqlite3_column_name(pStmt, i);
116954       nStr += (int)strlen(zCol) + 1;
116955     }
116956
116957     /* Allocate and populate the array to return. */
116958     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
116959     if( azCol==0 ){
116960       rc = SQLITE_NOMEM;
116961     }else{
116962       char *p = (char *)&azCol[nCol];
116963       for(i=0; i<nCol; i++){
116964         const char *zCol = sqlite3_column_name(pStmt, i);
116965         int n = (int)strlen(zCol)+1;
116966         memcpy(p, zCol, n);
116967         azCol[i] = p;
116968         p += n;
116969       }
116970     }
116971     sqlite3_finalize(pStmt);
116972
116973     /* Set the output variables. */
116974     *pnCol = nCol;
116975     *pnStr = nStr;
116976     *pazCol = azCol;
116977   }
116978
116979   return rc;
116980 }
116981
116982 /*
116983 ** This function is the implementation of both the xConnect and xCreate
116984 ** methods of the FTS3 virtual table.
116985 **
116986 ** The argv[] array contains the following:
116987 **
116988 **   argv[0]   -> module name  ("fts3" or "fts4")
116989 **   argv[1]   -> database name
116990 **   argv[2]   -> table name
116991 **   argv[...] -> "column name" and other module argument fields.
116992 */
116993 static int fts3InitVtab(
116994   int isCreate,                   /* True for xCreate, false for xConnect */
116995   sqlite3 *db,                    /* The SQLite database connection */
116996   void *pAux,                     /* Hash table containing tokenizers */
116997   int argc,                       /* Number of elements in argv array */
116998   const char * const *argv,       /* xCreate/xConnect argument array */
116999   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
117000   char **pzErr                    /* Write any error message here */
117001 ){
117002   Fts3Hash *pHash = (Fts3Hash *)pAux;
117003   Fts3Table *p = 0;               /* Pointer to allocated vtab */
117004   int rc = SQLITE_OK;             /* Return code */
117005   int i;                          /* Iterator variable */
117006   int nByte;                      /* Size of allocation used for *p */
117007   int iCol;                       /* Column index */
117008   int nString = 0;                /* Bytes required to hold all column names */
117009   int nCol = 0;                   /* Number of columns in the FTS table */
117010   char *zCsr;                     /* Space for holding column names */
117011   int nDb;                        /* Bytes required to hold database name */
117012   int nName;                      /* Bytes required to hold table name */
117013   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
117014   const char **aCol;              /* Array of column names */
117015   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
117016
117017   int nIndex;                     /* Size of aIndex[] array */
117018   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
117019
117020   /* The results of parsing supported FTS4 key=value options: */
117021   int bNoDocsize = 0;             /* True to omit %_docsize table */
117022   int bDescIdx = 0;               /* True to store descending indexes */
117023   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
117024   char *zCompress = 0;            /* compress=? parameter (or NULL) */
117025   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
117026   char *zContent = 0;             /* content=? parameter (or NULL) */
117027   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
117028
117029   assert( strlen(argv[0])==4 );
117030   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
117031        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
117032   );
117033
117034   nDb = (int)strlen(argv[1]) + 1;
117035   nName = (int)strlen(argv[2]) + 1;
117036
117037   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
117038   if( !aCol ) return SQLITE_NOMEM;
117039   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
117040
117041   /* Loop through all of the arguments passed by the user to the FTS3/4
117042   ** module (i.e. all the column names and special arguments). This loop
117043   ** does the following:
117044   **
117045   **   + Figures out the number of columns the FTSX table will have, and
117046   **     the number of bytes of space that must be allocated to store copies
117047   **     of the column names.
117048   **
117049   **   + If there is a tokenizer specification included in the arguments,
117050   **     initializes the tokenizer pTokenizer.
117051   */
117052   for(i=3; rc==SQLITE_OK && i<argc; i++){
117053     char const *z = argv[i];
117054     int nKey;
117055     char *zVal;
117056
117057     /* Check if this is a tokenizer specification */
117058     if( !pTokenizer 
117059      && strlen(z)>8
117060      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
117061      && 0==sqlite3Fts3IsIdChar(z[8])
117062     ){
117063       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
117064     }
117065
117066     /* Check if it is an FTS4 special argument. */
117067     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
117068       struct Fts4Option {
117069         const char *zOpt;
117070         int nOpt;
117071       } aFts4Opt[] = {
117072         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
117073         { "prefix",      6 },     /* 1 -> PREFIX */
117074         { "compress",    8 },     /* 2 -> COMPRESS */
117075         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
117076         { "order",       5 },     /* 4 -> ORDER */
117077         { "content",     7 },     /* 5 -> CONTENT */
117078         { "languageid", 10 }      /* 6 -> LANGUAGEID */
117079       };
117080
117081       int iOpt;
117082       if( !zVal ){
117083         rc = SQLITE_NOMEM;
117084       }else{
117085         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
117086           struct Fts4Option *pOp = &aFts4Opt[iOpt];
117087           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
117088             break;
117089           }
117090         }
117091         if( iOpt==SizeofArray(aFts4Opt) ){
117092           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
117093           rc = SQLITE_ERROR;
117094         }else{
117095           switch( iOpt ){
117096             case 0:               /* MATCHINFO */
117097               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
117098                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
117099                 rc = SQLITE_ERROR;
117100               }
117101               bNoDocsize = 1;
117102               break;
117103
117104             case 1:               /* PREFIX */
117105               sqlite3_free(zPrefix);
117106               zPrefix = zVal;
117107               zVal = 0;
117108               break;
117109
117110             case 2:               /* COMPRESS */
117111               sqlite3_free(zCompress);
117112               zCompress = zVal;
117113               zVal = 0;
117114               break;
117115
117116             case 3:               /* UNCOMPRESS */
117117               sqlite3_free(zUncompress);
117118               zUncompress = zVal;
117119               zVal = 0;
117120               break;
117121
117122             case 4:               /* ORDER */
117123               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
117124                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
117125               ){
117126                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
117127                 rc = SQLITE_ERROR;
117128               }
117129               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
117130               break;
117131
117132             case 5:              /* CONTENT */
117133               sqlite3_free(zContent);
117134               zContent = zVal;
117135               zVal = 0;
117136               break;
117137
117138             case 6:              /* LANGUAGEID */
117139               assert( iOpt==6 );
117140               sqlite3_free(zLanguageid);
117141               zLanguageid = zVal;
117142               zVal = 0;
117143               break;
117144           }
117145         }
117146         sqlite3_free(zVal);
117147       }
117148     }
117149
117150     /* Otherwise, the argument is a column name. */
117151     else {
117152       nString += (int)(strlen(z) + 1);
117153       aCol[nCol++] = z;
117154     }
117155   }
117156
117157   /* If a content=xxx option was specified, the following:
117158   **
117159   **   1. Ignore any compress= and uncompress= options.
117160   **
117161   **   2. If no column names were specified as part of the CREATE VIRTUAL
117162   **      TABLE statement, use all columns from the content table.
117163   */
117164   if( rc==SQLITE_OK && zContent ){
117165     sqlite3_free(zCompress); 
117166     sqlite3_free(zUncompress); 
117167     zCompress = 0;
117168     zUncompress = 0;
117169     if( nCol==0 ){
117170       sqlite3_free((void*)aCol); 
117171       aCol = 0;
117172       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
117173
117174       /* If a languageid= option was specified, remove the language id
117175       ** column from the aCol[] array. */ 
117176       if( rc==SQLITE_OK && zLanguageid ){
117177         int j;
117178         for(j=0; j<nCol; j++){
117179           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
117180             int k;
117181             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
117182             nCol--;
117183             break;
117184           }
117185         }
117186       }
117187     }
117188   }
117189   if( rc!=SQLITE_OK ) goto fts3_init_out;
117190
117191   if( nCol==0 ){
117192     assert( nString==0 );
117193     aCol[0] = "content";
117194     nString = 8;
117195     nCol = 1;
117196   }
117197
117198   if( pTokenizer==0 ){
117199     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
117200     if( rc!=SQLITE_OK ) goto fts3_init_out;
117201   }
117202   assert( pTokenizer );
117203
117204   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
117205   if( rc==SQLITE_ERROR ){
117206     assert( zPrefix );
117207     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
117208   }
117209   if( rc!=SQLITE_OK ) goto fts3_init_out;
117210
117211   /* Allocate and populate the Fts3Table structure. */
117212   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
117213           nCol * sizeof(char *) +              /* azColumn */
117214           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
117215           nName +                              /* zName */
117216           nDb +                                /* zDb */
117217           nString;                             /* Space for azColumn strings */
117218   p = (Fts3Table*)sqlite3_malloc(nByte);
117219   if( p==0 ){
117220     rc = SQLITE_NOMEM;
117221     goto fts3_init_out;
117222   }
117223   memset(p, 0, nByte);
117224   p->db = db;
117225   p->nColumn = nCol;
117226   p->nPendingData = 0;
117227   p->azColumn = (char **)&p[1];
117228   p->pTokenizer = pTokenizer;
117229   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
117230   p->bHasDocsize = (isFts4 && bNoDocsize==0);
117231   p->bHasStat = isFts4;
117232   p->bFts4 = isFts4;
117233   p->bDescIdx = bDescIdx;
117234   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
117235   p->zContentTbl = zContent;
117236   p->zLanguageid = zLanguageid;
117237   zContent = 0;
117238   zLanguageid = 0;
117239   TESTONLY( p->inTransaction = -1 );
117240   TESTONLY( p->mxSavepoint = -1 );
117241
117242   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
117243   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
117244   p->nIndex = nIndex;
117245   for(i=0; i<nIndex; i++){
117246     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
117247   }
117248
117249   /* Fill in the zName and zDb fields of the vtab structure. */
117250   zCsr = (char *)&p->aIndex[nIndex];
117251   p->zName = zCsr;
117252   memcpy(zCsr, argv[2], nName);
117253   zCsr += nName;
117254   p->zDb = zCsr;
117255   memcpy(zCsr, argv[1], nDb);
117256   zCsr += nDb;
117257
117258   /* Fill in the azColumn array */
117259   for(iCol=0; iCol<nCol; iCol++){
117260     char *z; 
117261     int n = 0;
117262     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
117263     memcpy(zCsr, z, n);
117264     zCsr[n] = '\0';
117265     sqlite3Fts3Dequote(zCsr);
117266     p->azColumn[iCol] = zCsr;
117267     zCsr += n+1;
117268     assert( zCsr <= &((char *)p)[nByte] );
117269   }
117270
117271   if( (zCompress==0)!=(zUncompress==0) ){
117272     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
117273     rc = SQLITE_ERROR;
117274     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
117275   }
117276   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
117277   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
117278   if( rc!=SQLITE_OK ) goto fts3_init_out;
117279
117280   /* If this is an xCreate call, create the underlying tables in the 
117281   ** database. TODO: For xConnect(), it could verify that said tables exist.
117282   */
117283   if( isCreate ){
117284     rc = fts3CreateTables(p);
117285   }
117286
117287   /* Check to see if a legacy fts3 table has been "upgraded" by the
117288   ** addition of a %_stat table so that it can use incremental merge.
117289   */
117290   if( !isFts4 && !isCreate ){
117291     int rc2 = SQLITE_OK;
117292     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
117293                p->zDb, p->zName);
117294     if( rc2==SQLITE_OK ) p->bHasStat = 1;
117295   }
117296
117297   /* Figure out the page-size for the database. This is required in order to
117298   ** estimate the cost of loading large doclists from the database.  */
117299   fts3DatabasePageSize(&rc, p);
117300   p->nNodeSize = p->nPgsz-35;
117301
117302   /* Declare the table schema to SQLite. */
117303   fts3DeclareVtab(&rc, p);
117304
117305 fts3_init_out:
117306   sqlite3_free(zPrefix);
117307   sqlite3_free(aIndex);
117308   sqlite3_free(zCompress);
117309   sqlite3_free(zUncompress);
117310   sqlite3_free(zContent);
117311   sqlite3_free(zLanguageid);
117312   sqlite3_free((void *)aCol);
117313   if( rc!=SQLITE_OK ){
117314     if( p ){
117315       fts3DisconnectMethod((sqlite3_vtab *)p);
117316     }else if( pTokenizer ){
117317       pTokenizer->pModule->xDestroy(pTokenizer);
117318     }
117319   }else{
117320     assert( p->pSegments==0 );
117321     *ppVTab = &p->base;
117322   }
117323   return rc;
117324 }
117325
117326 /*
117327 ** The xConnect() and xCreate() methods for the virtual table. All the
117328 ** work is done in function fts3InitVtab().
117329 */
117330 static int fts3ConnectMethod(
117331   sqlite3 *db,                    /* Database connection */
117332   void *pAux,                     /* Pointer to tokenizer hash table */
117333   int argc,                       /* Number of elements in argv array */
117334   const char * const *argv,       /* xCreate/xConnect argument array */
117335   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
117336   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
117337 ){
117338   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
117339 }
117340 static int fts3CreateMethod(
117341   sqlite3 *db,                    /* Database connection */
117342   void *pAux,                     /* Pointer to tokenizer hash table */
117343   int argc,                       /* Number of elements in argv array */
117344   const char * const *argv,       /* xCreate/xConnect argument array */
117345   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
117346   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
117347 ){
117348   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
117349 }
117350
117351 /* 
117352 ** Implementation of the xBestIndex method for FTS3 tables. There
117353 ** are three possible strategies, in order of preference:
117354 **
117355 **   1. Direct lookup by rowid or docid. 
117356 **   2. Full-text search using a MATCH operator on a non-docid column.
117357 **   3. Linear scan of %_content table.
117358 */
117359 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
117360   Fts3Table *p = (Fts3Table *)pVTab;
117361   int i;                          /* Iterator variable */
117362   int iCons = -1;                 /* Index of constraint to use */
117363   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
117364
117365   /* By default use a full table scan. This is an expensive option,
117366   ** so search through the constraints to see if a more efficient 
117367   ** strategy is possible.
117368   */
117369   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
117370   pInfo->estimatedCost = 500000;
117371   for(i=0; i<pInfo->nConstraint; i++){
117372     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
117373     if( pCons->usable==0 ) continue;
117374
117375     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
117376     if( iCons<0 
117377      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
117378      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
117379     ){
117380       pInfo->idxNum = FTS3_DOCID_SEARCH;
117381       pInfo->estimatedCost = 1.0;
117382       iCons = i;
117383     }
117384
117385     /* A MATCH constraint. Use a full-text search.
117386     **
117387     ** If there is more than one MATCH constraint available, use the first
117388     ** one encountered. If there is both a MATCH constraint and a direct
117389     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
117390     ** though the rowid/docid lookup is faster than a MATCH query, selecting
117391     ** it would lead to an "unable to use function MATCH in the requested 
117392     ** context" error.
117393     */
117394     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
117395      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
117396     ){
117397       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
117398       pInfo->estimatedCost = 2.0;
117399       iCons = i;
117400     }
117401
117402     /* Equality constraint on the langid column */
117403     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
117404      && pCons->iColumn==p->nColumn + 2
117405     ){
117406       iLangidCons = i;
117407     }
117408   }
117409
117410   if( iCons>=0 ){
117411     pInfo->aConstraintUsage[iCons].argvIndex = 1;
117412     pInfo->aConstraintUsage[iCons].omit = 1;
117413   } 
117414   if( iLangidCons>=0 ){
117415     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
117416   } 
117417
117418   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
117419   ** docid) order. Both ascending and descending are possible. 
117420   */
117421   if( pInfo->nOrderBy==1 ){
117422     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
117423     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
117424       if( pOrder->desc ){
117425         pInfo->idxStr = "DESC";
117426       }else{
117427         pInfo->idxStr = "ASC";
117428       }
117429       pInfo->orderByConsumed = 1;
117430     }
117431   }
117432
117433   assert( p->pSegments==0 );
117434   return SQLITE_OK;
117435 }
117436
117437 /*
117438 ** Implementation of xOpen method.
117439 */
117440 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
117441   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
117442
117443   UNUSED_PARAMETER(pVTab);
117444
117445   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
117446   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
117447   ** if the allocation fails, return SQLITE_NOMEM.
117448   */
117449   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
117450   if( !pCsr ){
117451     return SQLITE_NOMEM;
117452   }
117453   memset(pCsr, 0, sizeof(Fts3Cursor));
117454   return SQLITE_OK;
117455 }
117456
117457 /*
117458 ** Close the cursor.  For additional information see the documentation
117459 ** on the xClose method of the virtual table interface.
117460 */
117461 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
117462   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
117463   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117464   sqlite3_finalize(pCsr->pStmt);
117465   sqlite3Fts3ExprFree(pCsr->pExpr);
117466   sqlite3Fts3FreeDeferredTokens(pCsr);
117467   sqlite3_free(pCsr->aDoclist);
117468   sqlite3_free(pCsr->aMatchinfo);
117469   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117470   sqlite3_free(pCsr);
117471   return SQLITE_OK;
117472 }
117473
117474 /*
117475 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
117476 ** compose and prepare an SQL statement of the form:
117477 **
117478 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
117479 **
117480 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
117481 ** it. If an error occurs, return an SQLite error code.
117482 **
117483 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
117484 */
117485 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
117486   int rc = SQLITE_OK;
117487   if( pCsr->pStmt==0 ){
117488     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117489     char *zSql;
117490     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
117491     if( !zSql ) return SQLITE_NOMEM;
117492     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
117493     sqlite3_free(zSql);
117494   }
117495   *ppStmt = pCsr->pStmt;
117496   return rc;
117497 }
117498
117499 /*
117500 ** Position the pCsr->pStmt statement so that it is on the row
117501 ** of the %_content table that contains the last match.  Return
117502 ** SQLITE_OK on success.  
117503 */
117504 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
117505   int rc = SQLITE_OK;
117506   if( pCsr->isRequireSeek ){
117507     sqlite3_stmt *pStmt = 0;
117508
117509     rc = fts3CursorSeekStmt(pCsr, &pStmt);
117510     if( rc==SQLITE_OK ){
117511       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
117512       pCsr->isRequireSeek = 0;
117513       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
117514         return SQLITE_OK;
117515       }else{
117516         rc = sqlite3_reset(pCsr->pStmt);
117517         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
117518           /* If no row was found and no error has occured, then the %_content
117519           ** table is missing a row that is present in the full-text index.
117520           ** The data structures are corrupt.  */
117521           rc = FTS_CORRUPT_VTAB;
117522           pCsr->isEof = 1;
117523         }
117524       }
117525     }
117526   }
117527
117528   if( rc!=SQLITE_OK && pContext ){
117529     sqlite3_result_error_code(pContext, rc);
117530   }
117531   return rc;
117532 }
117533
117534 /*
117535 ** This function is used to process a single interior node when searching
117536 ** a b-tree for a term or term prefix. The node data is passed to this 
117537 ** function via the zNode/nNode parameters. The term to search for is
117538 ** passed in zTerm/nTerm.
117539 **
117540 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
117541 ** of the child node that heads the sub-tree that may contain the term.
117542 **
117543 ** If piLast is not NULL, then *piLast is set to the right-most child node
117544 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
117545 ** a prefix.
117546 **
117547 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
117548 */
117549 static int fts3ScanInteriorNode(
117550   const char *zTerm,              /* Term to select leaves for */
117551   int nTerm,                      /* Size of term zTerm in bytes */
117552   const char *zNode,              /* Buffer containing segment interior node */
117553   int nNode,                      /* Size of buffer at zNode */
117554   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
117555   sqlite3_int64 *piLast           /* OUT: Selected child node */
117556 ){
117557   int rc = SQLITE_OK;             /* Return code */
117558   const char *zCsr = zNode;       /* Cursor to iterate through node */
117559   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
117560   char *zBuffer = 0;              /* Buffer to load terms into */
117561   int nAlloc = 0;                 /* Size of allocated buffer */
117562   int isFirstTerm = 1;            /* True when processing first term on page */
117563   sqlite3_int64 iChild;           /* Block id of child node to descend to */
117564
117565   /* Skip over the 'height' varint that occurs at the start of every 
117566   ** interior node. Then load the blockid of the left-child of the b-tree
117567   ** node into variable iChild.  
117568   **
117569   ** Even if the data structure on disk is corrupted, this (reading two
117570   ** varints from the buffer) does not risk an overread. If zNode is a
117571   ** root node, then the buffer comes from a SELECT statement. SQLite does
117572   ** not make this guarantee explicitly, but in practice there are always
117573   ** either more than 20 bytes of allocated space following the nNode bytes of
117574   ** contents, or two zero bytes. Or, if the node is read from the %_segments
117575   ** table, then there are always 20 bytes of zeroed padding following the
117576   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
117577   */
117578   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
117579   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
117580   if( zCsr>zEnd ){
117581     return FTS_CORRUPT_VTAB;
117582   }
117583   
117584   while( zCsr<zEnd && (piFirst || piLast) ){
117585     int cmp;                      /* memcmp() result */
117586     int nSuffix;                  /* Size of term suffix */
117587     int nPrefix = 0;              /* Size of term prefix */
117588     int nBuffer;                  /* Total term size */
117589   
117590     /* Load the next term on the node into zBuffer. Use realloc() to expand
117591     ** the size of zBuffer if required.  */
117592     if( !isFirstTerm ){
117593       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
117594     }
117595     isFirstTerm = 0;
117596     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
117597     
117598     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
117599       rc = FTS_CORRUPT_VTAB;
117600       goto finish_scan;
117601     }
117602     if( nPrefix+nSuffix>nAlloc ){
117603       char *zNew;
117604       nAlloc = (nPrefix+nSuffix) * 2;
117605       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
117606       if( !zNew ){
117607         rc = SQLITE_NOMEM;
117608         goto finish_scan;
117609       }
117610       zBuffer = zNew;
117611     }
117612     assert( zBuffer );
117613     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
117614     nBuffer = nPrefix + nSuffix;
117615     zCsr += nSuffix;
117616
117617     /* Compare the term we are searching for with the term just loaded from
117618     ** the interior node. If the specified term is greater than or equal
117619     ** to the term from the interior node, then all terms on the sub-tree 
117620     ** headed by node iChild are smaller than zTerm. No need to search 
117621     ** iChild.
117622     **
117623     ** If the interior node term is larger than the specified term, then
117624     ** the tree headed by iChild may contain the specified term.
117625     */
117626     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
117627     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
117628       *piFirst = iChild;
117629       piFirst = 0;
117630     }
117631
117632     if( piLast && cmp<0 ){
117633       *piLast = iChild;
117634       piLast = 0;
117635     }
117636
117637     iChild++;
117638   };
117639
117640   if( piFirst ) *piFirst = iChild;
117641   if( piLast ) *piLast = iChild;
117642
117643  finish_scan:
117644   sqlite3_free(zBuffer);
117645   return rc;
117646 }
117647
117648
117649 /*
117650 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
117651 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
117652 ** contains a term. This function searches the sub-tree headed by the zNode
117653 ** node for the range of leaf nodes that may contain the specified term
117654 ** or terms for which the specified term is a prefix.
117655 **
117656 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
117657 ** left-most leaf node in the tree that may contain the specified term.
117658 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
117659 ** right-most leaf node that may contain a term for which the specified
117660 ** term is a prefix.
117661 **
117662 ** It is possible that the range of returned leaf nodes does not contain 
117663 ** the specified term or any terms for which it is a prefix. However, if the 
117664 ** segment does contain any such terms, they are stored within the identified
117665 ** range. Because this function only inspects interior segment nodes (and
117666 ** never loads leaf nodes into memory), it is not possible to be sure.
117667 **
117668 ** If an error occurs, an error code other than SQLITE_OK is returned.
117669 */ 
117670 static int fts3SelectLeaf(
117671   Fts3Table *p,                   /* Virtual table handle */
117672   const char *zTerm,              /* Term to select leaves for */
117673   int nTerm,                      /* Size of term zTerm in bytes */
117674   const char *zNode,              /* Buffer containing segment interior node */
117675   int nNode,                      /* Size of buffer at zNode */
117676   sqlite3_int64 *piLeaf,          /* Selected leaf node */
117677   sqlite3_int64 *piLeaf2          /* Selected leaf node */
117678 ){
117679   int rc;                         /* Return code */
117680   int iHeight;                    /* Height of this node in tree */
117681
117682   assert( piLeaf || piLeaf2 );
117683
117684   sqlite3Fts3GetVarint32(zNode, &iHeight);
117685   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
117686   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
117687
117688   if( rc==SQLITE_OK && iHeight>1 ){
117689     char *zBlob = 0;              /* Blob read from %_segments table */
117690     int nBlob;                    /* Size of zBlob in bytes */
117691
117692     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
117693       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
117694       if( rc==SQLITE_OK ){
117695         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
117696       }
117697       sqlite3_free(zBlob);
117698       piLeaf = 0;
117699       zBlob = 0;
117700     }
117701
117702     if( rc==SQLITE_OK ){
117703       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
117704     }
117705     if( rc==SQLITE_OK ){
117706       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
117707     }
117708     sqlite3_free(zBlob);
117709   }
117710
117711   return rc;
117712 }
117713
117714 /*
117715 ** This function is used to create delta-encoded serialized lists of FTS3 
117716 ** varints. Each call to this function appends a single varint to a list.
117717 */
117718 static void fts3PutDeltaVarint(
117719   char **pp,                      /* IN/OUT: Output pointer */
117720   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
117721   sqlite3_int64 iVal              /* Write this value to the list */
117722 ){
117723   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
117724   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
117725   *piPrev = iVal;
117726 }
117727
117728 /*
117729 ** When this function is called, *ppPoslist is assumed to point to the 
117730 ** start of a position-list. After it returns, *ppPoslist points to the
117731 ** first byte after the position-list.
117732 **
117733 ** A position list is list of positions (delta encoded) and columns for 
117734 ** a single document record of a doclist.  So, in other words, this
117735 ** routine advances *ppPoslist so that it points to the next docid in
117736 ** the doclist, or to the first byte past the end of the doclist.
117737 **
117738 ** If pp is not NULL, then the contents of the position list are copied
117739 ** to *pp. *pp is set to point to the first byte past the last byte copied
117740 ** before this function returns.
117741 */
117742 static void fts3PoslistCopy(char **pp, char **ppPoslist){
117743   char *pEnd = *ppPoslist;
117744   char c = 0;
117745
117746   /* The end of a position list is marked by a zero encoded as an FTS3 
117747   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
117748   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
117749   ** of some other, multi-byte, value.
117750   **
117751   ** The following while-loop moves pEnd to point to the first byte that is not 
117752   ** immediately preceded by a byte with the 0x80 bit set. Then increments
117753   ** pEnd once more so that it points to the byte immediately following the
117754   ** last byte in the position-list.
117755   */
117756   while( *pEnd | c ){
117757     c = *pEnd++ & 0x80;
117758     testcase( c!=0 && (*pEnd)==0 );
117759   }
117760   pEnd++;  /* Advance past the POS_END terminator byte */
117761
117762   if( pp ){
117763     int n = (int)(pEnd - *ppPoslist);
117764     char *p = *pp;
117765     memcpy(p, *ppPoslist, n);
117766     p += n;
117767     *pp = p;
117768   }
117769   *ppPoslist = pEnd;
117770 }
117771
117772 /*
117773 ** When this function is called, *ppPoslist is assumed to point to the 
117774 ** start of a column-list. After it returns, *ppPoslist points to the
117775 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
117776 **
117777 ** A column-list is list of delta-encoded positions for a single column
117778 ** within a single document within a doclist.
117779 **
117780 ** The column-list is terminated either by a POS_COLUMN varint (1) or
117781 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
117782 ** the POS_COLUMN or POS_END that terminates the column-list.
117783 **
117784 ** If pp is not NULL, then the contents of the column-list are copied
117785 ** to *pp. *pp is set to point to the first byte past the last byte copied
117786 ** before this function returns.  The POS_COLUMN or POS_END terminator
117787 ** is not copied into *pp.
117788 */
117789 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
117790   char *pEnd = *ppPoslist;
117791   char c = 0;
117792
117793   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
117794   ** not part of a multi-byte varint.
117795   */
117796   while( 0xFE & (*pEnd | c) ){
117797     c = *pEnd++ & 0x80;
117798     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
117799   }
117800   if( pp ){
117801     int n = (int)(pEnd - *ppPoslist);
117802     char *p = *pp;
117803     memcpy(p, *ppPoslist, n);
117804     p += n;
117805     *pp = p;
117806   }
117807   *ppPoslist = pEnd;
117808 }
117809
117810 /*
117811 ** Value used to signify the end of an position-list. This is safe because
117812 ** it is not possible to have a document with 2^31 terms.
117813 */
117814 #define POSITION_LIST_END 0x7fffffff
117815
117816 /*
117817 ** This function is used to help parse position-lists. When this function is
117818 ** called, *pp may point to the start of the next varint in the position-list
117819 ** being parsed, or it may point to 1 byte past the end of the position-list
117820 ** (in which case **pp will be a terminator bytes POS_END (0) or
117821 ** (1)).
117822 **
117823 ** If *pp points past the end of the current position-list, set *pi to 
117824 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
117825 ** increment the current value of *pi by the value read, and set *pp to
117826 ** point to the next value before returning.
117827 **
117828 ** Before calling this routine *pi must be initialized to the value of
117829 ** the previous position, or zero if we are reading the first position
117830 ** in the position-list.  Because positions are delta-encoded, the value
117831 ** of the previous position is needed in order to compute the value of
117832 ** the next position.
117833 */
117834 static void fts3ReadNextPos(
117835   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
117836   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
117837 ){
117838   if( (**pp)&0xFE ){
117839     fts3GetDeltaVarint(pp, pi);
117840     *pi -= 2;
117841   }else{
117842     *pi = POSITION_LIST_END;
117843   }
117844 }
117845
117846 /*
117847 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
117848 ** the value of iCol encoded as a varint to *pp.   This will start a new
117849 ** column list.
117850 **
117851 ** Set *pp to point to the byte just after the last byte written before 
117852 ** returning (do not modify it if iCol==0). Return the total number of bytes
117853 ** written (0 if iCol==0).
117854 */
117855 static int fts3PutColNumber(char **pp, int iCol){
117856   int n = 0;                      /* Number of bytes written */
117857   if( iCol ){
117858     char *p = *pp;                /* Output pointer */
117859     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
117860     *p = 0x01;
117861     *pp = &p[n];
117862   }
117863   return n;
117864 }
117865
117866 /*
117867 ** Compute the union of two position lists.  The output written
117868 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
117869 ** order and with any duplicates removed.  All pointers are
117870 ** updated appropriately.   The caller is responsible for insuring
117871 ** that there is enough space in *pp to hold the complete output.
117872 */
117873 static void fts3PoslistMerge(
117874   char **pp,                      /* Output buffer */
117875   char **pp1,                     /* Left input list */
117876   char **pp2                      /* Right input list */
117877 ){
117878   char *p = *pp;
117879   char *p1 = *pp1;
117880   char *p2 = *pp2;
117881
117882   while( *p1 || *p2 ){
117883     int iCol1;         /* The current column index in pp1 */
117884     int iCol2;         /* The current column index in pp2 */
117885
117886     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
117887     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
117888     else iCol1 = 0;
117889
117890     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
117891     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
117892     else iCol2 = 0;
117893
117894     if( iCol1==iCol2 ){
117895       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
117896       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
117897       sqlite3_int64 iPrev = 0;
117898       int n = fts3PutColNumber(&p, iCol1);
117899       p1 += n;
117900       p2 += n;
117901
117902       /* At this point, both p1 and p2 point to the start of column-lists
117903       ** for the same column (the column with index iCol1 and iCol2).
117904       ** A column-list is a list of non-negative delta-encoded varints, each 
117905       ** incremented by 2 before being stored. Each list is terminated by a
117906       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
117907       ** and writes the results to buffer p. p is left pointing to the byte
117908       ** after the list written. No terminator (POS_END or POS_COLUMN) is
117909       ** written to the output.
117910       */
117911       fts3GetDeltaVarint(&p1, &i1);
117912       fts3GetDeltaVarint(&p2, &i2);
117913       do {
117914         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
117915         iPrev -= 2;
117916         if( i1==i2 ){
117917           fts3ReadNextPos(&p1, &i1);
117918           fts3ReadNextPos(&p2, &i2);
117919         }else if( i1<i2 ){
117920           fts3ReadNextPos(&p1, &i1);
117921         }else{
117922           fts3ReadNextPos(&p2, &i2);
117923         }
117924       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
117925     }else if( iCol1<iCol2 ){
117926       p1 += fts3PutColNumber(&p, iCol1);
117927       fts3ColumnlistCopy(&p, &p1);
117928     }else{
117929       p2 += fts3PutColNumber(&p, iCol2);
117930       fts3ColumnlistCopy(&p, &p2);
117931     }
117932   }
117933
117934   *p++ = POS_END;
117935   *pp = p;
117936   *pp1 = p1 + 1;
117937   *pp2 = p2 + 1;
117938 }
117939
117940 /*
117941 ** This function is used to merge two position lists into one. When it is
117942 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
117943 ** the part of a doclist that follows each document id. For example, if a row
117944 ** contains:
117945 **
117946 **     'a b c'|'x y z'|'a b b a'
117947 **
117948 ** Then the position list for this row for token 'b' would consist of:
117949 **
117950 **     0x02 0x01 0x02 0x03 0x03 0x00
117951 **
117952 ** When this function returns, both *pp1 and *pp2 are left pointing to the
117953 ** byte following the 0x00 terminator of their respective position lists.
117954 **
117955 ** If isSaveLeft is 0, an entry is added to the output position list for 
117956 ** each position in *pp2 for which there exists one or more positions in
117957 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
117958 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
117959 ** slots before it.
117960 **
117961 ** e.g. nToken==1 searches for adjacent positions.
117962 */
117963 static int fts3PoslistPhraseMerge(
117964   char **pp,                      /* IN/OUT: Preallocated output buffer */
117965   int nToken,                     /* Maximum difference in token positions */
117966   int isSaveLeft,                 /* Save the left position */
117967   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
117968   char **pp1,                     /* IN/OUT: Left input list */
117969   char **pp2                      /* IN/OUT: Right input list */
117970 ){
117971   char *p = *pp;
117972   char *p1 = *pp1;
117973   char *p2 = *pp2;
117974   int iCol1 = 0;
117975   int iCol2 = 0;
117976
117977   /* Never set both isSaveLeft and isExact for the same invocation. */
117978   assert( isSaveLeft==0 || isExact==0 );
117979
117980   assert( p!=0 && *p1!=0 && *p2!=0 );
117981   if( *p1==POS_COLUMN ){ 
117982     p1++;
117983     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
117984   }
117985   if( *p2==POS_COLUMN ){ 
117986     p2++;
117987     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
117988   }
117989
117990   while( 1 ){
117991     if( iCol1==iCol2 ){
117992       char *pSave = p;
117993       sqlite3_int64 iPrev = 0;
117994       sqlite3_int64 iPos1 = 0;
117995       sqlite3_int64 iPos2 = 0;
117996
117997       if( iCol1 ){
117998         *p++ = POS_COLUMN;
117999         p += sqlite3Fts3PutVarint(p, iCol1);
118000       }
118001
118002       assert( *p1!=POS_END && *p1!=POS_COLUMN );
118003       assert( *p2!=POS_END && *p2!=POS_COLUMN );
118004       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118005       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118006
118007       while( 1 ){
118008         if( iPos2==iPos1+nToken 
118009          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
118010         ){
118011           sqlite3_int64 iSave;
118012           iSave = isSaveLeft ? iPos1 : iPos2;
118013           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
118014           pSave = 0;
118015           assert( p );
118016         }
118017         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
118018           if( (*p2&0xFE)==0 ) break;
118019           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118020         }else{
118021           if( (*p1&0xFE)==0 ) break;
118022           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118023         }
118024       }
118025
118026       if( pSave ){
118027         assert( pp && p );
118028         p = pSave;
118029       }
118030
118031       fts3ColumnlistCopy(0, &p1);
118032       fts3ColumnlistCopy(0, &p2);
118033       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
118034       if( 0==*p1 || 0==*p2 ) break;
118035
118036       p1++;
118037       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118038       p2++;
118039       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118040     }
118041
118042     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
118043     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
118044     ** end of the position list, or the 0x01 that precedes the next 
118045     ** column-number in the position list. 
118046     */
118047     else if( iCol1<iCol2 ){
118048       fts3ColumnlistCopy(0, &p1);
118049       if( 0==*p1 ) break;
118050       p1++;
118051       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118052     }else{
118053       fts3ColumnlistCopy(0, &p2);
118054       if( 0==*p2 ) break;
118055       p2++;
118056       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118057     }
118058   }
118059
118060   fts3PoslistCopy(0, &p2);
118061   fts3PoslistCopy(0, &p1);
118062   *pp1 = p1;
118063   *pp2 = p2;
118064   if( *pp==p ){
118065     return 0;
118066   }
118067   *p++ = 0x00;
118068   *pp = p;
118069   return 1;
118070 }
118071
118072 /*
118073 ** Merge two position-lists as required by the NEAR operator. The argument
118074 ** position lists correspond to the left and right phrases of an expression 
118075 ** like:
118076 **
118077 **     "phrase 1" NEAR "phrase number 2"
118078 **
118079 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
118080 ** expression and *pp2 to the right. As usual, the indexes in the position 
118081 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
118082 ** in the example above).
118083 **
118084 ** The output position list - written to *pp - is a copy of *pp2 with those
118085 ** entries that are not sufficiently NEAR entries in *pp1 removed.
118086 */
118087 static int fts3PoslistNearMerge(
118088   char **pp,                      /* Output buffer */
118089   char *aTmp,                     /* Temporary buffer space */
118090   int nRight,                     /* Maximum difference in token positions */
118091   int nLeft,                      /* Maximum difference in token positions */
118092   char **pp1,                     /* IN/OUT: Left input list */
118093   char **pp2                      /* IN/OUT: Right input list */
118094 ){
118095   char *p1 = *pp1;
118096   char *p2 = *pp2;
118097
118098   char *pTmp1 = aTmp;
118099   char *pTmp2;
118100   char *aTmp2;
118101   int res = 1;
118102
118103   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
118104   aTmp2 = pTmp2 = pTmp1;
118105   *pp1 = p1;
118106   *pp2 = p2;
118107   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
118108   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
118109     fts3PoslistMerge(pp, &aTmp, &aTmp2);
118110   }else if( pTmp1!=aTmp ){
118111     fts3PoslistCopy(pp, &aTmp);
118112   }else if( pTmp2!=aTmp2 ){
118113     fts3PoslistCopy(pp, &aTmp2);
118114   }else{
118115     res = 0;
118116   }
118117
118118   return res;
118119 }
118120
118121 /* 
118122 ** An instance of this function is used to merge together the (potentially
118123 ** large number of) doclists for each term that matches a prefix query.
118124 ** See function fts3TermSelectMerge() for details.
118125 */
118126 typedef struct TermSelect TermSelect;
118127 struct TermSelect {
118128   char *aaOutput[16];             /* Malloc'd output buffers */
118129   int anOutput[16];               /* Size each output buffer in bytes */
118130 };
118131
118132 /*
118133 ** This function is used to read a single varint from a buffer. Parameter
118134 ** pEnd points 1 byte past the end of the buffer. When this function is
118135 ** called, if *pp points to pEnd or greater, then the end of the buffer
118136 ** has been reached. In this case *pp is set to 0 and the function returns.
118137 **
118138 ** If *pp does not point to or past pEnd, then a single varint is read
118139 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
118140 **
118141 ** If bDescIdx is false, the value read is added to *pVal before returning.
118142 ** If it is true, the value read is subtracted from *pVal before this 
118143 ** function returns.
118144 */
118145 static void fts3GetDeltaVarint3(
118146   char **pp,                      /* IN/OUT: Point to read varint from */
118147   char *pEnd,                     /* End of buffer */
118148   int bDescIdx,                   /* True if docids are descending */
118149   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
118150 ){
118151   if( *pp>=pEnd ){
118152     *pp = 0;
118153   }else{
118154     sqlite3_int64 iVal;
118155     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118156     if( bDescIdx ){
118157       *pVal -= iVal;
118158     }else{
118159       *pVal += iVal;
118160     }
118161   }
118162 }
118163
118164 /*
118165 ** This function is used to write a single varint to a buffer. The varint
118166 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
118167 ** end of the value written.
118168 **
118169 ** If *pbFirst is zero when this function is called, the value written to
118170 ** the buffer is that of parameter iVal. 
118171 **
118172 ** If *pbFirst is non-zero when this function is called, then the value 
118173 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
118174 ** (if bDescIdx is non-zero).
118175 **
118176 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
118177 ** to the value of parameter iVal.
118178 */
118179 static void fts3PutDeltaVarint3(
118180   char **pp,                      /* IN/OUT: Output pointer */
118181   int bDescIdx,                   /* True for descending docids */
118182   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118183   int *pbFirst,                   /* IN/OUT: True after first int written */
118184   sqlite3_int64 iVal              /* Write this value to the list */
118185 ){
118186   sqlite3_int64 iWrite;
118187   if( bDescIdx==0 || *pbFirst==0 ){
118188     iWrite = iVal - *piPrev;
118189   }else{
118190     iWrite = *piPrev - iVal;
118191   }
118192   assert( *pbFirst || *piPrev==0 );
118193   assert( *pbFirst==0 || iWrite>0 );
118194   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
118195   *piPrev = iVal;
118196   *pbFirst = 1;
118197 }
118198
118199
118200 /*
118201 ** This macro is used by various functions that merge doclists. The two
118202 ** arguments are 64-bit docid values. If the value of the stack variable
118203 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
118204 ** Otherwise, (i2-i1).
118205 **
118206 ** Using this makes it easier to write code that can merge doclists that are
118207 ** sorted in either ascending or descending order.
118208 */
118209 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
118210
118211 /*
118212 ** This function does an "OR" merge of two doclists (output contains all
118213 ** positions contained in either argument doclist). If the docids in the 
118214 ** input doclists are sorted in ascending order, parameter bDescDoclist
118215 ** should be false. If they are sorted in ascending order, it should be
118216 ** passed a non-zero value.
118217 **
118218 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
118219 ** containing the output doclist and SQLITE_OK is returned. In this case
118220 ** *pnOut is set to the number of bytes in the output doclist.
118221 **
118222 ** If an error occurs, an SQLite error code is returned. The output values
118223 ** are undefined in this case.
118224 */
118225 static int fts3DoclistOrMerge(
118226   int bDescDoclist,               /* True if arguments are desc */
118227   char *a1, int n1,               /* First doclist */
118228   char *a2, int n2,               /* Second doclist */
118229   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
118230 ){
118231   sqlite3_int64 i1 = 0;
118232   sqlite3_int64 i2 = 0;
118233   sqlite3_int64 iPrev = 0;
118234   char *pEnd1 = &a1[n1];
118235   char *pEnd2 = &a2[n2];
118236   char *p1 = a1;
118237   char *p2 = a2;
118238   char *p;
118239   char *aOut;
118240   int bFirstOut = 0;
118241
118242   *paOut = 0;
118243   *pnOut = 0;
118244
118245   /* Allocate space for the output. Both the input and output doclists
118246   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
118247   ** then the first docid in each list is simply encoded as a varint. For
118248   ** each subsequent docid, the varint stored is the difference between the
118249   ** current and previous docid (a positive number - since the list is in
118250   ** ascending order).
118251   **
118252   ** The first docid written to the output is therefore encoded using the 
118253   ** same number of bytes as it is in whichever of the input lists it is
118254   ** read from. And each subsequent docid read from the same input list 
118255   ** consumes either the same or less bytes as it did in the input (since
118256   ** the difference between it and the previous value in the output must
118257   ** be a positive value less than or equal to the delta value read from 
118258   ** the input list). The same argument applies to all but the first docid
118259   ** read from the 'other' list. And to the contents of all position lists
118260   ** that will be copied and merged from the input to the output.
118261   **
118262   ** However, if the first docid copied to the output is a negative number,
118263   ** then the encoding of the first docid from the 'other' input list may
118264   ** be larger in the output than it was in the input (since the delta value
118265   ** may be a larger positive integer than the actual docid).
118266   **
118267   ** The space required to store the output is therefore the sum of the
118268   ** sizes of the two inputs, plus enough space for exactly one of the input
118269   ** docids to grow. 
118270   **
118271   ** A symetric argument may be made if the doclists are in descending 
118272   ** order.
118273   */
118274   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
118275   if( !aOut ) return SQLITE_NOMEM;
118276
118277   p = aOut;
118278   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118279   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118280   while( p1 || p2 ){
118281     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
118282
118283     if( p2 && p1 && iDiff==0 ){
118284       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118285       fts3PoslistMerge(&p, &p1, &p2);
118286       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118287       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118288     }else if( !p2 || (p1 && iDiff<0) ){
118289       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118290       fts3PoslistCopy(&p, &p1);
118291       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118292     }else{
118293       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
118294       fts3PoslistCopy(&p, &p2);
118295       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118296     }
118297   }
118298
118299   *paOut = aOut;
118300   *pnOut = (int)(p-aOut);
118301   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
118302   return SQLITE_OK;
118303 }
118304
118305 /*
118306 ** This function does a "phrase" merge of two doclists. In a phrase merge,
118307 ** the output contains a copy of each position from the right-hand input
118308 ** doclist for which there is a position in the left-hand input doclist
118309 ** exactly nDist tokens before it.
118310 **
118311 ** If the docids in the input doclists are sorted in ascending order,
118312 ** parameter bDescDoclist should be false. If they are sorted in ascending 
118313 ** order, it should be passed a non-zero value.
118314 **
118315 ** The right-hand input doclist is overwritten by this function.
118316 */
118317 static void fts3DoclistPhraseMerge(
118318   int bDescDoclist,               /* True if arguments are desc */
118319   int nDist,                      /* Distance from left to right (1=adjacent) */
118320   char *aLeft, int nLeft,         /* Left doclist */
118321   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
118322 ){
118323   sqlite3_int64 i1 = 0;
118324   sqlite3_int64 i2 = 0;
118325   sqlite3_int64 iPrev = 0;
118326   char *pEnd1 = &aLeft[nLeft];
118327   char *pEnd2 = &aRight[*pnRight];
118328   char *p1 = aLeft;
118329   char *p2 = aRight;
118330   char *p;
118331   int bFirstOut = 0;
118332   char *aOut = aRight;
118333
118334   assert( nDist>0 );
118335
118336   p = aOut;
118337   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118338   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118339
118340   while( p1 && p2 ){
118341     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
118342     if( iDiff==0 ){
118343       char *pSave = p;
118344       sqlite3_int64 iPrevSave = iPrev;
118345       int bFirstOutSave = bFirstOut;
118346
118347       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118348       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
118349         p = pSave;
118350         iPrev = iPrevSave;
118351         bFirstOut = bFirstOutSave;
118352       }
118353       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118354       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118355     }else if( iDiff<0 ){
118356       fts3PoslistCopy(0, &p1);
118357       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118358     }else{
118359       fts3PoslistCopy(0, &p2);
118360       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118361     }
118362   }
118363
118364   *pnRight = (int)(p - aOut);
118365 }
118366
118367 /*
118368 ** Argument pList points to a position list nList bytes in size. This
118369 ** function checks to see if the position list contains any entries for
118370 ** a token in position 0 (of any column). If so, it writes argument iDelta
118371 ** to the output buffer pOut, followed by a position list consisting only
118372 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
118373 ** The value returned is the number of bytes written to pOut (if any).
118374 */
118375 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
118376   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
118377   char *pList,                    /* Position list (no 0x00 term) */
118378   int nList,                      /* Size of pList in bytes */
118379   char *pOut                      /* Write output here */
118380 ){
118381   int nOut = 0;
118382   int bWritten = 0;               /* True once iDelta has been written */
118383   char *p = pList;
118384   char *pEnd = &pList[nList];
118385
118386   if( *p!=0x01 ){
118387     if( *p==0x02 ){
118388       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
118389       pOut[nOut++] = 0x02;
118390       bWritten = 1;
118391     }
118392     fts3ColumnlistCopy(0, &p);
118393   }
118394
118395   while( p<pEnd && *p==0x01 ){
118396     sqlite3_int64 iCol;
118397     p++;
118398     p += sqlite3Fts3GetVarint(p, &iCol);
118399     if( *p==0x02 ){
118400       if( bWritten==0 ){
118401         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
118402         bWritten = 1;
118403       }
118404       pOut[nOut++] = 0x01;
118405       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
118406       pOut[nOut++] = 0x02;
118407     }
118408     fts3ColumnlistCopy(0, &p);
118409   }
118410   if( bWritten ){
118411     pOut[nOut++] = 0x00;
118412   }
118413
118414   return nOut;
118415 }
118416
118417
118418 /*
118419 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
118420 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
118421 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
118422 **
118423 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
118424 ** the responsibility of the caller to free any doclists left in the
118425 ** TermSelect.aaOutput[] array.
118426 */
118427 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
118428   char *aOut = 0;
118429   int nOut = 0;
118430   int i;
118431
118432   /* Loop through the doclists in the aaOutput[] array. Merge them all
118433   ** into a single doclist.
118434   */
118435   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
118436     if( pTS->aaOutput[i] ){
118437       if( !aOut ){
118438         aOut = pTS->aaOutput[i];
118439         nOut = pTS->anOutput[i];
118440         pTS->aaOutput[i] = 0;
118441       }else{
118442         int nNew;
118443         char *aNew;
118444
118445         int rc = fts3DoclistOrMerge(p->bDescIdx, 
118446             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
118447         );
118448         if( rc!=SQLITE_OK ){
118449           sqlite3_free(aOut);
118450           return rc;
118451         }
118452
118453         sqlite3_free(pTS->aaOutput[i]);
118454         sqlite3_free(aOut);
118455         pTS->aaOutput[i] = 0;
118456         aOut = aNew;
118457         nOut = nNew;
118458       }
118459     }
118460   }
118461
118462   pTS->aaOutput[0] = aOut;
118463   pTS->anOutput[0] = nOut;
118464   return SQLITE_OK;
118465 }
118466
118467 /*
118468 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
118469 ** as the first argument. The merge is an "OR" merge (see function
118470 ** fts3DoclistOrMerge() for details).
118471 **
118472 ** This function is called with the doclist for each term that matches
118473 ** a queried prefix. It merges all these doclists into one, the doclist
118474 ** for the specified prefix. Since there can be a very large number of
118475 ** doclists to merge, the merging is done pair-wise using the TermSelect
118476 ** object.
118477 **
118478 ** This function returns SQLITE_OK if the merge is successful, or an
118479 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
118480 */
118481 static int fts3TermSelectMerge(
118482   Fts3Table *p,                   /* FTS table handle */
118483   TermSelect *pTS,                /* TermSelect object to merge into */
118484   char *aDoclist,                 /* Pointer to doclist */
118485   int nDoclist                    /* Size of aDoclist in bytes */
118486 ){
118487   if( pTS->aaOutput[0]==0 ){
118488     /* If this is the first term selected, copy the doclist to the output
118489     ** buffer using memcpy(). */
118490     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
118491     pTS->anOutput[0] = nDoclist;
118492     if( pTS->aaOutput[0] ){
118493       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
118494     }else{
118495       return SQLITE_NOMEM;
118496     }
118497   }else{
118498     char *aMerge = aDoclist;
118499     int nMerge = nDoclist;
118500     int iOut;
118501
118502     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
118503       if( pTS->aaOutput[iOut]==0 ){
118504         assert( iOut>0 );
118505         pTS->aaOutput[iOut] = aMerge;
118506         pTS->anOutput[iOut] = nMerge;
118507         break;
118508       }else{
118509         char *aNew;
118510         int nNew;
118511
118512         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
118513             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
118514         );
118515         if( rc!=SQLITE_OK ){
118516           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
118517           return rc;
118518         }
118519
118520         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
118521         sqlite3_free(pTS->aaOutput[iOut]);
118522         pTS->aaOutput[iOut] = 0;
118523   
118524         aMerge = aNew;
118525         nMerge = nNew;
118526         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
118527           pTS->aaOutput[iOut] = aMerge;
118528           pTS->anOutput[iOut] = nMerge;
118529         }
118530       }
118531     }
118532   }
118533   return SQLITE_OK;
118534 }
118535
118536 /*
118537 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
118538 */
118539 static int fts3SegReaderCursorAppend(
118540   Fts3MultiSegReader *pCsr, 
118541   Fts3SegReader *pNew
118542 ){
118543   if( (pCsr->nSegment%16)==0 ){
118544     Fts3SegReader **apNew;
118545     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
118546     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
118547     if( !apNew ){
118548       sqlite3Fts3SegReaderFree(pNew);
118549       return SQLITE_NOMEM;
118550     }
118551     pCsr->apSegment = apNew;
118552   }
118553   pCsr->apSegment[pCsr->nSegment++] = pNew;
118554   return SQLITE_OK;
118555 }
118556
118557 /*
118558 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
118559 ** 8th argument.
118560 **
118561 ** This function returns SQLITE_OK if successful, or an SQLite error code
118562 ** otherwise.
118563 */
118564 static int fts3SegReaderCursor(
118565   Fts3Table *p,                   /* FTS3 table handle */
118566   int iLangid,                    /* Language id */
118567   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118568   int iLevel,                     /* Level of segments to scan */
118569   const char *zTerm,              /* Term to query for */
118570   int nTerm,                      /* Size of zTerm in bytes */
118571   int isPrefix,                   /* True for a prefix search */
118572   int isScan,                     /* True to scan from zTerm to EOF */
118573   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
118574 ){
118575   int rc = SQLITE_OK;             /* Error code */
118576   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
118577   int rc2;                        /* Result of sqlite3_reset() */
118578
118579   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
118580   ** for the pending-terms. If this is a scan, then this call must be being
118581   ** made by an fts4aux module, not an FTS table. In this case calling
118582   ** Fts3SegReaderPending might segfault, as the data structures used by 
118583   ** fts4aux are not completely populated. So it's easiest to filter these
118584   ** calls out here.  */
118585   if( iLevel<0 && p->aIndex ){
118586     Fts3SegReader *pSeg = 0;
118587     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
118588     if( rc==SQLITE_OK && pSeg ){
118589       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118590     }
118591   }
118592
118593   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
118594     if( rc==SQLITE_OK ){
118595       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
118596     }
118597
118598     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
118599       Fts3SegReader *pSeg = 0;
118600
118601       /* Read the values returned by the SELECT into local variables. */
118602       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
118603       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
118604       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
118605       int nRoot = sqlite3_column_bytes(pStmt, 4);
118606       char const *zRoot = sqlite3_column_blob(pStmt, 4);
118607
118608       /* If zTerm is not NULL, and this segment is not stored entirely on its
118609       ** root node, the range of leaves scanned can be reduced. Do this. */
118610       if( iStartBlock && zTerm ){
118611         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
118612         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
118613         if( rc!=SQLITE_OK ) goto finished;
118614         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
118615       }
118616  
118617       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
118618           (isPrefix==0 && isScan==0),
118619           iStartBlock, iLeavesEndBlock, 
118620           iEndBlock, zRoot, nRoot, &pSeg
118621       );
118622       if( rc!=SQLITE_OK ) goto finished;
118623       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118624     }
118625   }
118626
118627  finished:
118628   rc2 = sqlite3_reset(pStmt);
118629   if( rc==SQLITE_DONE ) rc = rc2;
118630
118631   return rc;
118632 }
118633
118634 /*
118635 ** Set up a cursor object for iterating through a full-text index or a 
118636 ** single level therein.
118637 */
118638 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
118639   Fts3Table *p,                   /* FTS3 table handle */
118640   int iLangid,                    /* Language-id to search */
118641   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118642   int iLevel,                     /* Level of segments to scan */
118643   const char *zTerm,              /* Term to query for */
118644   int nTerm,                      /* Size of zTerm in bytes */
118645   int isPrefix,                   /* True for a prefix search */
118646   int isScan,                     /* True to scan from zTerm to EOF */
118647   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
118648 ){
118649   assert( iIndex>=0 && iIndex<p->nIndex );
118650   assert( iLevel==FTS3_SEGCURSOR_ALL
118651       ||  iLevel==FTS3_SEGCURSOR_PENDING 
118652       ||  iLevel>=0
118653   );
118654   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
118655   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
118656   assert( isPrefix==0 || isScan==0 );
118657
118658   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
118659   return fts3SegReaderCursor(
118660       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
118661   );
118662 }
118663
118664 /*
118665 ** In addition to its current configuration, have the Fts3MultiSegReader
118666 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
118667 **
118668 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
118669 */
118670 static int fts3SegReaderCursorAddZero(
118671   Fts3Table *p,                   /* FTS virtual table handle */
118672   int iLangid,
118673   const char *zTerm,              /* Term to scan doclist of */
118674   int nTerm,                      /* Number of bytes in zTerm */
118675   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
118676 ){
118677   return fts3SegReaderCursor(p, 
118678       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
118679   );
118680 }
118681
118682 /*
118683 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
118684 ** if isPrefix is true, to scan the doclist for all terms for which 
118685 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
118686 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
118687 ** an SQLite error code.
118688 **
118689 ** It is the responsibility of the caller to free this object by eventually
118690 ** passing it to fts3SegReaderCursorFree() 
118691 **
118692 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
118693 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
118694 */
118695 static int fts3TermSegReaderCursor(
118696   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
118697   const char *zTerm,              /* Term to query for */
118698   int nTerm,                      /* Size of zTerm in bytes */
118699   int isPrefix,                   /* True for a prefix search */
118700   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
118701 ){
118702   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
118703   int rc = SQLITE_NOMEM;          /* Return code */
118704
118705   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
118706   if( pSegcsr ){
118707     int i;
118708     int bFound = 0;               /* True once an index has been found */
118709     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118710
118711     if( isPrefix ){
118712       for(i=1; bFound==0 && i<p->nIndex; i++){
118713         if( p->aIndex[i].nPrefix==nTerm ){
118714           bFound = 1;
118715           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
118716               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
118717           );
118718           pSegcsr->bLookup = 1;
118719         }
118720       }
118721
118722       for(i=1; bFound==0 && i<p->nIndex; i++){
118723         if( p->aIndex[i].nPrefix==nTerm+1 ){
118724           bFound = 1;
118725           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
118726               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
118727           );
118728           if( rc==SQLITE_OK ){
118729             rc = fts3SegReaderCursorAddZero(
118730                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
118731             );
118732           }
118733         }
118734       }
118735     }
118736
118737     if( bFound==0 ){
118738       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
118739           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
118740       );
118741       pSegcsr->bLookup = !isPrefix;
118742     }
118743   }
118744
118745   *ppSegcsr = pSegcsr;
118746   return rc;
118747 }
118748
118749 /*
118750 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
118751 */
118752 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
118753   sqlite3Fts3SegReaderFinish(pSegcsr);
118754   sqlite3_free(pSegcsr);
118755 }
118756
118757 /*
118758 ** This function retreives the doclist for the specified term (or term
118759 ** prefix) from the database.
118760 */
118761 static int fts3TermSelect(
118762   Fts3Table *p,                   /* Virtual table handle */
118763   Fts3PhraseToken *pTok,          /* Token to query for */
118764   int iColumn,                    /* Column to query (or -ve for all columns) */
118765   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
118766   char **ppOut                    /* OUT: Malloced result buffer */
118767 ){
118768   int rc;                         /* Return code */
118769   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
118770   TermSelect tsc;                 /* Object for pair-wise doclist merging */
118771   Fts3SegFilter filter;           /* Segment term filter configuration */
118772
118773   pSegcsr = pTok->pSegcsr;
118774   memset(&tsc, 0, sizeof(TermSelect));
118775
118776   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
118777         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
118778         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
118779         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
118780   filter.iCol = iColumn;
118781   filter.zTerm = pTok->z;
118782   filter.nTerm = pTok->n;
118783
118784   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
118785   while( SQLITE_OK==rc
118786       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
118787   ){
118788     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
118789   }
118790
118791   if( rc==SQLITE_OK ){
118792     rc = fts3TermSelectFinishMerge(p, &tsc);
118793   }
118794   if( rc==SQLITE_OK ){
118795     *ppOut = tsc.aaOutput[0];
118796     *pnOut = tsc.anOutput[0];
118797   }else{
118798     int i;
118799     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
118800       sqlite3_free(tsc.aaOutput[i]);
118801     }
118802   }
118803
118804   fts3SegReaderCursorFree(pSegcsr);
118805   pTok->pSegcsr = 0;
118806   return rc;
118807 }
118808
118809 /*
118810 ** This function counts the total number of docids in the doclist stored
118811 ** in buffer aList[], size nList bytes.
118812 **
118813 ** If the isPoslist argument is true, then it is assumed that the doclist
118814 ** contains a position-list following each docid. Otherwise, it is assumed
118815 ** that the doclist is simply a list of docids stored as delta encoded 
118816 ** varints.
118817 */
118818 static int fts3DoclistCountDocids(char *aList, int nList){
118819   int nDoc = 0;                   /* Return value */
118820   if( aList ){
118821     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
118822     char *p = aList;              /* Cursor */
118823     while( p<aEnd ){
118824       nDoc++;
118825       while( (*p++)&0x80 );     /* Skip docid varint */
118826       fts3PoslistCopy(0, &p);   /* Skip over position list */
118827     }
118828   }
118829
118830   return nDoc;
118831 }
118832
118833 /*
118834 ** Advance the cursor to the next row in the %_content table that
118835 ** matches the search criteria.  For a MATCH search, this will be
118836 ** the next row that matches. For a full-table scan, this will be
118837 ** simply the next row in the %_content table.  For a docid lookup,
118838 ** this routine simply sets the EOF flag.
118839 **
118840 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
118841 ** even if we reach end-of-file.  The fts3EofMethod() will be called
118842 ** subsequently to determine whether or not an EOF was hit.
118843 */
118844 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
118845   int rc;
118846   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118847   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
118848     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
118849       pCsr->isEof = 1;
118850       rc = sqlite3_reset(pCsr->pStmt);
118851     }else{
118852       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
118853       rc = SQLITE_OK;
118854     }
118855   }else{
118856     rc = fts3EvalNext((Fts3Cursor *)pCursor);
118857   }
118858   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118859   return rc;
118860 }
118861
118862 /*
118863 ** This is the xFilter interface for the virtual table.  See
118864 ** the virtual table xFilter method documentation for additional
118865 ** information.
118866 **
118867 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
118868 ** the %_content table.
118869 **
118870 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
118871 ** in the %_content table.
118872 **
118873 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
118874 ** column on the left-hand side of the MATCH operator is column
118875 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
118876 ** side of the MATCH operator.
118877 */
118878 static int fts3FilterMethod(
118879   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
118880   int idxNum,                     /* Strategy index */
118881   const char *idxStr,             /* Unused */
118882   int nVal,                       /* Number of elements in apVal */
118883   sqlite3_value **apVal           /* Arguments for the indexing scheme */
118884 ){
118885   int rc;
118886   char *zSql;                     /* SQL statement used to access %_content */
118887   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
118888   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118889
118890   UNUSED_PARAMETER(idxStr);
118891   UNUSED_PARAMETER(nVal);
118892
118893   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
118894   assert( nVal==0 || nVal==1 || nVal==2 );
118895   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
118896   assert( p->pSegments==0 );
118897
118898   /* In case the cursor has been used before, clear it now. */
118899   sqlite3_finalize(pCsr->pStmt);
118900   sqlite3_free(pCsr->aDoclist);
118901   sqlite3Fts3ExprFree(pCsr->pExpr);
118902   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
118903
118904   if( idxStr ){
118905     pCsr->bDesc = (idxStr[0]=='D');
118906   }else{
118907     pCsr->bDesc = p->bDescIdx;
118908   }
118909   pCsr->eSearch = (i16)idxNum;
118910
118911   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
118912     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
118913     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
118914
118915     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
118916       return SQLITE_NOMEM;
118917     }
118918
118919     pCsr->iLangid = 0;
118920     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
118921
118922     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
118923         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
118924     );
118925     if( rc!=SQLITE_OK ){
118926       if( rc==SQLITE_ERROR ){
118927         static const char *zErr = "malformed MATCH expression: [%s]";
118928         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
118929       }
118930       return rc;
118931     }
118932
118933     rc = sqlite3Fts3ReadLock(p);
118934     if( rc!=SQLITE_OK ) return rc;
118935
118936     rc = fts3EvalStart(pCsr);
118937
118938     sqlite3Fts3SegmentsClose(p);
118939     if( rc!=SQLITE_OK ) return rc;
118940     pCsr->pNextId = pCsr->aDoclist;
118941     pCsr->iPrevId = 0;
118942   }
118943
118944   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
118945   ** statement loops through all rows of the %_content table. For a
118946   ** full-text query or docid lookup, the statement retrieves a single
118947   ** row by docid.
118948   */
118949   if( idxNum==FTS3_FULLSCAN_SEARCH ){
118950     zSql = sqlite3_mprintf(
118951         "SELECT %s ORDER BY rowid %s",
118952         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
118953     );
118954     if( zSql ){
118955       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
118956       sqlite3_free(zSql);
118957     }else{
118958       rc = SQLITE_NOMEM;
118959     }
118960   }else if( idxNum==FTS3_DOCID_SEARCH ){
118961     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
118962     if( rc==SQLITE_OK ){
118963       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
118964     }
118965   }
118966   if( rc!=SQLITE_OK ) return rc;
118967
118968   return fts3NextMethod(pCursor);
118969 }
118970
118971 /* 
118972 ** This is the xEof method of the virtual table. SQLite calls this 
118973 ** routine to find out if it has reached the end of a result set.
118974 */
118975 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
118976   return ((Fts3Cursor *)pCursor)->isEof;
118977 }
118978
118979 /* 
118980 ** This is the xRowid method. The SQLite core calls this routine to
118981 ** retrieve the rowid for the current row of the result set. fts3
118982 ** exposes %_content.docid as the rowid for the virtual table. The
118983 ** rowid should be written to *pRowid.
118984 */
118985 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
118986   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
118987   *pRowid = pCsr->iPrevId;
118988   return SQLITE_OK;
118989 }
118990
118991 /* 
118992 ** This is the xColumn method, called by SQLite to request a value from
118993 ** the row that the supplied cursor currently points to.
118994 **
118995 ** If:
118996 **
118997 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
118998 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
118999 **   (iCol == p->nColumn+1) -> Docid column
119000 **   (iCol == p->nColumn+2) -> Langid column
119001 */
119002 static int fts3ColumnMethod(
119003   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119004   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
119005   int iCol                        /* Index of column to read value from */
119006 ){
119007   int rc = SQLITE_OK;             /* Return Code */
119008   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119009   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119010
119011   /* The column value supplied by SQLite must be in range. */
119012   assert( iCol>=0 && iCol<=p->nColumn+2 );
119013
119014   if( iCol==p->nColumn+1 ){
119015     /* This call is a request for the "docid" column. Since "docid" is an 
119016     ** alias for "rowid", use the xRowid() method to obtain the value.
119017     */
119018     sqlite3_result_int64(pCtx, pCsr->iPrevId);
119019   }else if( iCol==p->nColumn ){
119020     /* The extra column whose name is the same as the table.
119021     ** Return a blob which is a pointer to the cursor.  */
119022     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
119023   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
119024     sqlite3_result_int64(pCtx, pCsr->iLangid);
119025   }else{
119026     /* The requested column is either a user column (one that contains 
119027     ** indexed data), or the language-id column.  */
119028     rc = fts3CursorSeek(0, pCsr);
119029
119030     if( rc==SQLITE_OK ){
119031       if( iCol==p->nColumn+2 ){
119032         int iLangid = 0;
119033         if( p->zLanguageid ){
119034           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
119035         }
119036         sqlite3_result_int(pCtx, iLangid);
119037       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
119038         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
119039       }
119040     }
119041   }
119042
119043   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119044   return rc;
119045 }
119046
119047 /* 
119048 ** This function is the implementation of the xUpdate callback used by 
119049 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
119050 ** inserted, updated or deleted.
119051 */
119052 static int fts3UpdateMethod(
119053   sqlite3_vtab *pVtab,            /* Virtual table handle */
119054   int nArg,                       /* Size of argument array */
119055   sqlite3_value **apVal,          /* Array of arguments */
119056   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
119057 ){
119058   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
119059 }
119060
119061 /*
119062 ** Implementation of xSync() method. Flush the contents of the pending-terms
119063 ** hash-table to the database.
119064 */
119065 static int fts3SyncMethod(sqlite3_vtab *pVtab){
119066
119067   /* Following an incremental-merge operation, assuming that the input
119068   ** segments are not completely consumed (the usual case), they are updated
119069   ** in place to remove the entries that have already been merged. This
119070   ** involves updating the leaf block that contains the smallest unmerged
119071   ** entry and each block (if any) between the leaf and the root node. So
119072   ** if the height of the input segment b-trees is N, and input segments
119073   ** are merged eight at a time, updating the input segments at the end
119074   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
119075   ** small - often between 0 and 2. So the overhead of the incremental
119076   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
119077   ** dwarfing the actual productive work accomplished, the incremental merge
119078   ** is only attempted if it will write at least 64 leaf blocks. Hence
119079   ** nMinMerge.
119080   **
119081   ** Of course, updating the input segments also involves deleting a bunch
119082   ** of blocks from the segments table. But this is not considered overhead
119083   ** as it would also be required by a crisis-merge that used the same input 
119084   ** segments.
119085   */
119086   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
119087
119088   Fts3Table *p = (Fts3Table*)pVtab;
119089   int rc = sqlite3Fts3PendingTermsFlush(p);
119090
119091   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
119092     int mxLevel = 0;              /* Maximum relative level value in db */
119093     int A;                        /* Incr-merge parameter A */
119094
119095     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
119096     assert( rc==SQLITE_OK || mxLevel==0 );
119097     A = p->nLeafAdd * mxLevel;
119098     A += (A/2);
119099     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
119100   }
119101   sqlite3Fts3SegmentsClose(p);
119102   return rc;
119103 }
119104
119105 /*
119106 ** Implementation of xBegin() method. This is a no-op.
119107 */
119108 static int fts3BeginMethod(sqlite3_vtab *pVtab){
119109   Fts3Table *p = (Fts3Table*)pVtab;
119110   UNUSED_PARAMETER(pVtab);
119111   assert( p->pSegments==0 );
119112   assert( p->nPendingData==0 );
119113   assert( p->inTransaction!=1 );
119114   TESTONLY( p->inTransaction = 1 );
119115   TESTONLY( p->mxSavepoint = -1; );
119116   p->nLeafAdd = 0;
119117   return SQLITE_OK;
119118 }
119119
119120 /*
119121 ** Implementation of xCommit() method. This is a no-op. The contents of
119122 ** the pending-terms hash-table have already been flushed into the database
119123 ** by fts3SyncMethod().
119124 */
119125 static int fts3CommitMethod(sqlite3_vtab *pVtab){
119126   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119127   UNUSED_PARAMETER(pVtab);
119128   assert( p->nPendingData==0 );
119129   assert( p->inTransaction!=0 );
119130   assert( p->pSegments==0 );
119131   TESTONLY( p->inTransaction = 0 );
119132   TESTONLY( p->mxSavepoint = -1; );
119133   return SQLITE_OK;
119134 }
119135
119136 /*
119137 ** Implementation of xRollback(). Discard the contents of the pending-terms
119138 ** hash-table. Any changes made to the database are reverted by SQLite.
119139 */
119140 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
119141   Fts3Table *p = (Fts3Table*)pVtab;
119142   sqlite3Fts3PendingTermsClear(p);
119143   assert( p->inTransaction!=0 );
119144   TESTONLY( p->inTransaction = 0 );
119145   TESTONLY( p->mxSavepoint = -1; );
119146   return SQLITE_OK;
119147 }
119148
119149 /*
119150 ** When called, *ppPoslist must point to the byte immediately following the
119151 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
119152 ** moves *ppPoslist so that it instead points to the first byte of the
119153 ** same position list.
119154 */
119155 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
119156   char *p = &(*ppPoslist)[-2];
119157   char c = 0;
119158
119159   while( p>pStart && (c=*p--)==0 );
119160   while( p>pStart && (*p & 0x80) | c ){ 
119161     c = *p--; 
119162   }
119163   if( p>pStart ){ p = &p[2]; }
119164   while( *p++&0x80 );
119165   *ppPoslist = p;
119166 }
119167
119168 /*
119169 ** Helper function used by the implementation of the overloaded snippet(),
119170 ** offsets() and optimize() SQL functions.
119171 **
119172 ** If the value passed as the third argument is a blob of size
119173 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
119174 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
119175 ** message is written to context pContext and SQLITE_ERROR returned. The
119176 ** string passed via zFunc is used as part of the error message.
119177 */
119178 static int fts3FunctionArg(
119179   sqlite3_context *pContext,      /* SQL function call context */
119180   const char *zFunc,              /* Function name */
119181   sqlite3_value *pVal,            /* argv[0] passed to function */
119182   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
119183 ){
119184   Fts3Cursor *pRet;
119185   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
119186    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
119187   ){
119188     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
119189     sqlite3_result_error(pContext, zErr, -1);
119190     sqlite3_free(zErr);
119191     return SQLITE_ERROR;
119192   }
119193   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
119194   *ppCsr = pRet;
119195   return SQLITE_OK;
119196 }
119197
119198 /*
119199 ** Implementation of the snippet() function for FTS3
119200 */
119201 static void fts3SnippetFunc(
119202   sqlite3_context *pContext,      /* SQLite function call context */
119203   int nVal,                       /* Size of apVal[] array */
119204   sqlite3_value **apVal           /* Array of arguments */
119205 ){
119206   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119207   const char *zStart = "<b>";
119208   const char *zEnd = "</b>";
119209   const char *zEllipsis = "<b>...</b>";
119210   int iCol = -1;
119211   int nToken = 15;                /* Default number of tokens in snippet */
119212
119213   /* There must be at least one argument passed to this function (otherwise
119214   ** the non-overloaded version would have been called instead of this one).
119215   */
119216   assert( nVal>=1 );
119217
119218   if( nVal>6 ){
119219     sqlite3_result_error(pContext, 
119220         "wrong number of arguments to function snippet()", -1);
119221     return;
119222   }
119223   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
119224
119225   switch( nVal ){
119226     case 6: nToken = sqlite3_value_int(apVal[5]);
119227     case 5: iCol = sqlite3_value_int(apVal[4]);
119228     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
119229     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
119230     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
119231   }
119232   if( !zEllipsis || !zEnd || !zStart ){
119233     sqlite3_result_error_nomem(pContext);
119234   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119235     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
119236   }
119237 }
119238
119239 /*
119240 ** Implementation of the offsets() function for FTS3
119241 */
119242 static void fts3OffsetsFunc(
119243   sqlite3_context *pContext,      /* SQLite function call context */
119244   int nVal,                       /* Size of argument array */
119245   sqlite3_value **apVal           /* Array of arguments */
119246 ){
119247   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119248
119249   UNUSED_PARAMETER(nVal);
119250
119251   assert( nVal==1 );
119252   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
119253   assert( pCsr );
119254   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119255     sqlite3Fts3Offsets(pContext, pCsr);
119256   }
119257 }
119258
119259 /* 
119260 ** Implementation of the special optimize() function for FTS3. This 
119261 ** function merges all segments in the database to a single segment.
119262 ** Example usage is:
119263 **
119264 **   SELECT optimize(t) FROM t LIMIT 1;
119265 **
119266 ** where 't' is the name of an FTS3 table.
119267 */
119268 static void fts3OptimizeFunc(
119269   sqlite3_context *pContext,      /* SQLite function call context */
119270   int nVal,                       /* Size of argument array */
119271   sqlite3_value **apVal           /* Array of arguments */
119272 ){
119273   int rc;                         /* Return code */
119274   Fts3Table *p;                   /* Virtual table handle */
119275   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
119276
119277   UNUSED_PARAMETER(nVal);
119278
119279   assert( nVal==1 );
119280   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
119281   p = (Fts3Table *)pCursor->base.pVtab;
119282   assert( p );
119283
119284   rc = sqlite3Fts3Optimize(p);
119285
119286   switch( rc ){
119287     case SQLITE_OK:
119288       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
119289       break;
119290     case SQLITE_DONE:
119291       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
119292       break;
119293     default:
119294       sqlite3_result_error_code(pContext, rc);
119295       break;
119296   }
119297 }
119298
119299 /*
119300 ** Implementation of the matchinfo() function for FTS3
119301 */
119302 static void fts3MatchinfoFunc(
119303   sqlite3_context *pContext,      /* SQLite function call context */
119304   int nVal,                       /* Size of argument array */
119305   sqlite3_value **apVal           /* Array of arguments */
119306 ){
119307   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119308   assert( nVal==1 || nVal==2 );
119309   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
119310     const char *zArg = 0;
119311     if( nVal>1 ){
119312       zArg = (const char *)sqlite3_value_text(apVal[1]);
119313     }
119314     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
119315   }
119316 }
119317
119318 /*
119319 ** This routine implements the xFindFunction method for the FTS3
119320 ** virtual table.
119321 */
119322 static int fts3FindFunctionMethod(
119323   sqlite3_vtab *pVtab,            /* Virtual table handle */
119324   int nArg,                       /* Number of SQL function arguments */
119325   const char *zName,              /* Name of SQL function */
119326   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
119327   void **ppArg                    /* Unused */
119328 ){
119329   struct Overloaded {
119330     const char *zName;
119331     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
119332   } aOverload[] = {
119333     { "snippet", fts3SnippetFunc },
119334     { "offsets", fts3OffsetsFunc },
119335     { "optimize", fts3OptimizeFunc },
119336     { "matchinfo", fts3MatchinfoFunc },
119337   };
119338   int i;                          /* Iterator variable */
119339
119340   UNUSED_PARAMETER(pVtab);
119341   UNUSED_PARAMETER(nArg);
119342   UNUSED_PARAMETER(ppArg);
119343
119344   for(i=0; i<SizeofArray(aOverload); i++){
119345     if( strcmp(zName, aOverload[i].zName)==0 ){
119346       *pxFunc = aOverload[i].xFunc;
119347       return 1;
119348     }
119349   }
119350
119351   /* No function of the specified name was found. Return 0. */
119352   return 0;
119353 }
119354
119355 /*
119356 ** Implementation of FTS3 xRename method. Rename an fts3 table.
119357 */
119358 static int fts3RenameMethod(
119359   sqlite3_vtab *pVtab,            /* Virtual table handle */
119360   const char *zName               /* New name of table */
119361 ){
119362   Fts3Table *p = (Fts3Table *)pVtab;
119363   sqlite3 *db = p->db;            /* Database connection */
119364   int rc;                         /* Return Code */
119365
119366   /* As it happens, the pending terms table is always empty here. This is
119367   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
119368   ** always opens a savepoint transaction. And the xSavepoint() method 
119369   ** flushes the pending terms table. But leave the (no-op) call to
119370   ** PendingTermsFlush() in in case that changes.
119371   */
119372   assert( p->nPendingData==0 );
119373   rc = sqlite3Fts3PendingTermsFlush(p);
119374
119375   if( p->zContentTbl==0 ){
119376     fts3DbExec(&rc, db,
119377       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
119378       p->zDb, p->zName, zName
119379     );
119380   }
119381
119382   if( p->bHasDocsize ){
119383     fts3DbExec(&rc, db,
119384       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
119385       p->zDb, p->zName, zName
119386     );
119387   }
119388   if( p->bHasStat ){
119389     fts3DbExec(&rc, db,
119390       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
119391       p->zDb, p->zName, zName
119392     );
119393   }
119394   fts3DbExec(&rc, db,
119395     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
119396     p->zDb, p->zName, zName
119397   );
119398   fts3DbExec(&rc, db,
119399     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
119400     p->zDb, p->zName, zName
119401   );
119402   return rc;
119403 }
119404
119405 /*
119406 ** The xSavepoint() method.
119407 **
119408 ** Flush the contents of the pending-terms table to disk.
119409 */
119410 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
119411   int rc = SQLITE_OK;
119412   UNUSED_PARAMETER(iSavepoint);
119413   assert( ((Fts3Table *)pVtab)->inTransaction );
119414   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
119415   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
119416   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
119417     rc = fts3SyncMethod(pVtab);
119418   }
119419   return rc;
119420 }
119421
119422 /*
119423 ** The xRelease() method.
119424 **
119425 ** This is a no-op.
119426 */
119427 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
119428   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119429   UNUSED_PARAMETER(iSavepoint);
119430   UNUSED_PARAMETER(pVtab);
119431   assert( p->inTransaction );
119432   assert( p->mxSavepoint >= iSavepoint );
119433   TESTONLY( p->mxSavepoint = iSavepoint-1 );
119434   return SQLITE_OK;
119435 }
119436
119437 /*
119438 ** The xRollbackTo() method.
119439 **
119440 ** Discard the contents of the pending terms table.
119441 */
119442 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
119443   Fts3Table *p = (Fts3Table*)pVtab;
119444   UNUSED_PARAMETER(iSavepoint);
119445   assert( p->inTransaction );
119446   assert( p->mxSavepoint >= iSavepoint );
119447   TESTONLY( p->mxSavepoint = iSavepoint );
119448   sqlite3Fts3PendingTermsClear(p);
119449   return SQLITE_OK;
119450 }
119451
119452 static const sqlite3_module fts3Module = {
119453   /* iVersion      */ 2,
119454   /* xCreate       */ fts3CreateMethod,
119455   /* xConnect      */ fts3ConnectMethod,
119456   /* xBestIndex    */ fts3BestIndexMethod,
119457   /* xDisconnect   */ fts3DisconnectMethod,
119458   /* xDestroy      */ fts3DestroyMethod,
119459   /* xOpen         */ fts3OpenMethod,
119460   /* xClose        */ fts3CloseMethod,
119461   /* xFilter       */ fts3FilterMethod,
119462   /* xNext         */ fts3NextMethod,
119463   /* xEof          */ fts3EofMethod,
119464   /* xColumn       */ fts3ColumnMethod,
119465   /* xRowid        */ fts3RowidMethod,
119466   /* xUpdate       */ fts3UpdateMethod,
119467   /* xBegin        */ fts3BeginMethod,
119468   /* xSync         */ fts3SyncMethod,
119469   /* xCommit       */ fts3CommitMethod,
119470   /* xRollback     */ fts3RollbackMethod,
119471   /* xFindFunction */ fts3FindFunctionMethod,
119472   /* xRename */       fts3RenameMethod,
119473   /* xSavepoint    */ fts3SavepointMethod,
119474   /* xRelease      */ fts3ReleaseMethod,
119475   /* xRollbackTo   */ fts3RollbackToMethod,
119476 };
119477
119478 /*
119479 ** This function is registered as the module destructor (called when an
119480 ** FTS3 enabled database connection is closed). It frees the memory
119481 ** allocated for the tokenizer hash table.
119482 */
119483 static void hashDestroy(void *p){
119484   Fts3Hash *pHash = (Fts3Hash *)p;
119485   sqlite3Fts3HashClear(pHash);
119486   sqlite3_free(pHash);
119487 }
119488
119489 /*
119490 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
119491 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
119492 ** respectively. The following three forward declarations are for functions
119493 ** declared in these files used to retrieve the respective implementations.
119494 **
119495 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
119496 ** to by the argument to point to the "simple" tokenizer implementation.
119497 ** And so on.
119498 */
119499 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119500 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119501 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
119502 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
119503 #endif
119504 #ifdef SQLITE_ENABLE_ICU
119505 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119506 #endif
119507
119508 /*
119509 ** Initialise the fts3 extension. If this extension is built as part
119510 ** of the sqlite library, then this function is called directly by
119511 ** SQLite. If fts3 is built as a dynamically loadable extension, this
119512 ** function is called by the sqlite3_extension_init() entry point.
119513 */
119514 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
119515   int rc = SQLITE_OK;
119516   Fts3Hash *pHash = 0;
119517   const sqlite3_tokenizer_module *pSimple = 0;
119518   const sqlite3_tokenizer_module *pPorter = 0;
119519 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
119520   const sqlite3_tokenizer_module *pUnicode = 0;
119521 #endif
119522
119523 #ifdef SQLITE_ENABLE_ICU
119524   const sqlite3_tokenizer_module *pIcu = 0;
119525   sqlite3Fts3IcuTokenizerModule(&pIcu);
119526 #endif
119527
119528 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
119529   sqlite3Fts3UnicodeTokenizer(&pUnicode);
119530 #endif
119531
119532 #ifdef SQLITE_TEST
119533   rc = sqlite3Fts3InitTerm(db);
119534   if( rc!=SQLITE_OK ) return rc;
119535 #endif
119536
119537   rc = sqlite3Fts3InitAux(db);
119538   if( rc!=SQLITE_OK ) return rc;
119539
119540   sqlite3Fts3SimpleTokenizerModule(&pSimple);
119541   sqlite3Fts3PorterTokenizerModule(&pPorter);
119542
119543   /* Allocate and initialise the hash-table used to store tokenizers. */
119544   pHash = sqlite3_malloc(sizeof(Fts3Hash));
119545   if( !pHash ){
119546     rc = SQLITE_NOMEM;
119547   }else{
119548     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119549   }
119550
119551   /* Load the built-in tokenizers into the hash table */
119552   if( rc==SQLITE_OK ){
119553     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
119554      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
119555
119556 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
119557      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
119558 #endif
119559 #ifdef SQLITE_ENABLE_ICU
119560      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
119561 #endif
119562     ){
119563       rc = SQLITE_NOMEM;
119564     }
119565   }
119566
119567 #ifdef SQLITE_TEST
119568   if( rc==SQLITE_OK ){
119569     rc = sqlite3Fts3ExprInitTestInterface(db);
119570   }
119571 #endif
119572
119573   /* Create the virtual table wrapper around the hash-table and overload 
119574   ** the two scalar functions. If this is successful, register the
119575   ** module with sqlite.
119576   */
119577   if( SQLITE_OK==rc 
119578    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
119579    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
119580    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
119581    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
119582    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
119583    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
119584   ){
119585     rc = sqlite3_create_module_v2(
119586         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
119587     );
119588     if( rc==SQLITE_OK ){
119589       rc = sqlite3_create_module_v2(
119590           db, "fts4", &fts3Module, (void *)pHash, 0
119591       );
119592     }
119593     return rc;
119594   }
119595
119596   /* An error has occurred. Delete the hash table and return the error code. */
119597   assert( rc!=SQLITE_OK );
119598   if( pHash ){
119599     sqlite3Fts3HashClear(pHash);
119600     sqlite3_free(pHash);
119601   }
119602   return rc;
119603 }
119604
119605 /*
119606 ** Allocate an Fts3MultiSegReader for each token in the expression headed
119607 ** by pExpr. 
119608 **
119609 ** An Fts3SegReader object is a cursor that can seek or scan a range of
119610 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
119611 ** Fts3SegReader objects internally to provide an interface to seek or scan
119612 ** within the union of all segments of a b-tree. Hence the name.
119613 **
119614 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
119615 ** segment b-tree (if the term is not a prefix or it is a prefix for which
119616 ** there exists prefix b-tree of the right length) then it may be traversed
119617 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
119618 ** doclist and then traversed.
119619 */
119620 static void fts3EvalAllocateReaders(
119621   Fts3Cursor *pCsr,               /* FTS cursor handle */
119622   Fts3Expr *pExpr,                /* Allocate readers for this expression */
119623   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
119624   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
119625   int *pRc                        /* IN/OUT: Error code */
119626 ){
119627   if( pExpr && SQLITE_OK==*pRc ){
119628     if( pExpr->eType==FTSQUERY_PHRASE ){
119629       int i;
119630       int nToken = pExpr->pPhrase->nToken;
119631       *pnToken += nToken;
119632       for(i=0; i<nToken; i++){
119633         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
119634         int rc = fts3TermSegReaderCursor(pCsr, 
119635             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
119636         );
119637         if( rc!=SQLITE_OK ){
119638           *pRc = rc;
119639           return;
119640         }
119641       }
119642       assert( pExpr->pPhrase->iDoclistToken==0 );
119643       pExpr->pPhrase->iDoclistToken = -1;
119644     }else{
119645       *pnOr += (pExpr->eType==FTSQUERY_OR);
119646       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
119647       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
119648     }
119649   }
119650 }
119651
119652 /*
119653 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
119654 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
119655 **
119656 ** This function assumes that pList points to a buffer allocated using
119657 ** sqlite3_malloc(). This function takes responsibility for eventually
119658 ** freeing the buffer.
119659 */
119660 static void fts3EvalPhraseMergeToken(
119661   Fts3Table *pTab,                /* FTS Table pointer */
119662   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
119663   int iToken,                     /* Token pList/nList corresponds to */
119664   char *pList,                    /* Pointer to doclist */
119665   int nList                       /* Number of bytes in pList */
119666 ){
119667   assert( iToken!=p->iDoclistToken );
119668
119669   if( pList==0 ){
119670     sqlite3_free(p->doclist.aAll);
119671     p->doclist.aAll = 0;
119672     p->doclist.nAll = 0;
119673   }
119674
119675   else if( p->iDoclistToken<0 ){
119676     p->doclist.aAll = pList;
119677     p->doclist.nAll = nList;
119678   }
119679
119680   else if( p->doclist.aAll==0 ){
119681     sqlite3_free(pList);
119682   }
119683
119684   else {
119685     char *pLeft;
119686     char *pRight;
119687     int nLeft;
119688     int nRight;
119689     int nDiff;
119690
119691     if( p->iDoclistToken<iToken ){
119692       pLeft = p->doclist.aAll;
119693       nLeft = p->doclist.nAll;
119694       pRight = pList;
119695       nRight = nList;
119696       nDiff = iToken - p->iDoclistToken;
119697     }else{
119698       pRight = p->doclist.aAll;
119699       nRight = p->doclist.nAll;
119700       pLeft = pList;
119701       nLeft = nList;
119702       nDiff = p->iDoclistToken - iToken;
119703     }
119704
119705     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
119706     sqlite3_free(pLeft);
119707     p->doclist.aAll = pRight;
119708     p->doclist.nAll = nRight;
119709   }
119710
119711   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
119712 }
119713
119714 /*
119715 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
119716 ** does not take deferred tokens into account.
119717 **
119718 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119719 */
119720 static int fts3EvalPhraseLoad(
119721   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119722   Fts3Phrase *p                   /* Phrase object */
119723 ){
119724   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119725   int iToken;
119726   int rc = SQLITE_OK;
119727
119728   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
119729     Fts3PhraseToken *pToken = &p->aToken[iToken];
119730     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
119731
119732     if( pToken->pSegcsr ){
119733       int nThis = 0;
119734       char *pThis = 0;
119735       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
119736       if( rc==SQLITE_OK ){
119737         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
119738       }
119739     }
119740     assert( pToken->pSegcsr==0 );
119741   }
119742
119743   return rc;
119744 }
119745
119746 /*
119747 ** This function is called on each phrase after the position lists for
119748 ** any deferred tokens have been loaded into memory. It updates the phrases
119749 ** current position list to include only those positions that are really
119750 ** instances of the phrase (after considering deferred tokens). If this
119751 ** means that the phrase does not appear in the current row, doclist.pList
119752 ** and doclist.nList are both zeroed.
119753 **
119754 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119755 */
119756 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
119757   int iToken;                     /* Used to iterate through phrase tokens */
119758   char *aPoslist = 0;             /* Position list for deferred tokens */
119759   int nPoslist = 0;               /* Number of bytes in aPoslist */
119760   int iPrev = -1;                 /* Token number of previous deferred token */
119761
119762   assert( pPhrase->doclist.bFreeList==0 );
119763
119764   for(iToken=0; iToken<pPhrase->nToken; iToken++){
119765     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
119766     Fts3DeferredToken *pDeferred = pToken->pDeferred;
119767
119768     if( pDeferred ){
119769       char *pList;
119770       int nList;
119771       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
119772       if( rc!=SQLITE_OK ) return rc;
119773
119774       if( pList==0 ){
119775         sqlite3_free(aPoslist);
119776         pPhrase->doclist.pList = 0;
119777         pPhrase->doclist.nList = 0;
119778         return SQLITE_OK;
119779
119780       }else if( aPoslist==0 ){
119781         aPoslist = pList;
119782         nPoslist = nList;
119783
119784       }else{
119785         char *aOut = pList;
119786         char *p1 = aPoslist;
119787         char *p2 = aOut;
119788
119789         assert( iPrev>=0 );
119790         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
119791         sqlite3_free(aPoslist);
119792         aPoslist = pList;
119793         nPoslist = (int)(aOut - aPoslist);
119794         if( nPoslist==0 ){
119795           sqlite3_free(aPoslist);
119796           pPhrase->doclist.pList = 0;
119797           pPhrase->doclist.nList = 0;
119798           return SQLITE_OK;
119799         }
119800       }
119801       iPrev = iToken;
119802     }
119803   }
119804
119805   if( iPrev>=0 ){
119806     int nMaxUndeferred = pPhrase->iDoclistToken;
119807     if( nMaxUndeferred<0 ){
119808       pPhrase->doclist.pList = aPoslist;
119809       pPhrase->doclist.nList = nPoslist;
119810       pPhrase->doclist.iDocid = pCsr->iPrevId;
119811       pPhrase->doclist.bFreeList = 1;
119812     }else{
119813       int nDistance;
119814       char *p1;
119815       char *p2;
119816       char *aOut;
119817
119818       if( nMaxUndeferred>iPrev ){
119819         p1 = aPoslist;
119820         p2 = pPhrase->doclist.pList;
119821         nDistance = nMaxUndeferred - iPrev;
119822       }else{
119823         p1 = pPhrase->doclist.pList;
119824         p2 = aPoslist;
119825         nDistance = iPrev - nMaxUndeferred;
119826       }
119827
119828       aOut = (char *)sqlite3_malloc(nPoslist+8);
119829       if( !aOut ){
119830         sqlite3_free(aPoslist);
119831         return SQLITE_NOMEM;
119832       }
119833       
119834       pPhrase->doclist.pList = aOut;
119835       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
119836         pPhrase->doclist.bFreeList = 1;
119837         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
119838       }else{
119839         sqlite3_free(aOut);
119840         pPhrase->doclist.pList = 0;
119841         pPhrase->doclist.nList = 0;
119842       }
119843       sqlite3_free(aPoslist);
119844     }
119845   }
119846
119847   return SQLITE_OK;
119848 }
119849
119850 /*
119851 ** This function is called for each Fts3Phrase in a full-text query 
119852 ** expression to initialize the mechanism for returning rows. Once this
119853 ** function has been called successfully on an Fts3Phrase, it may be
119854 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
119855 **
119856 ** If parameter bOptOk is true, then the phrase may (or may not) use the
119857 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
119858 ** memory within this call.
119859 **
119860 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119861 */
119862 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
119863   int rc;                         /* Error code */
119864   Fts3PhraseToken *pFirst = &p->aToken[0];
119865   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119866
119867   if( pCsr->bDesc==pTab->bDescIdx 
119868    && bOptOk==1 
119869    && p->nToken==1 
119870    && pFirst->pSegcsr 
119871    && pFirst->pSegcsr->bLookup 
119872    && pFirst->bFirst==0
119873   ){
119874     /* Use the incremental approach. */
119875     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
119876     rc = sqlite3Fts3MsrIncrStart(
119877         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
119878     p->bIncr = 1;
119879
119880   }else{
119881     /* Load the full doclist for the phrase into memory. */
119882     rc = fts3EvalPhraseLoad(pCsr, p);
119883     p->bIncr = 0;
119884   }
119885
119886   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
119887   return rc;
119888 }
119889
119890 /*
119891 ** This function is used to iterate backwards (from the end to start) 
119892 ** through doclists. It is used by this module to iterate through phrase
119893 ** doclists in reverse and by the fts3_write.c module to iterate through
119894 ** pending-terms lists when writing to databases with "order=desc".
119895 **
119896 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
119897 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
119898 ** function iterates from the end of the doclist to the beginning.
119899 */
119900 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
119901   int bDescIdx,                   /* True if the doclist is desc */
119902   char *aDoclist,                 /* Pointer to entire doclist */
119903   int nDoclist,                   /* Length of aDoclist in bytes */
119904   char **ppIter,                  /* IN/OUT: Iterator pointer */
119905   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
119906   int *pnList,                    /* OUT: List length pointer */
119907   u8 *pbEof                       /* OUT: End-of-file flag */
119908 ){
119909   char *p = *ppIter;
119910
119911   assert( nDoclist>0 );
119912   assert( *pbEof==0 );
119913   assert( p || *piDocid==0 );
119914   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
119915
119916   if( p==0 ){
119917     sqlite3_int64 iDocid = 0;
119918     char *pNext = 0;
119919     char *pDocid = aDoclist;
119920     char *pEnd = &aDoclist[nDoclist];
119921     int iMul = 1;
119922
119923     while( pDocid<pEnd ){
119924       sqlite3_int64 iDelta;
119925       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
119926       iDocid += (iMul * iDelta);
119927       pNext = pDocid;
119928       fts3PoslistCopy(0, &pDocid);
119929       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
119930       iMul = (bDescIdx ? -1 : 1);
119931     }
119932
119933     *pnList = (int)(pEnd - pNext);
119934     *ppIter = pNext;
119935     *piDocid = iDocid;
119936   }else{
119937     int iMul = (bDescIdx ? -1 : 1);
119938     sqlite3_int64 iDelta;
119939     fts3GetReverseVarint(&p, aDoclist, &iDelta);
119940     *piDocid -= (iMul * iDelta);
119941
119942     if( p==aDoclist ){
119943       *pbEof = 1;
119944     }else{
119945       char *pSave = p;
119946       fts3ReversePoslist(aDoclist, &p);
119947       *pnList = (int)(pSave - p);
119948     }
119949     *ppIter = p;
119950   }
119951 }
119952
119953 /*
119954 ** Iterate forwards through a doclist.
119955 */
119956 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
119957   int bDescIdx,                   /* True if the doclist is desc */
119958   char *aDoclist,                 /* Pointer to entire doclist */
119959   int nDoclist,                   /* Length of aDoclist in bytes */
119960   char **ppIter,                  /* IN/OUT: Iterator pointer */
119961   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
119962   u8 *pbEof                       /* OUT: End-of-file flag */
119963 ){
119964   char *p = *ppIter;
119965
119966   assert( nDoclist>0 );
119967   assert( *pbEof==0 );
119968   assert( p || *piDocid==0 );
119969   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
119970
119971   if( p==0 ){
119972     p = aDoclist;
119973     p += sqlite3Fts3GetVarint(p, piDocid);
119974   }else{
119975     fts3PoslistCopy(0, &p);
119976     if( p>=&aDoclist[nDoclist] ){
119977       *pbEof = 1;
119978     }else{
119979       sqlite3_int64 iVar;
119980       p += sqlite3Fts3GetVarint(p, &iVar);
119981       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
119982     }
119983   }
119984
119985   *ppIter = p;
119986 }
119987
119988 /*
119989 ** Attempt to move the phrase iterator to point to the next matching docid. 
119990 ** If an error occurs, return an SQLite error code. Otherwise, return 
119991 ** SQLITE_OK.
119992 **
119993 ** If there is no "next" entry and no error occurs, then *pbEof is set to
119994 ** 1 before returning. Otherwise, if no error occurs and the iterator is
119995 ** successfully advanced, *pbEof is set to 0.
119996 */
119997 static int fts3EvalPhraseNext(
119998   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119999   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
120000   u8 *pbEof                       /* OUT: Set to 1 if EOF */
120001 ){
120002   int rc = SQLITE_OK;
120003   Fts3Doclist *pDL = &p->doclist;
120004   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120005
120006   if( p->bIncr ){
120007     assert( p->nToken==1 );
120008     assert( pDL->pNextDocid==0 );
120009     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
120010         &pDL->iDocid, &pDL->pList, &pDL->nList
120011     );
120012     if( rc==SQLITE_OK && !pDL->pList ){
120013       *pbEof = 1;
120014     }
120015   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
120016     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
120017         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
120018     );
120019     pDL->pList = pDL->pNextDocid;
120020   }else{
120021     char *pIter;                            /* Used to iterate through aAll */
120022     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
120023     if( pDL->pNextDocid ){
120024       pIter = pDL->pNextDocid;
120025     }else{
120026       pIter = pDL->aAll;
120027     }
120028
120029     if( pIter>=pEnd ){
120030       /* We have already reached the end of this doclist. EOF. */
120031       *pbEof = 1;
120032     }else{
120033       sqlite3_int64 iDelta;
120034       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
120035       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
120036         pDL->iDocid += iDelta;
120037       }else{
120038         pDL->iDocid -= iDelta;
120039       }
120040       pDL->pList = pIter;
120041       fts3PoslistCopy(0, &pIter);
120042       pDL->nList = (int)(pIter - pDL->pList);
120043
120044       /* pIter now points just past the 0x00 that terminates the position-
120045       ** list for document pDL->iDocid. However, if this position-list was
120046       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
120047       ** point to the start of the next docid value. The following line deals
120048       ** with this case by advancing pIter past the zero-padding added by
120049       ** fts3EvalNearTrim().  */
120050       while( pIter<pEnd && *pIter==0 ) pIter++;
120051
120052       pDL->pNextDocid = pIter;
120053       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
120054       *pbEof = 0;
120055     }
120056   }
120057
120058   return rc;
120059 }
120060
120061 /*
120062 **
120063 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120064 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
120065 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
120066 ** expressions for which all descendent tokens are deferred.
120067 **
120068 ** If parameter bOptOk is zero, then it is guaranteed that the
120069 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
120070 ** each phrase in the expression (subject to deferred token processing).
120071 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
120072 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
120073 **
120074 ** If an error occurs within this function, *pRc is set to an SQLite error
120075 ** code before returning.
120076 */
120077 static void fts3EvalStartReaders(
120078   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120079   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
120080   int bOptOk,                     /* True to enable incremental loading */
120081   int *pRc                        /* IN/OUT: Error code */
120082 ){
120083   if( pExpr && SQLITE_OK==*pRc ){
120084     if( pExpr->eType==FTSQUERY_PHRASE ){
120085       int i;
120086       int nToken = pExpr->pPhrase->nToken;
120087       for(i=0; i<nToken; i++){
120088         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
120089       }
120090       pExpr->bDeferred = (i==nToken);
120091       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
120092     }else{
120093       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
120094       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
120095       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
120096     }
120097   }
120098 }
120099
120100 /*
120101 ** An array of the following structures is assembled as part of the process
120102 ** of selecting tokens to defer before the query starts executing (as part
120103 ** of the xFilter() method). There is one element in the array for each
120104 ** token in the FTS expression.
120105 **
120106 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
120107 ** to phrases that are connected only by AND and NEAR operators (not OR or
120108 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
120109 ** separately. The root of a tokens AND/NEAR cluster is stored in 
120110 ** Fts3TokenAndCost.pRoot.
120111 */
120112 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
120113 struct Fts3TokenAndCost {
120114   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
120115   int iToken;                     /* Position of token in phrase */
120116   Fts3PhraseToken *pToken;        /* The token itself */
120117   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
120118   int nOvfl;                      /* Number of overflow pages to load doclist */
120119   int iCol;                       /* The column the token must match */
120120 };
120121
120122 /*
120123 ** This function is used to populate an allocated Fts3TokenAndCost array.
120124 **
120125 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120126 ** Otherwise, if an error occurs during execution, *pRc is set to an
120127 ** SQLite error code.
120128 */
120129 static void fts3EvalTokenCosts(
120130   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120131   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
120132   Fts3Expr *pExpr,                /* Expression to consider */
120133   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
120134   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
120135   int *pRc                        /* IN/OUT: Error code */
120136 ){
120137   if( *pRc==SQLITE_OK ){
120138     if( pExpr->eType==FTSQUERY_PHRASE ){
120139       Fts3Phrase *pPhrase = pExpr->pPhrase;
120140       int i;
120141       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
120142         Fts3TokenAndCost *pTC = (*ppTC)++;
120143         pTC->pPhrase = pPhrase;
120144         pTC->iToken = i;
120145         pTC->pRoot = pRoot;
120146         pTC->pToken = &pPhrase->aToken[i];
120147         pTC->iCol = pPhrase->iColumn;
120148         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
120149       }
120150     }else if( pExpr->eType!=FTSQUERY_NOT ){
120151       assert( pExpr->eType==FTSQUERY_OR
120152            || pExpr->eType==FTSQUERY_AND
120153            || pExpr->eType==FTSQUERY_NEAR
120154       );
120155       assert( pExpr->pLeft && pExpr->pRight );
120156       if( pExpr->eType==FTSQUERY_OR ){
120157         pRoot = pExpr->pLeft;
120158         **ppOr = pRoot;
120159         (*ppOr)++;
120160       }
120161       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
120162       if( pExpr->eType==FTSQUERY_OR ){
120163         pRoot = pExpr->pRight;
120164         **ppOr = pRoot;
120165         (*ppOr)++;
120166       }
120167       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
120168     }
120169   }
120170 }
120171
120172 /*
120173 ** Determine the average document (row) size in pages. If successful,
120174 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
120175 ** an SQLite error code.
120176 **
120177 ** The average document size in pages is calculated by first calculating 
120178 ** determining the average size in bytes, B. If B is less than the amount
120179 ** of data that will fit on a single leaf page of an intkey table in
120180 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
120181 ** the number of overflow pages consumed by a record B bytes in size.
120182 */
120183 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
120184   if( pCsr->nRowAvg==0 ){
120185     /* The average document size, which is required to calculate the cost
120186     ** of each doclist, has not yet been determined. Read the required 
120187     ** data from the %_stat table to calculate it.
120188     **
120189     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
120190     ** varints, where nCol is the number of columns in the FTS3 table.
120191     ** The first varint is the number of documents currently stored in
120192     ** the table. The following nCol varints contain the total amount of
120193     ** data stored in all rows of each column of the table, from left
120194     ** to right.
120195     */
120196     int rc;
120197     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120198     sqlite3_stmt *pStmt;
120199     sqlite3_int64 nDoc = 0;
120200     sqlite3_int64 nByte = 0;
120201     const char *pEnd;
120202     const char *a;
120203
120204     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
120205     if( rc!=SQLITE_OK ) return rc;
120206     a = sqlite3_column_blob(pStmt, 0);
120207     assert( a );
120208
120209     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
120210     a += sqlite3Fts3GetVarint(a, &nDoc);
120211     while( a<pEnd ){
120212       a += sqlite3Fts3GetVarint(a, &nByte);
120213     }
120214     if( nDoc==0 || nByte==0 ){
120215       sqlite3_reset(pStmt);
120216       return FTS_CORRUPT_VTAB;
120217     }
120218
120219     pCsr->nDoc = nDoc;
120220     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
120221     assert( pCsr->nRowAvg>0 ); 
120222     rc = sqlite3_reset(pStmt);
120223     if( rc!=SQLITE_OK ) return rc;
120224   }
120225
120226   *pnPage = pCsr->nRowAvg;
120227   return SQLITE_OK;
120228 }
120229
120230 /*
120231 ** This function is called to select the tokens (if any) that will be 
120232 ** deferred. The array aTC[] has already been populated when this is
120233 ** called.
120234 **
120235 ** This function is called once for each AND/NEAR cluster in the 
120236 ** expression. Each invocation determines which tokens to defer within
120237 ** the cluster with root node pRoot. See comments above the definition
120238 ** of struct Fts3TokenAndCost for more details.
120239 **
120240 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
120241 ** called on each token to defer. Otherwise, an SQLite error code is
120242 ** returned.
120243 */
120244 static int fts3EvalSelectDeferred(
120245   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120246   Fts3Expr *pRoot,                /* Consider tokens with this root node */
120247   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
120248   int nTC                         /* Number of entries in aTC[] */
120249 ){
120250   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120251   int nDocSize = 0;               /* Number of pages per doc loaded */
120252   int rc = SQLITE_OK;             /* Return code */
120253   int ii;                         /* Iterator variable for various purposes */
120254   int nOvfl = 0;                  /* Total overflow pages used by doclists */
120255   int nToken = 0;                 /* Total number of tokens in cluster */
120256
120257   int nMinEst = 0;                /* The minimum count for any phrase so far. */
120258   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
120259
120260   /* Tokens are never deferred for FTS tables created using the content=xxx
120261   ** option. The reason being that it is not guaranteed that the content
120262   ** table actually contains the same data as the index. To prevent this from
120263   ** causing any problems, the deferred token optimization is completely
120264   ** disabled for content=xxx tables. */
120265   if( pTab->zContentTbl ){
120266     return SQLITE_OK;
120267   }
120268
120269   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
120270   ** associated with the tokens spill onto overflow pages, or if there is
120271   ** only 1 token, exit early. No tokens to defer in this case. */
120272   for(ii=0; ii<nTC; ii++){
120273     if( aTC[ii].pRoot==pRoot ){
120274       nOvfl += aTC[ii].nOvfl;
120275       nToken++;
120276     }
120277   }
120278   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
120279
120280   /* Obtain the average docsize (in pages). */
120281   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
120282   assert( rc!=SQLITE_OK || nDocSize>0 );
120283
120284
120285   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
120286   ** of the number of overflow pages that will be loaded by the pager layer 
120287   ** to retrieve the entire doclist for the token from the full-text index.
120288   ** Load the doclists for tokens that are either:
120289   **
120290   **   a. The cheapest token in the entire query (i.e. the one visited by the
120291   **      first iteration of this loop), or
120292   **
120293   **   b. Part of a multi-token phrase.
120294   **
120295   ** After each token doclist is loaded, merge it with the others from the
120296   ** same phrase and count the number of documents that the merged doclist
120297   ** contains. Set variable "nMinEst" to the smallest number of documents in 
120298   ** any phrase doclist for which 1 or more token doclists have been loaded.
120299   ** Let nOther be the number of other phrases for which it is certain that
120300   ** one or more tokens will not be deferred.
120301   **
120302   ** Then, for each token, defer it if loading the doclist would result in
120303   ** loading N or more overflow pages into memory, where N is computed as:
120304   **
120305   **    (nMinEst + 4^nOther - 1) / (4^nOther)
120306   */
120307   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
120308     int iTC;                      /* Used to iterate through aTC[] array. */
120309     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
120310
120311     /* Set pTC to point to the cheapest remaining token. */
120312     for(iTC=0; iTC<nTC; iTC++){
120313       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
120314        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
120315       ){
120316         pTC = &aTC[iTC];
120317       }
120318     }
120319     assert( pTC );
120320
120321     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
120322       /* The number of overflow pages to load for this (and therefore all
120323       ** subsequent) tokens is greater than the estimated number of pages 
120324       ** that will be loaded if all subsequent tokens are deferred.
120325       */
120326       Fts3PhraseToken *pToken = pTC->pToken;
120327       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
120328       fts3SegReaderCursorFree(pToken->pSegcsr);
120329       pToken->pSegcsr = 0;
120330     }else{
120331       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
120332       ** for-loop. Except, limit the value to 2^24 to prevent it from 
120333       ** overflowing the 32-bit integer it is stored in. */
120334       if( ii<12 ) nLoad4 = nLoad4*4;
120335
120336       if( ii==0 || pTC->pPhrase->nToken>1 ){
120337         /* Either this is the cheapest token in the entire query, or it is
120338         ** part of a multi-token phrase. Either way, the entire doclist will
120339         ** (eventually) be loaded into memory. It may as well be now. */
120340         Fts3PhraseToken *pToken = pTC->pToken;
120341         int nList = 0;
120342         char *pList = 0;
120343         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
120344         assert( rc==SQLITE_OK || pList==0 );
120345         if( rc==SQLITE_OK ){
120346           int nCount;
120347           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
120348           nCount = fts3DoclistCountDocids(
120349               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
120350           );
120351           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
120352         }
120353       }
120354     }
120355     pTC->pToken = 0;
120356   }
120357
120358   return rc;
120359 }
120360
120361 /*
120362 ** This function is called from within the xFilter method. It initializes
120363 ** the full-text query currently stored in pCsr->pExpr. To iterate through
120364 ** the results of a query, the caller does:
120365 **
120366 **    fts3EvalStart(pCsr);
120367 **    while( 1 ){
120368 **      fts3EvalNext(pCsr);
120369 **      if( pCsr->bEof ) break;
120370 **      ... return row pCsr->iPrevId to the caller ...
120371 **    }
120372 */
120373 static int fts3EvalStart(Fts3Cursor *pCsr){
120374   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120375   int rc = SQLITE_OK;
120376   int nToken = 0;
120377   int nOr = 0;
120378
120379   /* Allocate a MultiSegReader for each token in the expression. */
120380   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
120381
120382   /* Determine which, if any, tokens in the expression should be deferred. */
120383 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
120384   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
120385     Fts3TokenAndCost *aTC;
120386     Fts3Expr **apOr;
120387     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
120388         sizeof(Fts3TokenAndCost) * nToken
120389       + sizeof(Fts3Expr *) * nOr * 2
120390     );
120391     apOr = (Fts3Expr **)&aTC[nToken];
120392
120393     if( !aTC ){
120394       rc = SQLITE_NOMEM;
120395     }else{
120396       int ii;
120397       Fts3TokenAndCost *pTC = aTC;
120398       Fts3Expr **ppOr = apOr;
120399
120400       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
120401       nToken = (int)(pTC-aTC);
120402       nOr = (int)(ppOr-apOr);
120403
120404       if( rc==SQLITE_OK ){
120405         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
120406         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
120407           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
120408         }
120409       }
120410
120411       sqlite3_free(aTC);
120412     }
120413   }
120414 #endif
120415
120416   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
120417   return rc;
120418 }
120419
120420 /*
120421 ** Invalidate the current position list for phrase pPhrase.
120422 */
120423 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
120424   if( pPhrase->doclist.bFreeList ){
120425     sqlite3_free(pPhrase->doclist.pList);
120426   }
120427   pPhrase->doclist.pList = 0;
120428   pPhrase->doclist.nList = 0;
120429   pPhrase->doclist.bFreeList = 0;
120430 }
120431
120432 /*
120433 ** This function is called to edit the position list associated with
120434 ** the phrase object passed as the fifth argument according to a NEAR
120435 ** condition. For example:
120436 **
120437 **     abc NEAR/5 "def ghi"
120438 **
120439 ** Parameter nNear is passed the NEAR distance of the expression (5 in
120440 ** the example above). When this function is called, *paPoslist points to
120441 ** the position list, and *pnToken is the number of phrase tokens in, the
120442 ** phrase on the other side of the NEAR operator to pPhrase. For example,
120443 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
120444 ** the position list associated with phrase "abc".
120445 **
120446 ** All positions in the pPhrase position list that are not sufficiently
120447 ** close to a position in the *paPoslist position list are removed. If this
120448 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
120449 **
120450 ** Before returning, *paPoslist is set to point to the position lsit 
120451 ** associated with pPhrase. And *pnToken is set to the number of tokens in
120452 ** pPhrase.
120453 */
120454 static int fts3EvalNearTrim(
120455   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
120456   char *aTmp,                     /* Temporary space to use */
120457   char **paPoslist,               /* IN/OUT: Position list */
120458   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
120459   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
120460 ){
120461   int nParam1 = nNear + pPhrase->nToken;
120462   int nParam2 = nNear + *pnToken;
120463   int nNew;
120464   char *p2; 
120465   char *pOut; 
120466   int res;
120467
120468   assert( pPhrase->doclist.pList );
120469
120470   p2 = pOut = pPhrase->doclist.pList;
120471   res = fts3PoslistNearMerge(
120472     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
120473   );
120474   if( res ){
120475     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
120476     assert( pPhrase->doclist.pList[nNew]=='\0' );
120477     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
120478     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
120479     pPhrase->doclist.nList = nNew;
120480     *paPoslist = pPhrase->doclist.pList;
120481     *pnToken = pPhrase->nToken;
120482   }
120483
120484   return res;
120485 }
120486
120487 /*
120488 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
120489 ** Otherwise, it advances the expression passed as the second argument to
120490 ** point to the next matching row in the database. Expressions iterate through
120491 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
120492 ** or descending if it is non-zero.
120493 **
120494 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
120495 ** successful, the following variables in pExpr are set:
120496 **
120497 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
120498 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
120499 **
120500 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
120501 ** at EOF, then the following variables are populated with the position list
120502 ** for the phrase for the visited row:
120503 **
120504 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
120505 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
120506 **
120507 ** It says above that this function advances the expression to the next
120508 ** matching row. This is usually true, but there are the following exceptions:
120509 **
120510 **   1. Deferred tokens are not taken into account. If a phrase consists
120511 **      entirely of deferred tokens, it is assumed to match every row in
120512 **      the db. In this case the position-list is not populated at all. 
120513 **
120514 **      Or, if a phrase contains one or more deferred tokens and one or
120515 **      more non-deferred tokens, then the expression is advanced to the 
120516 **      next possible match, considering only non-deferred tokens. In other
120517 **      words, if the phrase is "A B C", and "B" is deferred, the expression
120518 **      is advanced to the next row that contains an instance of "A * C", 
120519 **      where "*" may match any single token. The position list in this case
120520 **      is populated as for "A * C" before returning.
120521 **
120522 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
120523 **      advanced to point to the next row that matches "x AND y".
120524 ** 
120525 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
120526 ** really a match, taking into account deferred tokens and NEAR operators.
120527 */
120528 static void fts3EvalNextRow(
120529   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120530   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
120531   int *pRc                        /* IN/OUT: Error code */
120532 ){
120533   if( *pRc==SQLITE_OK ){
120534     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
120535     assert( pExpr->bEof==0 );
120536     pExpr->bStart = 1;
120537
120538     switch( pExpr->eType ){
120539       case FTSQUERY_NEAR:
120540       case FTSQUERY_AND: {
120541         Fts3Expr *pLeft = pExpr->pLeft;
120542         Fts3Expr *pRight = pExpr->pRight;
120543         assert( !pLeft->bDeferred || !pRight->bDeferred );
120544
120545         if( pLeft->bDeferred ){
120546           /* LHS is entirely deferred. So we assume it matches every row.
120547           ** Advance the RHS iterator to find the next row visited. */
120548           fts3EvalNextRow(pCsr, pRight, pRc);
120549           pExpr->iDocid = pRight->iDocid;
120550           pExpr->bEof = pRight->bEof;
120551         }else if( pRight->bDeferred ){
120552           /* RHS is entirely deferred. So we assume it matches every row.
120553           ** Advance the LHS iterator to find the next row visited. */
120554           fts3EvalNextRow(pCsr, pLeft, pRc);
120555           pExpr->iDocid = pLeft->iDocid;
120556           pExpr->bEof = pLeft->bEof;
120557         }else{
120558           /* Neither the RHS or LHS are deferred. */
120559           fts3EvalNextRow(pCsr, pLeft, pRc);
120560           fts3EvalNextRow(pCsr, pRight, pRc);
120561           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
120562             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120563             if( iDiff==0 ) break;
120564             if( iDiff<0 ){
120565               fts3EvalNextRow(pCsr, pLeft, pRc);
120566             }else{
120567               fts3EvalNextRow(pCsr, pRight, pRc);
120568             }
120569           }
120570           pExpr->iDocid = pLeft->iDocid;
120571           pExpr->bEof = (pLeft->bEof || pRight->bEof);
120572         }
120573         break;
120574       }
120575   
120576       case FTSQUERY_OR: {
120577         Fts3Expr *pLeft = pExpr->pLeft;
120578         Fts3Expr *pRight = pExpr->pRight;
120579         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120580
120581         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
120582         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
120583
120584         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
120585           fts3EvalNextRow(pCsr, pLeft, pRc);
120586         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
120587           fts3EvalNextRow(pCsr, pRight, pRc);
120588         }else{
120589           fts3EvalNextRow(pCsr, pLeft, pRc);
120590           fts3EvalNextRow(pCsr, pRight, pRc);
120591         }
120592
120593         pExpr->bEof = (pLeft->bEof && pRight->bEof);
120594         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120595         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
120596           pExpr->iDocid = pLeft->iDocid;
120597         }else{
120598           pExpr->iDocid = pRight->iDocid;
120599         }
120600
120601         break;
120602       }
120603
120604       case FTSQUERY_NOT: {
120605         Fts3Expr *pLeft = pExpr->pLeft;
120606         Fts3Expr *pRight = pExpr->pRight;
120607
120608         if( pRight->bStart==0 ){
120609           fts3EvalNextRow(pCsr, pRight, pRc);
120610           assert( *pRc!=SQLITE_OK || pRight->bStart );
120611         }
120612
120613         fts3EvalNextRow(pCsr, pLeft, pRc);
120614         if( pLeft->bEof==0 ){
120615           while( !*pRc 
120616               && !pRight->bEof 
120617               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
120618           ){
120619             fts3EvalNextRow(pCsr, pRight, pRc);
120620           }
120621         }
120622         pExpr->iDocid = pLeft->iDocid;
120623         pExpr->bEof = pLeft->bEof;
120624         break;
120625       }
120626
120627       default: {
120628         Fts3Phrase *pPhrase = pExpr->pPhrase;
120629         fts3EvalInvalidatePoslist(pPhrase);
120630         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
120631         pExpr->iDocid = pPhrase->doclist.iDocid;
120632         break;
120633       }
120634     }
120635   }
120636 }
120637
120638 /*
120639 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
120640 ** cluster, then this function returns 1 immediately.
120641 **
120642 ** Otherwise, it checks if the current row really does match the NEAR 
120643 ** expression, using the data currently stored in the position lists 
120644 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
120645 **
120646 ** If the current row is a match, the position list associated with each
120647 ** phrase in the NEAR expression is edited in place to contain only those
120648 ** phrase instances sufficiently close to their peers to satisfy all NEAR
120649 ** constraints. In this case it returns 1. If the NEAR expression does not 
120650 ** match the current row, 0 is returned. The position lists may or may not
120651 ** be edited if 0 is returned.
120652 */
120653 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
120654   int res = 1;
120655
120656   /* The following block runs if pExpr is the root of a NEAR query.
120657   ** For example, the query:
120658   **
120659   **         "w" NEAR "x" NEAR "y" NEAR "z"
120660   **
120661   ** which is represented in tree form as:
120662   **
120663   **                               |
120664   **                          +--NEAR--+      <-- root of NEAR query
120665   **                          |        |
120666   **                     +--NEAR--+   "z"
120667   **                     |        |
120668   **                +--NEAR--+   "y"
120669   **                |        |
120670   **               "w"      "x"
120671   **
120672   ** The right-hand child of a NEAR node is always a phrase. The 
120673   ** left-hand child may be either a phrase or a NEAR node. There are
120674   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
120675   */
120676   if( *pRc==SQLITE_OK 
120677    && pExpr->eType==FTSQUERY_NEAR 
120678    && pExpr->bEof==0
120679    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120680   ){
120681     Fts3Expr *p; 
120682     int nTmp = 0;                 /* Bytes of temp space */
120683     char *aTmp;                   /* Temp space for PoslistNearMerge() */
120684
120685     /* Allocate temporary working space. */
120686     for(p=pExpr; p->pLeft; p=p->pLeft){
120687       nTmp += p->pRight->pPhrase->doclist.nList;
120688     }
120689     nTmp += p->pPhrase->doclist.nList;
120690     aTmp = sqlite3_malloc(nTmp*2);
120691     if( !aTmp ){
120692       *pRc = SQLITE_NOMEM;
120693       res = 0;
120694     }else{
120695       char *aPoslist = p->pPhrase->doclist.pList;
120696       int nToken = p->pPhrase->nToken;
120697
120698       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
120699         Fts3Phrase *pPhrase = p->pRight->pPhrase;
120700         int nNear = p->nNear;
120701         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120702       }
120703   
120704       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
120705       nToken = pExpr->pRight->pPhrase->nToken;
120706       for(p=pExpr->pLeft; p && res; p=p->pLeft){
120707         int nNear;
120708         Fts3Phrase *pPhrase;
120709         assert( p->pParent && p->pParent->pLeft==p );
120710         nNear = p->pParent->nNear;
120711         pPhrase = (
120712             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
120713         );
120714         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120715       }
120716     }
120717
120718     sqlite3_free(aTmp);
120719   }
120720
120721   return res;
120722 }
120723
120724 /*
120725 ** This function is a helper function for fts3EvalTestDeferredAndNear().
120726 ** Assuming no error occurs or has occurred, It returns non-zero if the
120727 ** expression passed as the second argument matches the row that pCsr 
120728 ** currently points to, or zero if it does not.
120729 **
120730 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120731 ** If an error occurs during execution of this function, *pRc is set to 
120732 ** the appropriate SQLite error code. In this case the returned value is 
120733 ** undefined.
120734 */
120735 static int fts3EvalTestExpr(
120736   Fts3Cursor *pCsr,               /* FTS cursor handle */
120737   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
120738   int *pRc                        /* IN/OUT: Error code */
120739 ){
120740   int bHit = 1;                   /* Return value */
120741   if( *pRc==SQLITE_OK ){
120742     switch( pExpr->eType ){
120743       case FTSQUERY_NEAR:
120744       case FTSQUERY_AND:
120745         bHit = (
120746             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120747          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120748          && fts3EvalNearTest(pExpr, pRc)
120749         );
120750
120751         /* If the NEAR expression does not match any rows, zero the doclist for 
120752         ** all phrases involved in the NEAR. This is because the snippet(),
120753         ** offsets() and matchinfo() functions are not supposed to recognize 
120754         ** any instances of phrases that are part of unmatched NEAR queries. 
120755         ** For example if this expression:
120756         **
120757         **    ... MATCH 'a OR (b NEAR c)'
120758         **
120759         ** is matched against a row containing:
120760         **
120761         **        'a b d e'
120762         **
120763         ** then any snippet() should ony highlight the "a" term, not the "b"
120764         ** (as "b" is part of a non-matching NEAR clause).
120765         */
120766         if( bHit==0 
120767          && pExpr->eType==FTSQUERY_NEAR 
120768          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120769         ){
120770           Fts3Expr *p;
120771           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
120772             if( p->pRight->iDocid==pCsr->iPrevId ){
120773               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
120774             }
120775           }
120776           if( p->iDocid==pCsr->iPrevId ){
120777             fts3EvalInvalidatePoslist(p->pPhrase);
120778           }
120779         }
120780
120781         break;
120782
120783       case FTSQUERY_OR: {
120784         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
120785         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
120786         bHit = bHit1 || bHit2;
120787         break;
120788       }
120789
120790       case FTSQUERY_NOT:
120791         bHit = (
120792             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120793          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120794         );
120795         break;
120796
120797       default: {
120798 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
120799         if( pCsr->pDeferred 
120800          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
120801         ){
120802           Fts3Phrase *pPhrase = pExpr->pPhrase;
120803           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
120804           if( pExpr->bDeferred ){
120805             fts3EvalInvalidatePoslist(pPhrase);
120806           }
120807           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
120808           bHit = (pPhrase->doclist.pList!=0);
120809           pExpr->iDocid = pCsr->iPrevId;
120810         }else
120811 #endif
120812         {
120813           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
120814         }
120815         break;
120816       }
120817     }
120818   }
120819   return bHit;
120820 }
120821
120822 /*
120823 ** This function is called as the second part of each xNext operation when
120824 ** iterating through the results of a full-text query. At this point the
120825 ** cursor points to a row that matches the query expression, with the
120826 ** following caveats:
120827 **
120828 **   * Up until this point, "NEAR" operators in the expression have been
120829 **     treated as "AND".
120830 **
120831 **   * Deferred tokens have not yet been considered.
120832 **
120833 ** If *pRc is not SQLITE_OK when this function is called, it immediately
120834 ** returns 0. Otherwise, it tests whether or not after considering NEAR
120835 ** operators and deferred tokens the current row is still a match for the
120836 ** expression. It returns 1 if both of the following are true:
120837 **
120838 **   1. *pRc is SQLITE_OK when this function returns, and
120839 **
120840 **   2. After scanning the current FTS table row for the deferred tokens,
120841 **      it is determined that the row does *not* match the query.
120842 **
120843 ** Or, if no error occurs and it seems the current row does match the FTS
120844 ** query, return 0.
120845 */
120846 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
120847   int rc = *pRc;
120848   int bMiss = 0;
120849   if( rc==SQLITE_OK ){
120850
120851     /* If there are one or more deferred tokens, load the current row into
120852     ** memory and scan it to determine the position list for each deferred
120853     ** token. Then, see if this row is really a match, considering deferred
120854     ** tokens and NEAR operators (neither of which were taken into account
120855     ** earlier, by fts3EvalNextRow()). 
120856     */
120857     if( pCsr->pDeferred ){
120858       rc = fts3CursorSeek(0, pCsr);
120859       if( rc==SQLITE_OK ){
120860         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
120861       }
120862     }
120863     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
120864
120865     /* Free the position-lists accumulated for each deferred token above. */
120866     sqlite3Fts3FreeDeferredDoclists(pCsr);
120867     *pRc = rc;
120868   }
120869   return (rc==SQLITE_OK && bMiss);
120870 }
120871
120872 /*
120873 ** Advance to the next document that matches the FTS expression in
120874 ** Fts3Cursor.pExpr.
120875 */
120876 static int fts3EvalNext(Fts3Cursor *pCsr){
120877   int rc = SQLITE_OK;             /* Return Code */
120878   Fts3Expr *pExpr = pCsr->pExpr;
120879   assert( pCsr->isEof==0 );
120880   if( pExpr==0 ){
120881     pCsr->isEof = 1;
120882   }else{
120883     do {
120884       if( pCsr->isRequireSeek==0 ){
120885         sqlite3_reset(pCsr->pStmt);
120886       }
120887       assert( sqlite3_data_count(pCsr->pStmt)==0 );
120888       fts3EvalNextRow(pCsr, pExpr, &rc);
120889       pCsr->isEof = pExpr->bEof;
120890       pCsr->isRequireSeek = 1;
120891       pCsr->isMatchinfoNeeded = 1;
120892       pCsr->iPrevId = pExpr->iDocid;
120893     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
120894   }
120895   return rc;
120896 }
120897
120898 /*
120899 ** Restart interation for expression pExpr so that the next call to
120900 ** fts3EvalNext() visits the first row. Do not allow incremental 
120901 ** loading or merging of phrase doclists for this iteration.
120902 **
120903 ** If *pRc is other than SQLITE_OK when this function is called, it is
120904 ** a no-op. If an error occurs within this function, *pRc is set to an
120905 ** SQLite error code before returning.
120906 */
120907 static void fts3EvalRestart(
120908   Fts3Cursor *pCsr,
120909   Fts3Expr *pExpr,
120910   int *pRc
120911 ){
120912   if( pExpr && *pRc==SQLITE_OK ){
120913     Fts3Phrase *pPhrase = pExpr->pPhrase;
120914
120915     if( pPhrase ){
120916       fts3EvalInvalidatePoslist(pPhrase);
120917       if( pPhrase->bIncr ){
120918         assert( pPhrase->nToken==1 );
120919         assert( pPhrase->aToken[0].pSegcsr );
120920         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
120921         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
120922       }
120923
120924       pPhrase->doclist.pNextDocid = 0;
120925       pPhrase->doclist.iDocid = 0;
120926     }
120927
120928     pExpr->iDocid = 0;
120929     pExpr->bEof = 0;
120930     pExpr->bStart = 0;
120931
120932     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
120933     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
120934   }
120935 }
120936
120937 /*
120938 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
120939 ** expression rooted at pExpr, the cursor iterates through all rows matched
120940 ** by pExpr, calling this function for each row. This function increments
120941 ** the values in Fts3Expr.aMI[] according to the position-list currently
120942 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
120943 ** expression nodes.
120944 */
120945 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
120946   if( pExpr ){
120947     Fts3Phrase *pPhrase = pExpr->pPhrase;
120948     if( pPhrase && pPhrase->doclist.pList ){
120949       int iCol = 0;
120950       char *p = pPhrase->doclist.pList;
120951
120952       assert( *p );
120953       while( 1 ){
120954         u8 c = 0;
120955         int iCnt = 0;
120956         while( 0xFE & (*p | c) ){
120957           if( (c&0x80)==0 ) iCnt++;
120958           c = *p++ & 0x80;
120959         }
120960
120961         /* aMI[iCol*3 + 1] = Number of occurrences
120962         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
120963         */
120964         pExpr->aMI[iCol*3 + 1] += iCnt;
120965         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
120966         if( *p==0x00 ) break;
120967         p++;
120968         p += sqlite3Fts3GetVarint32(p, &iCol);
120969       }
120970     }
120971
120972     fts3EvalUpdateCounts(pExpr->pLeft);
120973     fts3EvalUpdateCounts(pExpr->pRight);
120974   }
120975 }
120976
120977 /*
120978 ** Expression pExpr must be of type FTSQUERY_PHRASE.
120979 **
120980 ** If it is not already allocated and populated, this function allocates and
120981 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
120982 ** of a NEAR expression, then it also allocates and populates the same array
120983 ** for all other phrases that are part of the NEAR expression.
120984 **
120985 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
120986 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
120987 */
120988 static int fts3EvalGatherStats(
120989   Fts3Cursor *pCsr,               /* Cursor object */
120990   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
120991 ){
120992   int rc = SQLITE_OK;             /* Return code */
120993
120994   assert( pExpr->eType==FTSQUERY_PHRASE );
120995   if( pExpr->aMI==0 ){
120996     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120997     Fts3Expr *pRoot;                /* Root of NEAR expression */
120998     Fts3Expr *p;                    /* Iterator used for several purposes */
120999
121000     sqlite3_int64 iPrevId = pCsr->iPrevId;
121001     sqlite3_int64 iDocid;
121002     u8 bEof;
121003
121004     /* Find the root of the NEAR expression */
121005     pRoot = pExpr;
121006     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
121007       pRoot = pRoot->pParent;
121008     }
121009     iDocid = pRoot->iDocid;
121010     bEof = pRoot->bEof;
121011     assert( pRoot->bStart );
121012
121013     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
121014     for(p=pRoot; p; p=p->pLeft){
121015       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
121016       assert( pE->aMI==0 );
121017       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
121018       if( !pE->aMI ) return SQLITE_NOMEM;
121019       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
121020     }
121021
121022     fts3EvalRestart(pCsr, pRoot, &rc);
121023
121024     while( pCsr->isEof==0 && rc==SQLITE_OK ){
121025
121026       do {
121027         /* Ensure the %_content statement is reset. */
121028         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
121029         assert( sqlite3_data_count(pCsr->pStmt)==0 );
121030
121031         /* Advance to the next document */
121032         fts3EvalNextRow(pCsr, pRoot, &rc);
121033         pCsr->isEof = pRoot->bEof;
121034         pCsr->isRequireSeek = 1;
121035         pCsr->isMatchinfoNeeded = 1;
121036         pCsr->iPrevId = pRoot->iDocid;
121037       }while( pCsr->isEof==0 
121038            && pRoot->eType==FTSQUERY_NEAR 
121039            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
121040       );
121041
121042       if( rc==SQLITE_OK && pCsr->isEof==0 ){
121043         fts3EvalUpdateCounts(pRoot);
121044       }
121045     }
121046
121047     pCsr->isEof = 0;
121048     pCsr->iPrevId = iPrevId;
121049
121050     if( bEof ){
121051       pRoot->bEof = bEof;
121052     }else{
121053       /* Caution: pRoot may iterate through docids in ascending or descending
121054       ** order. For this reason, even though it seems more defensive, the 
121055       ** do loop can not be written:
121056       **
121057       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
121058       */
121059       fts3EvalRestart(pCsr, pRoot, &rc);
121060       do {
121061         fts3EvalNextRow(pCsr, pRoot, &rc);
121062         assert( pRoot->bEof==0 );
121063       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
121064       fts3EvalTestDeferredAndNear(pCsr, &rc);
121065     }
121066   }
121067   return rc;
121068 }
121069
121070 /*
121071 ** This function is used by the matchinfo() module to query a phrase 
121072 ** expression node for the following information:
121073 **
121074 **   1. The total number of occurrences of the phrase in each column of 
121075 **      the FTS table (considering all rows), and
121076 **
121077 **   2. For each column, the number of rows in the table for which the
121078 **      column contains at least one instance of the phrase.
121079 **
121080 ** If no error occurs, SQLITE_OK is returned and the values for each column
121081 ** written into the array aiOut as follows:
121082 **
121083 **   aiOut[iCol*3 + 1] = Number of occurrences
121084 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
121085 **
121086 ** Caveats:
121087 **
121088 **   * If a phrase consists entirely of deferred tokens, then all output 
121089 **     values are set to the number of documents in the table. In other
121090 **     words we assume that very common tokens occur exactly once in each 
121091 **     column of each row of the table.
121092 **
121093 **   * If a phrase contains some deferred tokens (and some non-deferred 
121094 **     tokens), count the potential occurrence identified by considering
121095 **     the non-deferred tokens instead of actual phrase occurrences.
121096 **
121097 **   * If the phrase is part of a NEAR expression, then only phrase instances
121098 **     that meet the NEAR constraint are included in the counts.
121099 */
121100 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
121101   Fts3Cursor *pCsr,               /* FTS cursor handle */
121102   Fts3Expr *pExpr,                /* Phrase expression */
121103   u32 *aiOut                      /* Array to write results into (see above) */
121104 ){
121105   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121106   int rc = SQLITE_OK;
121107   int iCol;
121108
121109   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
121110     assert( pCsr->nDoc>0 );
121111     for(iCol=0; iCol<pTab->nColumn; iCol++){
121112       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
121113       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
121114     }
121115   }else{
121116     rc = fts3EvalGatherStats(pCsr, pExpr);
121117     if( rc==SQLITE_OK ){
121118       assert( pExpr->aMI );
121119       for(iCol=0; iCol<pTab->nColumn; iCol++){
121120         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
121121         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
121122       }
121123     }
121124   }
121125
121126   return rc;
121127 }
121128
121129 /*
121130 ** The expression pExpr passed as the second argument to this function
121131 ** must be of type FTSQUERY_PHRASE. 
121132 **
121133 ** The returned value is either NULL or a pointer to a buffer containing
121134 ** a position-list indicating the occurrences of the phrase in column iCol
121135 ** of the current row. 
121136 **
121137 ** More specifically, the returned buffer contains 1 varint for each 
121138 ** occurence of the phrase in the column, stored using the normal (delta+2) 
121139 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
121140 ** if the requested column contains "a b X c d X X" and the position-list
121141 ** for 'X' is requested, the buffer returned may contain:
121142 **
121143 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
121144 **
121145 ** This function works regardless of whether or not the phrase is deferred,
121146 ** incremental, or neither.
121147 */
121148 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
121149   Fts3Cursor *pCsr,               /* FTS3 cursor object */
121150   Fts3Expr *pExpr,                /* Phrase to return doclist for */
121151   int iCol,                       /* Column to return position list for */
121152   char **ppOut                    /* OUT: Pointer to position list */
121153 ){
121154   Fts3Phrase *pPhrase = pExpr->pPhrase;
121155   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121156   char *pIter;
121157   int iThis;
121158   sqlite3_int64 iDocid;
121159
121160   /* If this phrase is applies specifically to some column other than 
121161   ** column iCol, return a NULL pointer.  */
121162   *ppOut = 0;
121163   assert( iCol>=0 && iCol<pTab->nColumn );
121164   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
121165     return SQLITE_OK;
121166   }
121167
121168   iDocid = pExpr->iDocid;
121169   pIter = pPhrase->doclist.pList;
121170   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
121171     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
121172     int bOr = 0;
121173     u8 bEof = 0;
121174     Fts3Expr *p;
121175
121176     /* Check if this phrase descends from an OR expression node. If not, 
121177     ** return NULL. Otherwise, the entry that corresponds to docid 
121178     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
121179     for(p=pExpr->pParent; p; p=p->pParent){
121180       if( p->eType==FTSQUERY_OR ) bOr = 1;
121181     }
121182     if( bOr==0 ) return SQLITE_OK;
121183
121184     /* This is the descendent of an OR node. In this case we cannot use
121185     ** an incremental phrase. Load the entire doclist for the phrase
121186     ** into memory in this case.  */
121187     if( pPhrase->bIncr ){
121188       int rc = SQLITE_OK;
121189       int bEofSave = pExpr->bEof;
121190       fts3EvalRestart(pCsr, pExpr, &rc);
121191       while( rc==SQLITE_OK && !pExpr->bEof ){
121192         fts3EvalNextRow(pCsr, pExpr, &rc);
121193         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
121194       }
121195       pIter = pPhrase->doclist.pList;
121196       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
121197       if( rc!=SQLITE_OK ) return rc;
121198     }
121199
121200     if( pExpr->bEof ){
121201       pIter = 0;
121202       iDocid = 0;
121203     }
121204     bEof = (pPhrase->doclist.nAll==0);
121205     assert( bDescDoclist==0 || bDescDoclist==1 );
121206     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
121207
121208     if( pCsr->bDesc==bDescDoclist ){
121209       int dummy;
121210       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
121211         sqlite3Fts3DoclistPrev(
121212             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
121213             &pIter, &iDocid, &dummy, &bEof
121214         );
121215       }
121216     }else{
121217       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
121218         sqlite3Fts3DoclistNext(
121219             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
121220             &pIter, &iDocid, &bEof
121221         );
121222       }
121223     }
121224
121225     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
121226   }
121227   if( pIter==0 ) return SQLITE_OK;
121228
121229   if( *pIter==0x01 ){
121230     pIter++;
121231     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121232   }else{
121233     iThis = 0;
121234   }
121235   while( iThis<iCol ){
121236     fts3ColumnlistCopy(0, &pIter);
121237     if( *pIter==0x00 ) return 0;
121238     pIter++;
121239     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121240   }
121241
121242   *ppOut = ((iCol==iThis)?pIter:0);
121243   return SQLITE_OK;
121244 }
121245
121246 /*
121247 ** Free all components of the Fts3Phrase structure that were allocated by
121248 ** the eval module. Specifically, this means to free:
121249 **
121250 **   * the contents of pPhrase->doclist, and
121251 **   * any Fts3MultiSegReader objects held by phrase tokens.
121252 */
121253 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
121254   if( pPhrase ){
121255     int i;
121256     sqlite3_free(pPhrase->doclist.aAll);
121257     fts3EvalInvalidatePoslist(pPhrase);
121258     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
121259     for(i=0; i<pPhrase->nToken; i++){
121260       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
121261       pPhrase->aToken[i].pSegcsr = 0;
121262     }
121263   }
121264 }
121265
121266
121267 /*
121268 ** Return SQLITE_CORRUPT_VTAB.
121269 */
121270 #ifdef SQLITE_DEBUG
121271 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
121272   return SQLITE_CORRUPT_VTAB;
121273 }
121274 #endif
121275
121276 #if !SQLITE_CORE
121277 /*
121278 ** Initialize API pointer table, if required.
121279 */
121280 SQLITE_API int sqlite3_extension_init(
121281   sqlite3 *db, 
121282   char **pzErrMsg,
121283   const sqlite3_api_routines *pApi
121284 ){
121285   SQLITE_EXTENSION_INIT2(pApi)
121286   return sqlite3Fts3Init(db);
121287 }
121288 #endif
121289
121290 #endif
121291
121292 /************** End of fts3.c ************************************************/
121293 /************** Begin file fts3_aux.c ****************************************/
121294 /*
121295 ** 2011 Jan 27
121296 **
121297 ** The author disclaims copyright to this source code.  In place of
121298 ** a legal notice, here is a blessing:
121299 **
121300 **    May you do good and not evil.
121301 **    May you find forgiveness for yourself and forgive others.
121302 **    May you share freely, never taking more than you give.
121303 **
121304 ******************************************************************************
121305 **
121306 */
121307 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121308
121309 /* #include <string.h> */
121310 /* #include <assert.h> */
121311
121312 typedef struct Fts3auxTable Fts3auxTable;
121313 typedef struct Fts3auxCursor Fts3auxCursor;
121314
121315 struct Fts3auxTable {
121316   sqlite3_vtab base;              /* Base class used by SQLite core */
121317   Fts3Table *pFts3Tab;
121318 };
121319
121320 struct Fts3auxCursor {
121321   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
121322   Fts3MultiSegReader csr;        /* Must be right after "base" */
121323   Fts3SegFilter filter;
121324   char *zStop;
121325   int nStop;                      /* Byte-length of string zStop */
121326   int isEof;                      /* True if cursor is at EOF */
121327   sqlite3_int64 iRowid;           /* Current rowid */
121328
121329   int iCol;                       /* Current value of 'col' column */
121330   int nStat;                      /* Size of aStat[] array */
121331   struct Fts3auxColstats {
121332     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
121333     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
121334   } *aStat;
121335 };
121336
121337 /*
121338 ** Schema of the terms table.
121339 */
121340 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
121341
121342 /*
121343 ** This function does all the work for both the xConnect and xCreate methods.
121344 ** These tables have no persistent representation of their own, so xConnect
121345 ** and xCreate are identical operations.
121346 */
121347 static int fts3auxConnectMethod(
121348   sqlite3 *db,                    /* Database connection */
121349   void *pUnused,                  /* Unused */
121350   int argc,                       /* Number of elements in argv array */
121351   const char * const *argv,       /* xCreate/xConnect argument array */
121352   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
121353   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
121354 ){
121355   char const *zDb;                /* Name of database (e.g. "main") */
121356   char const *zFts3;              /* Name of fts3 table */
121357   int nDb;                        /* Result of strlen(zDb) */
121358   int nFts3;                      /* Result of strlen(zFts3) */
121359   int nByte;                      /* Bytes of space to allocate here */
121360   int rc;                         /* value returned by declare_vtab() */
121361   Fts3auxTable *p;                /* Virtual table object to return */
121362
121363   UNUSED_PARAMETER(pUnused);
121364
121365   /* The user should specify a single argument - the name of an fts3 table. */
121366   if( argc!=4 ){
121367     *pzErr = sqlite3_mprintf(
121368         "wrong number of arguments to fts4aux constructor"
121369     );
121370     return SQLITE_ERROR;
121371   }
121372
121373   zDb = argv[1]; 
121374   nDb = (int)strlen(zDb);
121375   zFts3 = argv[3];
121376   nFts3 = (int)strlen(zFts3);
121377
121378   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
121379   if( rc!=SQLITE_OK ) return rc;
121380
121381   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
121382   p = (Fts3auxTable *)sqlite3_malloc(nByte);
121383   if( !p ) return SQLITE_NOMEM;
121384   memset(p, 0, nByte);
121385
121386   p->pFts3Tab = (Fts3Table *)&p[1];
121387   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
121388   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
121389   p->pFts3Tab->db = db;
121390   p->pFts3Tab->nIndex = 1;
121391
121392   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
121393   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
121394   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
121395
121396   *ppVtab = (sqlite3_vtab *)p;
121397   return SQLITE_OK;
121398 }
121399
121400 /*
121401 ** This function does the work for both the xDisconnect and xDestroy methods.
121402 ** These tables have no persistent representation of their own, so xDisconnect
121403 ** and xDestroy are identical operations.
121404 */
121405 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
121406   Fts3auxTable *p = (Fts3auxTable *)pVtab;
121407   Fts3Table *pFts3 = p->pFts3Tab;
121408   int i;
121409
121410   /* Free any prepared statements held */
121411   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
121412     sqlite3_finalize(pFts3->aStmt[i]);
121413   }
121414   sqlite3_free(pFts3->zSegmentsTbl);
121415   sqlite3_free(p);
121416   return SQLITE_OK;
121417 }
121418
121419 #define FTS4AUX_EQ_CONSTRAINT 1
121420 #define FTS4AUX_GE_CONSTRAINT 2
121421 #define FTS4AUX_LE_CONSTRAINT 4
121422
121423 /*
121424 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
121425 */
121426 static int fts3auxBestIndexMethod(
121427   sqlite3_vtab *pVTab, 
121428   sqlite3_index_info *pInfo
121429 ){
121430   int i;
121431   int iEq = -1;
121432   int iGe = -1;
121433   int iLe = -1;
121434
121435   UNUSED_PARAMETER(pVTab);
121436
121437   /* This vtab delivers always results in "ORDER BY term ASC" order. */
121438   if( pInfo->nOrderBy==1 
121439    && pInfo->aOrderBy[0].iColumn==0 
121440    && pInfo->aOrderBy[0].desc==0
121441   ){
121442     pInfo->orderByConsumed = 1;
121443   }
121444
121445   /* Search for equality and range constraints on the "term" column. */
121446   for(i=0; i<pInfo->nConstraint; i++){
121447     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
121448       int op = pInfo->aConstraint[i].op;
121449       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
121450       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
121451       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
121452       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
121453       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
121454     }
121455   }
121456
121457   if( iEq>=0 ){
121458     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
121459     pInfo->aConstraintUsage[iEq].argvIndex = 1;
121460     pInfo->estimatedCost = 5;
121461   }else{
121462     pInfo->idxNum = 0;
121463     pInfo->estimatedCost = 20000;
121464     if( iGe>=0 ){
121465       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
121466       pInfo->aConstraintUsage[iGe].argvIndex = 1;
121467       pInfo->estimatedCost /= 2;
121468     }
121469     if( iLe>=0 ){
121470       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
121471       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
121472       pInfo->estimatedCost /= 2;
121473     }
121474   }
121475
121476   return SQLITE_OK;
121477 }
121478
121479 /*
121480 ** xOpen - Open a cursor.
121481 */
121482 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
121483   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
121484
121485   UNUSED_PARAMETER(pVTab);
121486
121487   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
121488   if( !pCsr ) return SQLITE_NOMEM;
121489   memset(pCsr, 0, sizeof(Fts3auxCursor));
121490
121491   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
121492   return SQLITE_OK;
121493 }
121494
121495 /*
121496 ** xClose - Close a cursor.
121497 */
121498 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
121499   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121500   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121501
121502   sqlite3Fts3SegmentsClose(pFts3);
121503   sqlite3Fts3SegReaderFinish(&pCsr->csr);
121504   sqlite3_free((void *)pCsr->filter.zTerm);
121505   sqlite3_free(pCsr->zStop);
121506   sqlite3_free(pCsr->aStat);
121507   sqlite3_free(pCsr);
121508   return SQLITE_OK;
121509 }
121510
121511 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
121512   if( nSize>pCsr->nStat ){
121513     struct Fts3auxColstats *aNew;
121514     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
121515         sizeof(struct Fts3auxColstats) * nSize
121516     );
121517     if( aNew==0 ) return SQLITE_NOMEM;
121518     memset(&aNew[pCsr->nStat], 0, 
121519         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
121520     );
121521     pCsr->aStat = aNew;
121522     pCsr->nStat = nSize;
121523   }
121524   return SQLITE_OK;
121525 }
121526
121527 /*
121528 ** xNext - Advance the cursor to the next row, if any.
121529 */
121530 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
121531   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121532   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121533   int rc;
121534
121535   /* Increment our pretend rowid value. */
121536   pCsr->iRowid++;
121537
121538   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
121539     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
121540   }
121541
121542   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
121543   if( rc==SQLITE_ROW ){
121544     int i = 0;
121545     int nDoclist = pCsr->csr.nDoclist;
121546     char *aDoclist = pCsr->csr.aDoclist;
121547     int iCol;
121548
121549     int eState = 0;
121550
121551     if( pCsr->zStop ){
121552       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
121553       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
121554       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
121555         pCsr->isEof = 1;
121556         return SQLITE_OK;
121557       }
121558     }
121559
121560     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
121561     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
121562     iCol = 0;
121563
121564     while( i<nDoclist ){
121565       sqlite3_int64 v = 0;
121566
121567       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
121568       switch( eState ){
121569         /* State 0. In this state the integer just read was a docid. */
121570         case 0:
121571           pCsr->aStat[0].nDoc++;
121572           eState = 1;
121573           iCol = 0;
121574           break;
121575
121576         /* State 1. In this state we are expecting either a 1, indicating
121577         ** that the following integer will be a column number, or the
121578         ** start of a position list for column 0.  
121579         ** 
121580         ** The only difference between state 1 and state 2 is that if the
121581         ** integer encountered in state 1 is not 0 or 1, then we need to
121582         ** increment the column 0 "nDoc" count for this term.
121583         */
121584         case 1:
121585           assert( iCol==0 );
121586           if( v>1 ){
121587             pCsr->aStat[1].nDoc++;
121588           }
121589           eState = 2;
121590           /* fall through */
121591
121592         case 2:
121593           if( v==0 ){       /* 0x00. Next integer will be a docid. */
121594             eState = 0;
121595           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
121596             eState = 3;
121597           }else{            /* 2 or greater. A position. */
121598             pCsr->aStat[iCol+1].nOcc++;
121599             pCsr->aStat[0].nOcc++;
121600           }
121601           break;
121602
121603         /* State 3. The integer just read is a column number. */
121604         default: assert( eState==3 );
121605           iCol = (int)v;
121606           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
121607           pCsr->aStat[iCol+1].nDoc++;
121608           eState = 2;
121609           break;
121610       }
121611     }
121612
121613     pCsr->iCol = 0;
121614     rc = SQLITE_OK;
121615   }else{
121616     pCsr->isEof = 1;
121617   }
121618   return rc;
121619 }
121620
121621 /*
121622 ** xFilter - Initialize a cursor to point at the start of its data.
121623 */
121624 static int fts3auxFilterMethod(
121625   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
121626   int idxNum,                     /* Strategy index */
121627   const char *idxStr,             /* Unused */
121628   int nVal,                       /* Number of elements in apVal */
121629   sqlite3_value **apVal           /* Arguments for the indexing scheme */
121630 ){
121631   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121632   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121633   int rc;
121634   int isScan;
121635
121636   UNUSED_PARAMETER(nVal);
121637   UNUSED_PARAMETER(idxStr);
121638
121639   assert( idxStr==0 );
121640   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
121641        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
121642        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
121643   );
121644   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
121645
121646   /* In case this cursor is being reused, close and zero it. */
121647   testcase(pCsr->filter.zTerm);
121648   sqlite3Fts3SegReaderFinish(&pCsr->csr);
121649   sqlite3_free((void *)pCsr->filter.zTerm);
121650   sqlite3_free(pCsr->aStat);
121651   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
121652
121653   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
121654   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
121655
121656   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
121657     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
121658     if( zStr ){
121659       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
121660       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
121661       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
121662     }
121663   }
121664   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
121665     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
121666     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
121667     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
121668     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
121669   }
121670
121671   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
121672       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
121673   );
121674   if( rc==SQLITE_OK ){
121675     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
121676   }
121677
121678   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
121679   return rc;
121680 }
121681
121682 /*
121683 ** xEof - Return true if the cursor is at EOF, or false otherwise.
121684 */
121685 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
121686   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121687   return pCsr->isEof;
121688 }
121689
121690 /*
121691 ** xColumn - Return a column value.
121692 */
121693 static int fts3auxColumnMethod(
121694   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121695   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
121696   int iCol                        /* Index of column to read value from */
121697 ){
121698   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
121699
121700   assert( p->isEof==0 );
121701   if( iCol==0 ){        /* Column "term" */
121702     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
121703   }else if( iCol==1 ){  /* Column "col" */
121704     if( p->iCol ){
121705       sqlite3_result_int(pContext, p->iCol-1);
121706     }else{
121707       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
121708     }
121709   }else if( iCol==2 ){  /* Column "documents" */
121710     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
121711   }else{                /* Column "occurrences" */
121712     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
121713   }
121714
121715   return SQLITE_OK;
121716 }
121717
121718 /*
121719 ** xRowid - Return the current rowid for the cursor.
121720 */
121721 static int fts3auxRowidMethod(
121722   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121723   sqlite_int64 *pRowid            /* OUT: Rowid value */
121724 ){
121725   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121726   *pRowid = pCsr->iRowid;
121727   return SQLITE_OK;
121728 }
121729
121730 /*
121731 ** Register the fts3aux module with database connection db. Return SQLITE_OK
121732 ** if successful or an error code if sqlite3_create_module() fails.
121733 */
121734 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
121735   static const sqlite3_module fts3aux_module = {
121736      0,                           /* iVersion      */
121737      fts3auxConnectMethod,        /* xCreate       */
121738      fts3auxConnectMethod,        /* xConnect      */
121739      fts3auxBestIndexMethod,      /* xBestIndex    */
121740      fts3auxDisconnectMethod,     /* xDisconnect   */
121741      fts3auxDisconnectMethod,     /* xDestroy      */
121742      fts3auxOpenMethod,           /* xOpen         */
121743      fts3auxCloseMethod,          /* xClose        */
121744      fts3auxFilterMethod,         /* xFilter       */
121745      fts3auxNextMethod,           /* xNext         */
121746      fts3auxEofMethod,            /* xEof          */
121747      fts3auxColumnMethod,         /* xColumn       */
121748      fts3auxRowidMethod,          /* xRowid        */
121749      0,                           /* xUpdate       */
121750      0,                           /* xBegin        */
121751      0,                           /* xSync         */
121752      0,                           /* xCommit       */
121753      0,                           /* xRollback     */
121754      0,                           /* xFindFunction */
121755      0,                           /* xRename       */
121756      0,                           /* xSavepoint    */
121757      0,                           /* xRelease      */
121758      0                            /* xRollbackTo   */
121759   };
121760   int rc;                         /* Return code */
121761
121762   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
121763   return rc;
121764 }
121765
121766 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
121767
121768 /************** End of fts3_aux.c ********************************************/
121769 /************** Begin file fts3_expr.c ***************************************/
121770 /*
121771 ** 2008 Nov 28
121772 **
121773 ** The author disclaims copyright to this source code.  In place of
121774 ** a legal notice, here is a blessing:
121775 **
121776 **    May you do good and not evil.
121777 **    May you find forgiveness for yourself and forgive others.
121778 **    May you share freely, never taking more than you give.
121779 **
121780 ******************************************************************************
121781 **
121782 ** This module contains code that implements a parser for fts3 query strings
121783 ** (the right-hand argument to the MATCH operator). Because the supported 
121784 ** syntax is relatively simple, the whole tokenizer/parser system is
121785 ** hand-coded. 
121786 */
121787 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121788
121789 /*
121790 ** By default, this module parses the legacy syntax that has been 
121791 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
121792 ** is defined, then it uses the new syntax. The differences between
121793 ** the new and the old syntaxes are:
121794 **
121795 **  a) The new syntax supports parenthesis. The old does not.
121796 **
121797 **  b) The new syntax supports the AND and NOT operators. The old does not.
121798 **
121799 **  c) The old syntax supports the "-" token qualifier. This is not 
121800 **     supported by the new syntax (it is replaced by the NOT operator).
121801 **
121802 **  d) When using the old syntax, the OR operator has a greater precedence
121803 **     than an implicit AND. When using the new, both implicity and explicit
121804 **     AND operators have a higher precedence than OR.
121805 **
121806 ** If compiled with SQLITE_TEST defined, then this module exports the
121807 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
121808 ** to zero causes the module to use the old syntax. If it is set to 
121809 ** non-zero the new syntax is activated. This is so both syntaxes can
121810 ** be tested using a single build of testfixture.
121811 **
121812 ** The following describes the syntax supported by the fts3 MATCH
121813 ** operator in a similar format to that used by the lemon parser
121814 ** generator. This module does not use actually lemon, it uses a
121815 ** custom parser.
121816 **
121817 **   query ::= andexpr (OR andexpr)*.
121818 **
121819 **   andexpr ::= notexpr (AND? notexpr)*.
121820 **
121821 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
121822 **   notexpr ::= LP query RP.
121823 **
121824 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
121825 **
121826 **   distance_opt ::= .
121827 **   distance_opt ::= / INTEGER.
121828 **
121829 **   phrase ::= TOKEN.
121830 **   phrase ::= COLUMN:TOKEN.
121831 **   phrase ::= "TOKEN TOKEN TOKEN...".
121832 */
121833
121834 #ifdef SQLITE_TEST
121835 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
121836 #else
121837 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
121838 #  define sqlite3_fts3_enable_parentheses 1
121839 # else
121840 #  define sqlite3_fts3_enable_parentheses 0
121841 # endif
121842 #endif
121843
121844 /*
121845 ** Default span for NEAR operators.
121846 */
121847 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
121848
121849 /* #include <string.h> */
121850 /* #include <assert.h> */
121851
121852 /*
121853 ** isNot:
121854 **   This variable is used by function getNextNode(). When getNextNode() is
121855 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
121856 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
121857 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
121858 **   zero.
121859 */
121860 typedef struct ParseContext ParseContext;
121861 struct ParseContext {
121862   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
121863   int iLangid;                        /* Language id used with tokenizer */
121864   const char **azCol;                 /* Array of column names for fts3 table */
121865   int bFts4;                          /* True to allow FTS4-only syntax */
121866   int nCol;                           /* Number of entries in azCol[] */
121867   int iDefaultCol;                    /* Default column to query */
121868   int isNot;                          /* True if getNextNode() sees a unary - */
121869   sqlite3_context *pCtx;              /* Write error message here */
121870   int nNest;                          /* Number of nested brackets */
121871 };
121872
121873 /*
121874 ** This function is equivalent to the standard isspace() function. 
121875 **
121876 ** The standard isspace() can be awkward to use safely, because although it
121877 ** is defined to accept an argument of type int, its behaviour when passed
121878 ** an integer that falls outside of the range of the unsigned char type
121879 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
121880 ** is defined to accept an argument of type char, and always returns 0 for
121881 ** any values that fall outside of the range of the unsigned char type (i.e.
121882 ** negative values).
121883 */
121884 static int fts3isspace(char c){
121885   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
121886 }
121887
121888 /*
121889 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
121890 ** zero the memory before returning a pointer to it. If unsuccessful, 
121891 ** return NULL.
121892 */
121893 static void *fts3MallocZero(int nByte){
121894   void *pRet = sqlite3_malloc(nByte);
121895   if( pRet ) memset(pRet, 0, nByte);
121896   return pRet;
121897 }
121898
121899 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
121900   sqlite3_tokenizer *pTokenizer,
121901   int iLangid,
121902   const char *z,
121903   int n,
121904   sqlite3_tokenizer_cursor **ppCsr
121905 ){
121906   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
121907   sqlite3_tokenizer_cursor *pCsr = 0;
121908   int rc;
121909
121910   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
121911   assert( rc==SQLITE_OK || pCsr==0 );
121912   if( rc==SQLITE_OK ){
121913     pCsr->pTokenizer = pTokenizer;
121914     if( pModule->iVersion>=1 ){
121915       rc = pModule->xLanguageid(pCsr, iLangid);
121916       if( rc!=SQLITE_OK ){
121917         pModule->xClose(pCsr);
121918         pCsr = 0;
121919       }
121920     }
121921   }
121922   *ppCsr = pCsr;
121923   return rc;
121924 }
121925
121926
121927 /*
121928 ** Extract the next token from buffer z (length n) using the tokenizer
121929 ** and other information (column names etc.) in pParse. Create an Fts3Expr
121930 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
121931 ** single token and set *ppExpr to point to it. If the end of the buffer is
121932 ** reached before a token is found, set *ppExpr to zero. It is the
121933 ** responsibility of the caller to eventually deallocate the allocated 
121934 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
121935 **
121936 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
121937 ** fails.
121938 */
121939 static int getNextToken(
121940   ParseContext *pParse,                   /* fts3 query parse context */
121941   int iCol,                               /* Value for Fts3Phrase.iColumn */
121942   const char *z, int n,                   /* Input string */
121943   Fts3Expr **ppExpr,                      /* OUT: expression */
121944   int *pnConsumed                         /* OUT: Number of bytes consumed */
121945 ){
121946   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
121947   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
121948   int rc;
121949   sqlite3_tokenizer_cursor *pCursor;
121950   Fts3Expr *pRet = 0;
121951   int nConsumed = 0;
121952
121953   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
121954   if( rc==SQLITE_OK ){
121955     const char *zToken;
121956     int nToken, iStart, iEnd, iPosition;
121957     int nByte;                               /* total space to allocate */
121958
121959     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
121960     if( rc==SQLITE_OK ){
121961       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
121962       pRet = (Fts3Expr *)fts3MallocZero(nByte);
121963       if( !pRet ){
121964         rc = SQLITE_NOMEM;
121965       }else{
121966         pRet->eType = FTSQUERY_PHRASE;
121967         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
121968         pRet->pPhrase->nToken = 1;
121969         pRet->pPhrase->iColumn = iCol;
121970         pRet->pPhrase->aToken[0].n = nToken;
121971         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
121972         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
121973
121974         if( iEnd<n && z[iEnd]=='*' ){
121975           pRet->pPhrase->aToken[0].isPrefix = 1;
121976           iEnd++;
121977         }
121978
121979         while( 1 ){
121980           if( !sqlite3_fts3_enable_parentheses 
121981            && iStart>0 && z[iStart-1]=='-' 
121982           ){
121983             pParse->isNot = 1;
121984             iStart--;
121985           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
121986             pRet->pPhrase->aToken[0].bFirst = 1;
121987             iStart--;
121988           }else{
121989             break;
121990           }
121991         }
121992
121993       }
121994       nConsumed = iEnd;
121995     }
121996
121997     pModule->xClose(pCursor);
121998   }
121999   
122000   *pnConsumed = nConsumed;
122001   *ppExpr = pRet;
122002   return rc;
122003 }
122004
122005
122006 /*
122007 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
122008 ** then free the old allocation.
122009 */
122010 static void *fts3ReallocOrFree(void *pOrig, int nNew){
122011   void *pRet = sqlite3_realloc(pOrig, nNew);
122012   if( !pRet ){
122013     sqlite3_free(pOrig);
122014   }
122015   return pRet;
122016 }
122017
122018 /*
122019 ** Buffer zInput, length nInput, contains the contents of a quoted string
122020 ** that appeared as part of an fts3 query expression. Neither quote character
122021 ** is included in the buffer. This function attempts to tokenize the entire
122022 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
122023 ** containing the results.
122024 **
122025 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
122026 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
122027 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
122028 ** to 0.
122029 */
122030 static int getNextString(
122031   ParseContext *pParse,                   /* fts3 query parse context */
122032   const char *zInput, int nInput,         /* Input string */
122033   Fts3Expr **ppExpr                       /* OUT: expression */
122034 ){
122035   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
122036   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122037   int rc;
122038   Fts3Expr *p = 0;
122039   sqlite3_tokenizer_cursor *pCursor = 0;
122040   char *zTemp = 0;
122041   int nTemp = 0;
122042
122043   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
122044   int nToken = 0;
122045
122046   /* The final Fts3Expr data structure, including the Fts3Phrase,
122047   ** Fts3PhraseToken structures token buffers are all stored as a single 
122048   ** allocation so that the expression can be freed with a single call to
122049   ** sqlite3_free(). Setting this up requires a two pass approach.
122050   **
122051   ** The first pass, in the block below, uses a tokenizer cursor to iterate
122052   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
122053   ** to assemble data in two dynamic buffers:
122054   **
122055   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
122056   **             structure, followed by the array of Fts3PhraseToken 
122057   **             structures. This pass only populates the Fts3PhraseToken array.
122058   **
122059   **   Buffer zTemp: Contains copies of all tokens.
122060   **
122061   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
122062   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
122063   ** structures.
122064   */
122065   rc = sqlite3Fts3OpenTokenizer(
122066       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
122067   if( rc==SQLITE_OK ){
122068     int ii;
122069     for(ii=0; rc==SQLITE_OK; ii++){
122070       const char *zByte;
122071       int nByte, iBegin, iEnd, iPos;
122072       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
122073       if( rc==SQLITE_OK ){
122074         Fts3PhraseToken *pToken;
122075
122076         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
122077         if( !p ) goto no_mem;
122078
122079         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
122080         if( !zTemp ) goto no_mem;
122081
122082         assert( nToken==ii );
122083         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
122084         memset(pToken, 0, sizeof(Fts3PhraseToken));
122085
122086         memcpy(&zTemp[nTemp], zByte, nByte);
122087         nTemp += nByte;
122088
122089         pToken->n = nByte;
122090         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
122091         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
122092         nToken = ii+1;
122093       }
122094     }
122095
122096     pModule->xClose(pCursor);
122097     pCursor = 0;
122098   }
122099
122100   if( rc==SQLITE_DONE ){
122101     int jj;
122102     char *zBuf = 0;
122103
122104     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
122105     if( !p ) goto no_mem;
122106     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
122107     p->eType = FTSQUERY_PHRASE;
122108     p->pPhrase = (Fts3Phrase *)&p[1];
122109     p->pPhrase->iColumn = pParse->iDefaultCol;
122110     p->pPhrase->nToken = nToken;
122111
122112     zBuf = (char *)&p->pPhrase->aToken[nToken];
122113     if( zTemp ){
122114       memcpy(zBuf, zTemp, nTemp);
122115       sqlite3_free(zTemp);
122116     }else{
122117       assert( nTemp==0 );
122118     }
122119
122120     for(jj=0; jj<p->pPhrase->nToken; jj++){
122121       p->pPhrase->aToken[jj].z = zBuf;
122122       zBuf += p->pPhrase->aToken[jj].n;
122123     }
122124     rc = SQLITE_OK;
122125   }
122126
122127   *ppExpr = p;
122128   return rc;
122129 no_mem:
122130
122131   if( pCursor ){
122132     pModule->xClose(pCursor);
122133   }
122134   sqlite3_free(zTemp);
122135   sqlite3_free(p);
122136   *ppExpr = 0;
122137   return SQLITE_NOMEM;
122138 }
122139
122140 /*
122141 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
122142 ** call fts3ExprParse(). So this forward declaration is required.
122143 */
122144 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
122145
122146 /*
122147 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
122148 ** structure, or set to 0 if the end of the input buffer is reached.
122149 **
122150 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
122151 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
122152 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
122153 */
122154 static int getNextNode(
122155   ParseContext *pParse,                   /* fts3 query parse context */
122156   const char *z, int n,                   /* Input string */
122157   Fts3Expr **ppExpr,                      /* OUT: expression */
122158   int *pnConsumed                         /* OUT: Number of bytes consumed */
122159 ){
122160   static const struct Fts3Keyword {
122161     char *z;                              /* Keyword text */
122162     unsigned char n;                      /* Length of the keyword */
122163     unsigned char parenOnly;              /* Only valid in paren mode */
122164     unsigned char eType;                  /* Keyword code */
122165   } aKeyword[] = {
122166     { "OR" ,  2, 0, FTSQUERY_OR   },
122167     { "AND",  3, 1, FTSQUERY_AND  },
122168     { "NOT",  3, 1, FTSQUERY_NOT  },
122169     { "NEAR", 4, 0, FTSQUERY_NEAR }
122170   };
122171   int ii;
122172   int iCol;
122173   int iColLen;
122174   int rc;
122175   Fts3Expr *pRet = 0;
122176
122177   const char *zInput = z;
122178   int nInput = n;
122179
122180   pParse->isNot = 0;
122181
122182   /* Skip over any whitespace before checking for a keyword, an open or
122183   ** close bracket, or a quoted string. 
122184   */
122185   while( nInput>0 && fts3isspace(*zInput) ){
122186     nInput--;
122187     zInput++;
122188   }
122189   if( nInput==0 ){
122190     return SQLITE_DONE;
122191   }
122192
122193   /* See if we are dealing with a keyword. */
122194   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
122195     const struct Fts3Keyword *pKey = &aKeyword[ii];
122196
122197     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
122198       continue;
122199     }
122200
122201     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
122202       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
122203       int nKey = pKey->n;
122204       char cNext;
122205
122206       /* If this is a "NEAR" keyword, check for an explicit nearness. */
122207       if( pKey->eType==FTSQUERY_NEAR ){
122208         assert( nKey==4 );
122209         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
122210           nNear = 0;
122211           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
122212             nNear = nNear * 10 + (zInput[nKey] - '0');
122213           }
122214         }
122215       }
122216
122217       /* At this point this is probably a keyword. But for that to be true,
122218       ** the next byte must contain either whitespace, an open or close
122219       ** parenthesis, a quote character, or EOF. 
122220       */
122221       cNext = zInput[nKey];
122222       if( fts3isspace(cNext) 
122223        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
122224       ){
122225         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
122226         if( !pRet ){
122227           return SQLITE_NOMEM;
122228         }
122229         pRet->eType = pKey->eType;
122230         pRet->nNear = nNear;
122231         *ppExpr = pRet;
122232         *pnConsumed = (int)((zInput - z) + nKey);
122233         return SQLITE_OK;
122234       }
122235
122236       /* Turns out that wasn't a keyword after all. This happens if the
122237       ** user has supplied a token such as "ORacle". Continue.
122238       */
122239     }
122240   }
122241
122242   /* Check for an open bracket. */
122243   if( sqlite3_fts3_enable_parentheses ){
122244     if( *zInput=='(' ){
122245       int nConsumed;
122246       pParse->nNest++;
122247       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
122248       if( rc==SQLITE_OK && !*ppExpr ){
122249         rc = SQLITE_DONE;
122250       }
122251       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
122252       return rc;
122253     }
122254   
122255     /* Check for a close bracket. */
122256     if( *zInput==')' ){
122257       pParse->nNest--;
122258       *pnConsumed = (int)((zInput - z) + 1);
122259       return SQLITE_DONE;
122260     }
122261   }
122262
122263   /* See if we are dealing with a quoted phrase. If this is the case, then
122264   ** search for the closing quote and pass the whole string to getNextString()
122265   ** for processing. This is easy to do, as fts3 has no syntax for escaping
122266   ** a quote character embedded in a string.
122267   */
122268   if( *zInput=='"' ){
122269     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
122270     *pnConsumed = (int)((zInput - z) + ii + 1);
122271     if( ii==nInput ){
122272       return SQLITE_ERROR;
122273     }
122274     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
122275   }
122276
122277
122278   /* If control flows to this point, this must be a regular token, or 
122279   ** the end of the input. Read a regular token using the sqlite3_tokenizer
122280   ** interface. Before doing so, figure out if there is an explicit
122281   ** column specifier for the token. 
122282   **
122283   ** TODO: Strangely, it is not possible to associate a column specifier
122284   ** with a quoted phrase, only with a single token. Not sure if this was
122285   ** an implementation artifact or an intentional decision when fts3 was
122286   ** first implemented. Whichever it was, this module duplicates the 
122287   ** limitation.
122288   */
122289   iCol = pParse->iDefaultCol;
122290   iColLen = 0;
122291   for(ii=0; ii<pParse->nCol; ii++){
122292     const char *zStr = pParse->azCol[ii];
122293     int nStr = (int)strlen(zStr);
122294     if( nInput>nStr && zInput[nStr]==':' 
122295      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
122296     ){
122297       iCol = ii;
122298       iColLen = (int)((zInput - z) + nStr + 1);
122299       break;
122300     }
122301   }
122302   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
122303   *pnConsumed += iColLen;
122304   return rc;
122305 }
122306
122307 /*
122308 ** The argument is an Fts3Expr structure for a binary operator (any type
122309 ** except an FTSQUERY_PHRASE). Return an integer value representing the
122310 ** precedence of the operator. Lower values have a higher precedence (i.e.
122311 ** group more tightly). For example, in the C language, the == operator
122312 ** groups more tightly than ||, and would therefore have a higher precedence.
122313 **
122314 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
122315 ** is defined), the order of the operators in precedence from highest to
122316 ** lowest is:
122317 **
122318 **   NEAR
122319 **   NOT
122320 **   AND (including implicit ANDs)
122321 **   OR
122322 **
122323 ** Note that when using the old query syntax, the OR operator has a higher
122324 ** precedence than the AND operator.
122325 */
122326 static int opPrecedence(Fts3Expr *p){
122327   assert( p->eType!=FTSQUERY_PHRASE );
122328   if( sqlite3_fts3_enable_parentheses ){
122329     return p->eType;
122330   }else if( p->eType==FTSQUERY_NEAR ){
122331     return 1;
122332   }else if( p->eType==FTSQUERY_OR ){
122333     return 2;
122334   }
122335   assert( p->eType==FTSQUERY_AND );
122336   return 3;
122337 }
122338
122339 /*
122340 ** Argument ppHead contains a pointer to the current head of a query 
122341 ** expression tree being parsed. pPrev is the expression node most recently
122342 ** inserted into the tree. This function adds pNew, which is always a binary
122343 ** operator node, into the expression tree based on the relative precedence
122344 ** of pNew and the existing nodes of the tree. This may result in the head
122345 ** of the tree changing, in which case *ppHead is set to the new root node.
122346 */
122347 static void insertBinaryOperator(
122348   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
122349   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
122350   Fts3Expr *pNew           /* New binary node to insert into expression tree */
122351 ){
122352   Fts3Expr *pSplit = pPrev;
122353   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
122354     pSplit = pSplit->pParent;
122355   }
122356
122357   if( pSplit->pParent ){
122358     assert( pSplit->pParent->pRight==pSplit );
122359     pSplit->pParent->pRight = pNew;
122360     pNew->pParent = pSplit->pParent;
122361   }else{
122362     *ppHead = pNew;
122363   }
122364   pNew->pLeft = pSplit;
122365   pSplit->pParent = pNew;
122366 }
122367
122368 /*
122369 ** Parse the fts3 query expression found in buffer z, length n. This function
122370 ** returns either when the end of the buffer is reached or an unmatched 
122371 ** closing bracket - ')' - is encountered.
122372 **
122373 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
122374 ** parsed form of the expression and *pnConsumed is set to the number of
122375 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
122376 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
122377 */
122378 static int fts3ExprParse(
122379   ParseContext *pParse,                   /* fts3 query parse context */
122380   const char *z, int n,                   /* Text of MATCH query */
122381   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
122382   int *pnConsumed                         /* OUT: Number of bytes consumed */
122383 ){
122384   Fts3Expr *pRet = 0;
122385   Fts3Expr *pPrev = 0;
122386   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
122387   int nIn = n;
122388   const char *zIn = z;
122389   int rc = SQLITE_OK;
122390   int isRequirePhrase = 1;
122391
122392   while( rc==SQLITE_OK ){
122393     Fts3Expr *p = 0;
122394     int nByte = 0;
122395     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
122396     if( rc==SQLITE_OK ){
122397       int isPhrase;
122398
122399       if( !sqlite3_fts3_enable_parentheses 
122400        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
122401       ){
122402         /* Create an implicit NOT operator. */
122403         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
122404         if( !pNot ){
122405           sqlite3Fts3ExprFree(p);
122406           rc = SQLITE_NOMEM;
122407           goto exprparse_out;
122408         }
122409         pNot->eType = FTSQUERY_NOT;
122410         pNot->pRight = p;
122411         if( pNotBranch ){
122412           pNot->pLeft = pNotBranch;
122413         }
122414         pNotBranch = pNot;
122415         p = pPrev;
122416       }else{
122417         int eType = p->eType;
122418         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
122419
122420         /* The isRequirePhrase variable is set to true if a phrase or
122421         ** an expression contained in parenthesis is required. If a
122422         ** binary operator (AND, OR, NOT or NEAR) is encounted when
122423         ** isRequirePhrase is set, this is a syntax error.
122424         */
122425         if( !isPhrase && isRequirePhrase ){
122426           sqlite3Fts3ExprFree(p);
122427           rc = SQLITE_ERROR;
122428           goto exprparse_out;
122429         }
122430   
122431         if( isPhrase && !isRequirePhrase ){
122432           /* Insert an implicit AND operator. */
122433           Fts3Expr *pAnd;
122434           assert( pRet && pPrev );
122435           pAnd = fts3MallocZero(sizeof(Fts3Expr));
122436           if( !pAnd ){
122437             sqlite3Fts3ExprFree(p);
122438             rc = SQLITE_NOMEM;
122439             goto exprparse_out;
122440           }
122441           pAnd->eType = FTSQUERY_AND;
122442           insertBinaryOperator(&pRet, pPrev, pAnd);
122443           pPrev = pAnd;
122444         }
122445
122446         /* This test catches attempts to make either operand of a NEAR
122447         ** operator something other than a phrase. For example, either of
122448         ** the following:
122449         **
122450         **    (bracketed expression) NEAR phrase
122451         **    phrase NEAR (bracketed expression)
122452         **
122453         ** Return an error in either case.
122454         */
122455         if( pPrev && (
122456             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
122457          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
122458         )){
122459           sqlite3Fts3ExprFree(p);
122460           rc = SQLITE_ERROR;
122461           goto exprparse_out;
122462         }
122463   
122464         if( isPhrase ){
122465           if( pRet ){
122466             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
122467             pPrev->pRight = p;
122468             p->pParent = pPrev;
122469           }else{
122470             pRet = p;
122471           }
122472         }else{
122473           insertBinaryOperator(&pRet, pPrev, p);
122474         }
122475         isRequirePhrase = !isPhrase;
122476       }
122477       assert( nByte>0 );
122478     }
122479     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
122480     nIn -= nByte;
122481     zIn += nByte;
122482     pPrev = p;
122483   }
122484
122485   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
122486     rc = SQLITE_ERROR;
122487   }
122488
122489   if( rc==SQLITE_DONE ){
122490     rc = SQLITE_OK;
122491     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
122492       if( !pRet ){
122493         rc = SQLITE_ERROR;
122494       }else{
122495         Fts3Expr *pIter = pNotBranch;
122496         while( pIter->pLeft ){
122497           pIter = pIter->pLeft;
122498         }
122499         pIter->pLeft = pRet;
122500         pRet = pNotBranch;
122501       }
122502     }
122503   }
122504   *pnConsumed = n - nIn;
122505
122506 exprparse_out:
122507   if( rc!=SQLITE_OK ){
122508     sqlite3Fts3ExprFree(pRet);
122509     sqlite3Fts3ExprFree(pNotBranch);
122510     pRet = 0;
122511   }
122512   *ppExpr = pRet;
122513   return rc;
122514 }
122515
122516 /*
122517 ** Parameters z and n contain a pointer to and length of a buffer containing
122518 ** an fts3 query expression, respectively. This function attempts to parse the
122519 ** query expression and create a tree of Fts3Expr structures representing the
122520 ** parsed expression. If successful, *ppExpr is set to point to the head
122521 ** of the parsed expression tree and SQLITE_OK is returned. If an error
122522 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
122523 ** error) is returned and *ppExpr is set to 0.
122524 **
122525 ** If parameter n is a negative number, then z is assumed to point to a
122526 ** nul-terminated string and the length is determined using strlen().
122527 **
122528 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
122529 ** use to normalize query tokens while parsing the expression. The azCol[]
122530 ** array, which is assumed to contain nCol entries, should contain the names
122531 ** of each column in the target fts3 table, in order from left to right. 
122532 ** Column names must be nul-terminated strings.
122533 **
122534 ** The iDefaultCol parameter should be passed the index of the table column
122535 ** that appears on the left-hand-side of the MATCH operator (the default
122536 ** column to match against for tokens for which a column name is not explicitly
122537 ** specified as part of the query string), or -1 if tokens may by default
122538 ** match any table column.
122539 */
122540 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
122541   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
122542   int iLangid,                        /* Language id for tokenizer */
122543   char **azCol,                       /* Array of column names for fts3 table */
122544   int bFts4,                          /* True to allow FTS4-only syntax */
122545   int nCol,                           /* Number of entries in azCol[] */
122546   int iDefaultCol,                    /* Default column to query */
122547   const char *z, int n,               /* Text of MATCH query */
122548   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
122549 ){
122550   int nParsed;
122551   int rc;
122552   ParseContext sParse;
122553
122554   memset(&sParse, 0, sizeof(ParseContext));
122555   sParse.pTokenizer = pTokenizer;
122556   sParse.iLangid = iLangid;
122557   sParse.azCol = (const char **)azCol;
122558   sParse.nCol = nCol;
122559   sParse.iDefaultCol = iDefaultCol;
122560   sParse.bFts4 = bFts4;
122561   if( z==0 ){
122562     *ppExpr = 0;
122563     return SQLITE_OK;
122564   }
122565   if( n<0 ){
122566     n = (int)strlen(z);
122567   }
122568   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
122569
122570   /* Check for mismatched parenthesis */
122571   if( rc==SQLITE_OK && sParse.nNest ){
122572     rc = SQLITE_ERROR;
122573     sqlite3Fts3ExprFree(*ppExpr);
122574     *ppExpr = 0;
122575   }
122576
122577   return rc;
122578 }
122579
122580 /*
122581 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
122582 */
122583 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
122584   if( p ){
122585     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
122586     sqlite3Fts3ExprFree(p->pLeft);
122587     sqlite3Fts3ExprFree(p->pRight);
122588     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
122589     sqlite3_free(p->aMI);
122590     sqlite3_free(p);
122591   }
122592 }
122593
122594 /****************************************************************************
122595 *****************************************************************************
122596 ** Everything after this point is just test code.
122597 */
122598
122599 #ifdef SQLITE_TEST
122600
122601 /* #include <stdio.h> */
122602
122603 /*
122604 ** Function to query the hash-table of tokenizers (see README.tokenizers).
122605 */
122606 static int queryTestTokenizer(
122607   sqlite3 *db, 
122608   const char *zName,  
122609   const sqlite3_tokenizer_module **pp
122610 ){
122611   int rc;
122612   sqlite3_stmt *pStmt;
122613   const char zSql[] = "SELECT fts3_tokenizer(?)";
122614
122615   *pp = 0;
122616   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122617   if( rc!=SQLITE_OK ){
122618     return rc;
122619   }
122620
122621   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
122622   if( SQLITE_ROW==sqlite3_step(pStmt) ){
122623     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
122624       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
122625     }
122626   }
122627
122628   return sqlite3_finalize(pStmt);
122629 }
122630
122631 /*
122632 ** Return a pointer to a buffer containing a text representation of the
122633 ** expression passed as the first argument. The buffer is obtained from
122634 ** sqlite3_malloc(). It is the responsibility of the caller to use 
122635 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
122636 ** NULL is returned.
122637 **
122638 ** If the second argument is not NULL, then its contents are prepended to 
122639 ** the returned expression text and then freed using sqlite3_free().
122640 */
122641 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
122642   switch( pExpr->eType ){
122643     case FTSQUERY_PHRASE: {
122644       Fts3Phrase *pPhrase = pExpr->pPhrase;
122645       int i;
122646       zBuf = sqlite3_mprintf(
122647           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
122648       for(i=0; zBuf && i<pPhrase->nToken; i++){
122649         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
122650             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
122651             (pPhrase->aToken[i].isPrefix?"+":"")
122652         );
122653       }
122654       return zBuf;
122655     }
122656
122657     case FTSQUERY_NEAR:
122658       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
122659       break;
122660     case FTSQUERY_NOT:
122661       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
122662       break;
122663     case FTSQUERY_AND:
122664       zBuf = sqlite3_mprintf("%zAND ", zBuf);
122665       break;
122666     case FTSQUERY_OR:
122667       zBuf = sqlite3_mprintf("%zOR ", zBuf);
122668       break;
122669   }
122670
122671   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
122672   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
122673   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
122674
122675   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
122676   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
122677
122678   return zBuf;
122679 }
122680
122681 /*
122682 ** This is the implementation of a scalar SQL function used to test the 
122683 ** expression parser. It should be called as follows:
122684 **
122685 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
122686 **
122687 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
122688 ** to parse the query expression (see README.tokenizers). The second argument
122689 ** is the query expression to parse. Each subsequent argument is the name
122690 ** of a column of the fts3 table that the query expression may refer to.
122691 ** For example:
122692 **
122693 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
122694 */
122695 static void fts3ExprTest(
122696   sqlite3_context *context,
122697   int argc,
122698   sqlite3_value **argv
122699 ){
122700   sqlite3_tokenizer_module const *pModule = 0;
122701   sqlite3_tokenizer *pTokenizer = 0;
122702   int rc;
122703   char **azCol = 0;
122704   const char *zExpr;
122705   int nExpr;
122706   int nCol;
122707   int ii;
122708   Fts3Expr *pExpr;
122709   char *zBuf = 0;
122710   sqlite3 *db = sqlite3_context_db_handle(context);
122711
122712   if( argc<3 ){
122713     sqlite3_result_error(context, 
122714         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
122715     );
122716     return;
122717   }
122718
122719   rc = queryTestTokenizer(db,
122720                           (const char *)sqlite3_value_text(argv[0]), &pModule);
122721   if( rc==SQLITE_NOMEM ){
122722     sqlite3_result_error_nomem(context);
122723     goto exprtest_out;
122724   }else if( !pModule ){
122725     sqlite3_result_error(context, "No such tokenizer module", -1);
122726     goto exprtest_out;
122727   }
122728
122729   rc = pModule->xCreate(0, 0, &pTokenizer);
122730   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
122731   if( rc==SQLITE_NOMEM ){
122732     sqlite3_result_error_nomem(context);
122733     goto exprtest_out;
122734   }
122735   pTokenizer->pModule = pModule;
122736
122737   zExpr = (const char *)sqlite3_value_text(argv[1]);
122738   nExpr = sqlite3_value_bytes(argv[1]);
122739   nCol = argc-2;
122740   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
122741   if( !azCol ){
122742     sqlite3_result_error_nomem(context);
122743     goto exprtest_out;
122744   }
122745   for(ii=0; ii<nCol; ii++){
122746     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
122747   }
122748
122749   rc = sqlite3Fts3ExprParse(
122750       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
122751   );
122752   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
122753     sqlite3_result_error(context, "Error parsing expression", -1);
122754   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
122755     sqlite3_result_error_nomem(context);
122756   }else{
122757     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
122758     sqlite3_free(zBuf);
122759   }
122760
122761   sqlite3Fts3ExprFree(pExpr);
122762
122763 exprtest_out:
122764   if( pModule && pTokenizer ){
122765     rc = pModule->xDestroy(pTokenizer);
122766   }
122767   sqlite3_free(azCol);
122768 }
122769
122770 /*
122771 ** Register the query expression parser test function fts3_exprtest() 
122772 ** with database connection db. 
122773 */
122774 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
122775   return sqlite3_create_function(
122776       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
122777   );
122778 }
122779
122780 #endif
122781 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122782
122783 /************** End of fts3_expr.c *******************************************/
122784 /************** Begin file fts3_hash.c ***************************************/
122785 /*
122786 ** 2001 September 22
122787 **
122788 ** The author disclaims copyright to this source code.  In place of
122789 ** a legal notice, here is a blessing:
122790 **
122791 **    May you do good and not evil.
122792 **    May you find forgiveness for yourself and forgive others.
122793 **    May you share freely, never taking more than you give.
122794 **
122795 *************************************************************************
122796 ** This is the implementation of generic hash-tables used in SQLite.
122797 ** We've modified it slightly to serve as a standalone hash table
122798 ** implementation for the full-text indexing module.
122799 */
122800
122801 /*
122802 ** The code in this file is only compiled if:
122803 **
122804 **     * The FTS3 module is being built as an extension
122805 **       (in which case SQLITE_CORE is not defined), or
122806 **
122807 **     * The FTS3 module is being built into the core of
122808 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
122809 */
122810 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122811
122812 /* #include <assert.h> */
122813 /* #include <stdlib.h> */
122814 /* #include <string.h> */
122815
122816
122817 /*
122818 ** Malloc and Free functions
122819 */
122820 static void *fts3HashMalloc(int n){
122821   void *p = sqlite3_malloc(n);
122822   if( p ){
122823     memset(p, 0, n);
122824   }
122825   return p;
122826 }
122827 static void fts3HashFree(void *p){
122828   sqlite3_free(p);
122829 }
122830
122831 /* Turn bulk memory into a hash table object by initializing the
122832 ** fields of the Hash structure.
122833 **
122834 ** "pNew" is a pointer to the hash table that is to be initialized.
122835 ** keyClass is one of the constants 
122836 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
122837 ** determines what kind of key the hash table will use.  "copyKey" is
122838 ** true if the hash table should make its own private copy of keys and
122839 ** false if it should just use the supplied pointer.
122840 */
122841 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
122842   assert( pNew!=0 );
122843   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
122844   pNew->keyClass = keyClass;
122845   pNew->copyKey = copyKey;
122846   pNew->first = 0;
122847   pNew->count = 0;
122848   pNew->htsize = 0;
122849   pNew->ht = 0;
122850 }
122851
122852 /* Remove all entries from a hash table.  Reclaim all memory.
122853 ** Call this routine to delete a hash table or to reset a hash table
122854 ** to the empty state.
122855 */
122856 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
122857   Fts3HashElem *elem;         /* For looping over all elements of the table */
122858
122859   assert( pH!=0 );
122860   elem = pH->first;
122861   pH->first = 0;
122862   fts3HashFree(pH->ht);
122863   pH->ht = 0;
122864   pH->htsize = 0;
122865   while( elem ){
122866     Fts3HashElem *next_elem = elem->next;
122867     if( pH->copyKey && elem->pKey ){
122868       fts3HashFree(elem->pKey);
122869     }
122870     fts3HashFree(elem);
122871     elem = next_elem;
122872   }
122873   pH->count = 0;
122874 }
122875
122876 /*
122877 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
122878 */
122879 static int fts3StrHash(const void *pKey, int nKey){
122880   const char *z = (const char *)pKey;
122881   int h = 0;
122882   if( nKey<=0 ) nKey = (int) strlen(z);
122883   while( nKey > 0  ){
122884     h = (h<<3) ^ h ^ *z++;
122885     nKey--;
122886   }
122887   return h & 0x7fffffff;
122888 }
122889 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122890   if( n1!=n2 ) return 1;
122891   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
122892 }
122893
122894 /*
122895 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
122896 */
122897 static int fts3BinHash(const void *pKey, int nKey){
122898   int h = 0;
122899   const char *z = (const char *)pKey;
122900   while( nKey-- > 0 ){
122901     h = (h<<3) ^ h ^ *(z++);
122902   }
122903   return h & 0x7fffffff;
122904 }
122905 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122906   if( n1!=n2 ) return 1;
122907   return memcmp(pKey1,pKey2,n1);
122908 }
122909
122910 /*
122911 ** Return a pointer to the appropriate hash function given the key class.
122912 **
122913 ** The C syntax in this function definition may be unfamilar to some 
122914 ** programmers, so we provide the following additional explanation:
122915 **
122916 ** The name of the function is "ftsHashFunction".  The function takes a
122917 ** single parameter "keyClass".  The return value of ftsHashFunction()
122918 ** is a pointer to another function.  Specifically, the return value
122919 ** of ftsHashFunction() is a pointer to a function that takes two parameters
122920 ** with types "const void*" and "int" and returns an "int".
122921 */
122922 static int (*ftsHashFunction(int keyClass))(const void*,int){
122923   if( keyClass==FTS3_HASH_STRING ){
122924     return &fts3StrHash;
122925   }else{
122926     assert( keyClass==FTS3_HASH_BINARY );
122927     return &fts3BinHash;
122928   }
122929 }
122930
122931 /*
122932 ** Return a pointer to the appropriate hash function given the key class.
122933 **
122934 ** For help in interpreted the obscure C code in the function definition,
122935 ** see the header comment on the previous function.
122936 */
122937 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
122938   if( keyClass==FTS3_HASH_STRING ){
122939     return &fts3StrCompare;
122940   }else{
122941     assert( keyClass==FTS3_HASH_BINARY );
122942     return &fts3BinCompare;
122943   }
122944 }
122945
122946 /* Link an element into the hash table
122947 */
122948 static void fts3HashInsertElement(
122949   Fts3Hash *pH,            /* The complete hash table */
122950   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
122951   Fts3HashElem *pNew       /* The element to be inserted */
122952 ){
122953   Fts3HashElem *pHead;     /* First element already in pEntry */
122954   pHead = pEntry->chain;
122955   if( pHead ){
122956     pNew->next = pHead;
122957     pNew->prev = pHead->prev;
122958     if( pHead->prev ){ pHead->prev->next = pNew; }
122959     else             { pH->first = pNew; }
122960     pHead->prev = pNew;
122961   }else{
122962     pNew->next = pH->first;
122963     if( pH->first ){ pH->first->prev = pNew; }
122964     pNew->prev = 0;
122965     pH->first = pNew;
122966   }
122967   pEntry->count++;
122968   pEntry->chain = pNew;
122969 }
122970
122971
122972 /* Resize the hash table so that it cantains "new_size" buckets.
122973 ** "new_size" must be a power of 2.  The hash table might fail 
122974 ** to resize if sqliteMalloc() fails.
122975 **
122976 ** Return non-zero if a memory allocation error occurs.
122977 */
122978 static int fts3Rehash(Fts3Hash *pH, int new_size){
122979   struct _fts3ht *new_ht;          /* The new hash table */
122980   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
122981   int (*xHash)(const void*,int);   /* The hash function */
122982
122983   assert( (new_size & (new_size-1))==0 );
122984   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
122985   if( new_ht==0 ) return 1;
122986   fts3HashFree(pH->ht);
122987   pH->ht = new_ht;
122988   pH->htsize = new_size;
122989   xHash = ftsHashFunction(pH->keyClass);
122990   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
122991     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
122992     next_elem = elem->next;
122993     fts3HashInsertElement(pH, &new_ht[h], elem);
122994   }
122995   return 0;
122996 }
122997
122998 /* This function (for internal use only) locates an element in an
122999 ** hash table that matches the given key.  The hash for this key has
123000 ** already been computed and is passed as the 4th parameter.
123001 */
123002 static Fts3HashElem *fts3FindElementByHash(
123003   const Fts3Hash *pH, /* The pH to be searched */
123004   const void *pKey,   /* The key we are searching for */
123005   int nKey,
123006   int h               /* The hash for this key. */
123007 ){
123008   Fts3HashElem *elem;            /* Used to loop thru the element list */
123009   int count;                     /* Number of elements left to test */
123010   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
123011
123012   if( pH->ht ){
123013     struct _fts3ht *pEntry = &pH->ht[h];
123014     elem = pEntry->chain;
123015     count = pEntry->count;
123016     xCompare = ftsCompareFunction(pH->keyClass);
123017     while( count-- && elem ){
123018       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
123019         return elem;
123020       }
123021       elem = elem->next;
123022     }
123023   }
123024   return 0;
123025 }
123026
123027 /* Remove a single entry from the hash table given a pointer to that
123028 ** element and a hash on the element's key.
123029 */
123030 static void fts3RemoveElementByHash(
123031   Fts3Hash *pH,         /* The pH containing "elem" */
123032   Fts3HashElem* elem,   /* The element to be removed from the pH */
123033   int h                 /* Hash value for the element */
123034 ){
123035   struct _fts3ht *pEntry;
123036   if( elem->prev ){
123037     elem->prev->next = elem->next; 
123038   }else{
123039     pH->first = elem->next;
123040   }
123041   if( elem->next ){
123042     elem->next->prev = elem->prev;
123043   }
123044   pEntry = &pH->ht[h];
123045   if( pEntry->chain==elem ){
123046     pEntry->chain = elem->next;
123047   }
123048   pEntry->count--;
123049   if( pEntry->count<=0 ){
123050     pEntry->chain = 0;
123051   }
123052   if( pH->copyKey && elem->pKey ){
123053     fts3HashFree(elem->pKey);
123054   }
123055   fts3HashFree( elem );
123056   pH->count--;
123057   if( pH->count<=0 ){
123058     assert( pH->first==0 );
123059     assert( pH->count==0 );
123060     fts3HashClear(pH);
123061   }
123062 }
123063
123064 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
123065   const Fts3Hash *pH, 
123066   const void *pKey, 
123067   int nKey
123068 ){
123069   int h;                          /* A hash on key */
123070   int (*xHash)(const void*,int);  /* The hash function */
123071
123072   if( pH==0 || pH->ht==0 ) return 0;
123073   xHash = ftsHashFunction(pH->keyClass);
123074   assert( xHash!=0 );
123075   h = (*xHash)(pKey,nKey);
123076   assert( (pH->htsize & (pH->htsize-1))==0 );
123077   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
123078 }
123079
123080 /* 
123081 ** Attempt to locate an element of the hash table pH with a key
123082 ** that matches pKey,nKey.  Return the data for this element if it is
123083 ** found, or NULL if there is no match.
123084 */
123085 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
123086   Fts3HashElem *pElem;            /* The element that matches key (if any) */
123087
123088   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
123089   return pElem ? pElem->data : 0;
123090 }
123091
123092 /* Insert an element into the hash table pH.  The key is pKey,nKey
123093 ** and the data is "data".
123094 **
123095 ** If no element exists with a matching key, then a new
123096 ** element is created.  A copy of the key is made if the copyKey
123097 ** flag is set.  NULL is returned.
123098 **
123099 ** If another element already exists with the same key, then the
123100 ** new data replaces the old data and the old data is returned.
123101 ** The key is not copied in this instance.  If a malloc fails, then
123102 ** the new data is returned and the hash table is unchanged.
123103 **
123104 ** If the "data" parameter to this function is NULL, then the
123105 ** element corresponding to "key" is removed from the hash table.
123106 */
123107 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
123108   Fts3Hash *pH,        /* The hash table to insert into */
123109   const void *pKey,    /* The key */
123110   int nKey,            /* Number of bytes in the key */
123111   void *data           /* The data */
123112 ){
123113   int hraw;                 /* Raw hash value of the key */
123114   int h;                    /* the hash of the key modulo hash table size */
123115   Fts3HashElem *elem;       /* Used to loop thru the element list */
123116   Fts3HashElem *new_elem;   /* New element added to the pH */
123117   int (*xHash)(const void*,int);  /* The hash function */
123118
123119   assert( pH!=0 );
123120   xHash = ftsHashFunction(pH->keyClass);
123121   assert( xHash!=0 );
123122   hraw = (*xHash)(pKey, nKey);
123123   assert( (pH->htsize & (pH->htsize-1))==0 );
123124   h = hraw & (pH->htsize-1);
123125   elem = fts3FindElementByHash(pH,pKey,nKey,h);
123126   if( elem ){
123127     void *old_data = elem->data;
123128     if( data==0 ){
123129       fts3RemoveElementByHash(pH,elem,h);
123130     }else{
123131       elem->data = data;
123132     }
123133     return old_data;
123134   }
123135   if( data==0 ) return 0;
123136   if( (pH->htsize==0 && fts3Rehash(pH,8))
123137    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
123138   ){
123139     pH->count = 0;
123140     return data;
123141   }
123142   assert( pH->htsize>0 );
123143   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
123144   if( new_elem==0 ) return data;
123145   if( pH->copyKey && pKey!=0 ){
123146     new_elem->pKey = fts3HashMalloc( nKey );
123147     if( new_elem->pKey==0 ){
123148       fts3HashFree(new_elem);
123149       return data;
123150     }
123151     memcpy((void*)new_elem->pKey, pKey, nKey);
123152   }else{
123153     new_elem->pKey = (void*)pKey;
123154   }
123155   new_elem->nKey = nKey;
123156   pH->count++;
123157   assert( pH->htsize>0 );
123158   assert( (pH->htsize & (pH->htsize-1))==0 );
123159   h = hraw & (pH->htsize-1);
123160   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
123161   new_elem->data = data;
123162   return 0;
123163 }
123164
123165 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123166
123167 /************** End of fts3_hash.c *******************************************/
123168 /************** Begin file fts3_porter.c *************************************/
123169 /*
123170 ** 2006 September 30
123171 **
123172 ** The author disclaims copyright to this source code.  In place of
123173 ** a legal notice, here is a blessing:
123174 **
123175 **    May you do good and not evil.
123176 **    May you find forgiveness for yourself and forgive others.
123177 **    May you share freely, never taking more than you give.
123178 **
123179 *************************************************************************
123180 ** Implementation of the full-text-search tokenizer that implements
123181 ** a Porter stemmer.
123182 */
123183
123184 /*
123185 ** The code in this file is only compiled if:
123186 **
123187 **     * The FTS3 module is being built as an extension
123188 **       (in which case SQLITE_CORE is not defined), or
123189 **
123190 **     * The FTS3 module is being built into the core of
123191 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123192 */
123193 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123194
123195 /* #include <assert.h> */
123196 /* #include <stdlib.h> */
123197 /* #include <stdio.h> */
123198 /* #include <string.h> */
123199
123200
123201 /*
123202 ** Class derived from sqlite3_tokenizer
123203 */
123204 typedef struct porter_tokenizer {
123205   sqlite3_tokenizer base;      /* Base class */
123206 } porter_tokenizer;
123207
123208 /*
123209 ** Class derived from sqlite3_tokenizer_cursor
123210 */
123211 typedef struct porter_tokenizer_cursor {
123212   sqlite3_tokenizer_cursor base;
123213   const char *zInput;          /* input we are tokenizing */
123214   int nInput;                  /* size of the input */
123215   int iOffset;                 /* current position in zInput */
123216   int iToken;                  /* index of next token to be returned */
123217   char *zToken;                /* storage for current token */
123218   int nAllocated;              /* space allocated to zToken buffer */
123219 } porter_tokenizer_cursor;
123220
123221
123222 /*
123223 ** Create a new tokenizer instance.
123224 */
123225 static int porterCreate(
123226   int argc, const char * const *argv,
123227   sqlite3_tokenizer **ppTokenizer
123228 ){
123229   porter_tokenizer *t;
123230
123231   UNUSED_PARAMETER(argc);
123232   UNUSED_PARAMETER(argv);
123233
123234   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
123235   if( t==NULL ) return SQLITE_NOMEM;
123236   memset(t, 0, sizeof(*t));
123237   *ppTokenizer = &t->base;
123238   return SQLITE_OK;
123239 }
123240
123241 /*
123242 ** Destroy a tokenizer
123243 */
123244 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
123245   sqlite3_free(pTokenizer);
123246   return SQLITE_OK;
123247 }
123248
123249 /*
123250 ** Prepare to begin tokenizing a particular string.  The input
123251 ** string to be tokenized is zInput[0..nInput-1].  A cursor
123252 ** used to incrementally tokenize this string is returned in 
123253 ** *ppCursor.
123254 */
123255 static int porterOpen(
123256   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
123257   const char *zInput, int nInput,        /* String to be tokenized */
123258   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123259 ){
123260   porter_tokenizer_cursor *c;
123261
123262   UNUSED_PARAMETER(pTokenizer);
123263
123264   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
123265   if( c==NULL ) return SQLITE_NOMEM;
123266
123267   c->zInput = zInput;
123268   if( zInput==0 ){
123269     c->nInput = 0;
123270   }else if( nInput<0 ){
123271     c->nInput = (int)strlen(zInput);
123272   }else{
123273     c->nInput = nInput;
123274   }
123275   c->iOffset = 0;                 /* start tokenizing at the beginning */
123276   c->iToken = 0;
123277   c->zToken = NULL;               /* no space allocated, yet. */
123278   c->nAllocated = 0;
123279
123280   *ppCursor = &c->base;
123281   return SQLITE_OK;
123282 }
123283
123284 /*
123285 ** Close a tokenization cursor previously opened by a call to
123286 ** porterOpen() above.
123287 */
123288 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
123289   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123290   sqlite3_free(c->zToken);
123291   sqlite3_free(c);
123292   return SQLITE_OK;
123293 }
123294 /*
123295 ** Vowel or consonant
123296 */
123297 static const char cType[] = {
123298    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
123299    1, 1, 1, 2, 1
123300 };
123301
123302 /*
123303 ** isConsonant() and isVowel() determine if their first character in
123304 ** the string they point to is a consonant or a vowel, according
123305 ** to Porter ruls.  
123306 **
123307 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
123308 ** 'Y' is a consonant unless it follows another consonant,
123309 ** in which case it is a vowel.
123310 **
123311 ** In these routine, the letters are in reverse order.  So the 'y' rule
123312 ** is that 'y' is a consonant unless it is followed by another
123313 ** consonent.
123314 */
123315 static int isVowel(const char*);
123316 static int isConsonant(const char *z){
123317   int j;
123318   char x = *z;
123319   if( x==0 ) return 0;
123320   assert( x>='a' && x<='z' );
123321   j = cType[x-'a'];
123322   if( j<2 ) return j;
123323   return z[1]==0 || isVowel(z + 1);
123324 }
123325 static int isVowel(const char *z){
123326   int j;
123327   char x = *z;
123328   if( x==0 ) return 0;
123329   assert( x>='a' && x<='z' );
123330   j = cType[x-'a'];
123331   if( j<2 ) return 1-j;
123332   return isConsonant(z + 1);
123333 }
123334
123335 /*
123336 ** Let any sequence of one or more vowels be represented by V and let
123337 ** C be sequence of one or more consonants.  Then every word can be
123338 ** represented as:
123339 **
123340 **           [C] (VC){m} [V]
123341 **
123342 ** In prose:  A word is an optional consonant followed by zero or
123343 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
123344 ** number of vowel consonant pairs.  This routine computes the value
123345 ** of m for the first i bytes of a word.
123346 **
123347 ** Return true if the m-value for z is 1 or more.  In other words,
123348 ** return true if z contains at least one vowel that is followed
123349 ** by a consonant.
123350 **
123351 ** In this routine z[] is in reverse order.  So we are really looking
123352 ** for an instance of of a consonant followed by a vowel.
123353 */
123354 static int m_gt_0(const char *z){
123355   while( isVowel(z) ){ z++; }
123356   if( *z==0 ) return 0;
123357   while( isConsonant(z) ){ z++; }
123358   return *z!=0;
123359 }
123360
123361 /* Like mgt0 above except we are looking for a value of m which is
123362 ** exactly 1
123363 */
123364 static int m_eq_1(const char *z){
123365   while( isVowel(z) ){ z++; }
123366   if( *z==0 ) return 0;
123367   while( isConsonant(z) ){ z++; }
123368   if( *z==0 ) return 0;
123369   while( isVowel(z) ){ z++; }
123370   if( *z==0 ) return 1;
123371   while( isConsonant(z) ){ z++; }
123372   return *z==0;
123373 }
123374
123375 /* Like mgt0 above except we are looking for a value of m>1 instead
123376 ** or m>0
123377 */
123378 static int m_gt_1(const char *z){
123379   while( isVowel(z) ){ z++; }
123380   if( *z==0 ) return 0;
123381   while( isConsonant(z) ){ z++; }
123382   if( *z==0 ) return 0;
123383   while( isVowel(z) ){ z++; }
123384   if( *z==0 ) return 0;
123385   while( isConsonant(z) ){ z++; }
123386   return *z!=0;
123387 }
123388
123389 /*
123390 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
123391 */
123392 static int hasVowel(const char *z){
123393   while( isConsonant(z) ){ z++; }
123394   return *z!=0;
123395 }
123396
123397 /*
123398 ** Return TRUE if the word ends in a double consonant.
123399 **
123400 ** The text is reversed here. So we are really looking at
123401 ** the first two characters of z[].
123402 */
123403 static int doubleConsonant(const char *z){
123404   return isConsonant(z) && z[0]==z[1];
123405 }
123406
123407 /*
123408 ** Return TRUE if the word ends with three letters which
123409 ** are consonant-vowel-consonent and where the final consonant
123410 ** is not 'w', 'x', or 'y'.
123411 **
123412 ** The word is reversed here.  So we are really checking the
123413 ** first three letters and the first one cannot be in [wxy].
123414 */
123415 static int star_oh(const char *z){
123416   return
123417     isConsonant(z) &&
123418     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
123419     isVowel(z+1) &&
123420     isConsonant(z+2);
123421 }
123422
123423 /*
123424 ** If the word ends with zFrom and xCond() is true for the stem
123425 ** of the word that preceeds the zFrom ending, then change the 
123426 ** ending to zTo.
123427 **
123428 ** The input word *pz and zFrom are both in reverse order.  zTo
123429 ** is in normal order. 
123430 **
123431 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
123432 ** match.  Not that TRUE is returned even if xCond() fails and
123433 ** no substitution occurs.
123434 */
123435 static int stem(
123436   char **pz,             /* The word being stemmed (Reversed) */
123437   const char *zFrom,     /* If the ending matches this... (Reversed) */
123438   const char *zTo,       /* ... change the ending to this (not reversed) */
123439   int (*xCond)(const char*)   /* Condition that must be true */
123440 ){
123441   char *z = *pz;
123442   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
123443   if( *zFrom!=0 ) return 0;
123444   if( xCond && !xCond(z) ) return 1;
123445   while( *zTo ){
123446     *(--z) = *(zTo++);
123447   }
123448   *pz = z;
123449   return 1;
123450 }
123451
123452 /*
123453 ** This is the fallback stemmer used when the porter stemmer is
123454 ** inappropriate.  The input word is copied into the output with
123455 ** US-ASCII case folding.  If the input word is too long (more
123456 ** than 20 bytes if it contains no digits or more than 6 bytes if
123457 ** it contains digits) then word is truncated to 20 or 6 bytes
123458 ** by taking 10 or 3 bytes from the beginning and end.
123459 */
123460 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123461   int i, mx, j;
123462   int hasDigit = 0;
123463   for(i=0; i<nIn; i++){
123464     char c = zIn[i];
123465     if( c>='A' && c<='Z' ){
123466       zOut[i] = c - 'A' + 'a';
123467     }else{
123468       if( c>='0' && c<='9' ) hasDigit = 1;
123469       zOut[i] = c;
123470     }
123471   }
123472   mx = hasDigit ? 3 : 10;
123473   if( nIn>mx*2 ){
123474     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
123475       zOut[j] = zOut[i];
123476     }
123477     i = j;
123478   }
123479   zOut[i] = 0;
123480   *pnOut = i;
123481 }
123482
123483
123484 /*
123485 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
123486 ** zOut is at least big enough to hold nIn bytes.  Write the actual
123487 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
123488 **
123489 ** Any upper-case characters in the US-ASCII character set ([A-Z])
123490 ** are converted to lower case.  Upper-case UTF characters are
123491 ** unchanged.
123492 **
123493 ** Words that are longer than about 20 bytes are stemmed by retaining
123494 ** a few bytes from the beginning and the end of the word.  If the
123495 ** word contains digits, 3 bytes are taken from the beginning and
123496 ** 3 bytes from the end.  For long words without digits, 10 bytes
123497 ** are taken from each end.  US-ASCII case folding still applies.
123498 ** 
123499 ** If the input word contains not digits but does characters not 
123500 ** in [a-zA-Z] then no stemming is attempted and this routine just 
123501 ** copies the input into the input into the output with US-ASCII
123502 ** case folding.
123503 **
123504 ** Stemming never increases the length of the word.  So there is
123505 ** no chance of overflowing the zOut buffer.
123506 */
123507 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123508   int i, j;
123509   char zReverse[28];
123510   char *z, *z2;
123511   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
123512     /* The word is too big or too small for the porter stemmer.
123513     ** Fallback to the copy stemmer */
123514     copy_stemmer(zIn, nIn, zOut, pnOut);
123515     return;
123516   }
123517   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
123518     char c = zIn[i];
123519     if( c>='A' && c<='Z' ){
123520       zReverse[j] = c + 'a' - 'A';
123521     }else if( c>='a' && c<='z' ){
123522       zReverse[j] = c;
123523     }else{
123524       /* The use of a character not in [a-zA-Z] means that we fallback
123525       ** to the copy stemmer */
123526       copy_stemmer(zIn, nIn, zOut, pnOut);
123527       return;
123528     }
123529   }
123530   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
123531   z = &zReverse[j+1];
123532
123533
123534   /* Step 1a */
123535   if( z[0]=='s' ){
123536     if(
123537      !stem(&z, "sess", "ss", 0) &&
123538      !stem(&z, "sei", "i", 0)  &&
123539      !stem(&z, "ss", "ss", 0)
123540     ){
123541       z++;
123542     }
123543   }
123544
123545   /* Step 1b */  
123546   z2 = z;
123547   if( stem(&z, "dee", "ee", m_gt_0) ){
123548     /* Do nothing.  The work was all in the test */
123549   }else if( 
123550      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
123551       && z!=z2
123552   ){
123553      if( stem(&z, "ta", "ate", 0) ||
123554          stem(&z, "lb", "ble", 0) ||
123555          stem(&z, "zi", "ize", 0) ){
123556        /* Do nothing.  The work was all in the test */
123557      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
123558        z++;
123559      }else if( m_eq_1(z) && star_oh(z) ){
123560        *(--z) = 'e';
123561      }
123562   }
123563
123564   /* Step 1c */
123565   if( z[0]=='y' && hasVowel(z+1) ){
123566     z[0] = 'i';
123567   }
123568
123569   /* Step 2 */
123570   switch( z[1] ){
123571    case 'a':
123572      stem(&z, "lanoita", "ate", m_gt_0) ||
123573      stem(&z, "lanoit", "tion", m_gt_0);
123574      break;
123575    case 'c':
123576      stem(&z, "icne", "ence", m_gt_0) ||
123577      stem(&z, "icna", "ance", m_gt_0);
123578      break;
123579    case 'e':
123580      stem(&z, "rezi", "ize", m_gt_0);
123581      break;
123582    case 'g':
123583      stem(&z, "igol", "log", m_gt_0);
123584      break;
123585    case 'l':
123586      stem(&z, "ilb", "ble", m_gt_0) ||
123587      stem(&z, "illa", "al", m_gt_0) ||
123588      stem(&z, "iltne", "ent", m_gt_0) ||
123589      stem(&z, "ile", "e", m_gt_0) ||
123590      stem(&z, "ilsuo", "ous", m_gt_0);
123591      break;
123592    case 'o':
123593      stem(&z, "noitazi", "ize", m_gt_0) ||
123594      stem(&z, "noita", "ate", m_gt_0) ||
123595      stem(&z, "rota", "ate", m_gt_0);
123596      break;
123597    case 's':
123598      stem(&z, "msila", "al", m_gt_0) ||
123599      stem(&z, "ssenevi", "ive", m_gt_0) ||
123600      stem(&z, "ssenluf", "ful", m_gt_0) ||
123601      stem(&z, "ssensuo", "ous", m_gt_0);
123602      break;
123603    case 't':
123604      stem(&z, "itila", "al", m_gt_0) ||
123605      stem(&z, "itivi", "ive", m_gt_0) ||
123606      stem(&z, "itilib", "ble", m_gt_0);
123607      break;
123608   }
123609
123610   /* Step 3 */
123611   switch( z[0] ){
123612    case 'e':
123613      stem(&z, "etaci", "ic", m_gt_0) ||
123614      stem(&z, "evita", "", m_gt_0)   ||
123615      stem(&z, "ezila", "al", m_gt_0);
123616      break;
123617    case 'i':
123618      stem(&z, "itici", "ic", m_gt_0);
123619      break;
123620    case 'l':
123621      stem(&z, "laci", "ic", m_gt_0) ||
123622      stem(&z, "luf", "", m_gt_0);
123623      break;
123624    case 's':
123625      stem(&z, "ssen", "", m_gt_0);
123626      break;
123627   }
123628
123629   /* Step 4 */
123630   switch( z[1] ){
123631    case 'a':
123632      if( z[0]=='l' && m_gt_1(z+2) ){
123633        z += 2;
123634      }
123635      break;
123636    case 'c':
123637      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
123638        z += 4;
123639      }
123640      break;
123641    case 'e':
123642      if( z[0]=='r' && m_gt_1(z+2) ){
123643        z += 2;
123644      }
123645      break;
123646    case 'i':
123647      if( z[0]=='c' && m_gt_1(z+2) ){
123648        z += 2;
123649      }
123650      break;
123651    case 'l':
123652      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
123653        z += 4;
123654      }
123655      break;
123656    case 'n':
123657      if( z[0]=='t' ){
123658        if( z[2]=='a' ){
123659          if( m_gt_1(z+3) ){
123660            z += 3;
123661          }
123662        }else if( z[2]=='e' ){
123663          stem(&z, "tneme", "", m_gt_1) ||
123664          stem(&z, "tnem", "", m_gt_1) ||
123665          stem(&z, "tne", "", m_gt_1);
123666        }
123667      }
123668      break;
123669    case 'o':
123670      if( z[0]=='u' ){
123671        if( m_gt_1(z+2) ){
123672          z += 2;
123673        }
123674      }else if( z[3]=='s' || z[3]=='t' ){
123675        stem(&z, "noi", "", m_gt_1);
123676      }
123677      break;
123678    case 's':
123679      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
123680        z += 3;
123681      }
123682      break;
123683    case 't':
123684      stem(&z, "eta", "", m_gt_1) ||
123685      stem(&z, "iti", "", m_gt_1);
123686      break;
123687    case 'u':
123688      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
123689        z += 3;
123690      }
123691      break;
123692    case 'v':
123693    case 'z':
123694      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
123695        z += 3;
123696      }
123697      break;
123698   }
123699
123700   /* Step 5a */
123701   if( z[0]=='e' ){
123702     if( m_gt_1(z+1) ){
123703       z++;
123704     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
123705       z++;
123706     }
123707   }
123708
123709   /* Step 5b */
123710   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
123711     z++;
123712   }
123713
123714   /* z[] is now the stemmed word in reverse order.  Flip it back
123715   ** around into forward order and return.
123716   */
123717   *pnOut = i = (int)strlen(z);
123718   zOut[i] = 0;
123719   while( *z ){
123720     zOut[--i] = *(z++);
123721   }
123722 }
123723
123724 /*
123725 ** Characters that can be part of a token.  We assume any character
123726 ** whose value is greater than 0x80 (any UTF character) can be
123727 ** part of a token.  In other words, delimiters all must have
123728 ** values of 0x7f or lower.
123729 */
123730 static const char porterIdChar[] = {
123731 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
123732     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123733     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123734     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123735     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123736     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123737 };
123738 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
123739
123740 /*
123741 ** Extract the next token from a tokenization cursor.  The cursor must
123742 ** have been opened by a prior call to porterOpen().
123743 */
123744 static int porterNext(
123745   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
123746   const char **pzToken,               /* OUT: *pzToken is the token text */
123747   int *pnBytes,                       /* OUT: Number of bytes in token */
123748   int *piStartOffset,                 /* OUT: Starting offset of token */
123749   int *piEndOffset,                   /* OUT: Ending offset of token */
123750   int *piPosition                     /* OUT: Position integer of token */
123751 ){
123752   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123753   const char *z = c->zInput;
123754
123755   while( c->iOffset<c->nInput ){
123756     int iStartOffset, ch;
123757
123758     /* Scan past delimiter characters */
123759     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
123760       c->iOffset++;
123761     }
123762
123763     /* Count non-delimiter characters. */
123764     iStartOffset = c->iOffset;
123765     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
123766       c->iOffset++;
123767     }
123768
123769     if( c->iOffset>iStartOffset ){
123770       int n = c->iOffset-iStartOffset;
123771       if( n>c->nAllocated ){
123772         char *pNew;
123773         c->nAllocated = n+20;
123774         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
123775         if( !pNew ) return SQLITE_NOMEM;
123776         c->zToken = pNew;
123777       }
123778       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
123779       *pzToken = c->zToken;
123780       *piStartOffset = iStartOffset;
123781       *piEndOffset = c->iOffset;
123782       *piPosition = c->iToken++;
123783       return SQLITE_OK;
123784     }
123785   }
123786   return SQLITE_DONE;
123787 }
123788
123789 /*
123790 ** The set of routines that implement the porter-stemmer tokenizer
123791 */
123792 static const sqlite3_tokenizer_module porterTokenizerModule = {
123793   0,
123794   porterCreate,
123795   porterDestroy,
123796   porterOpen,
123797   porterClose,
123798   porterNext,
123799   0
123800 };
123801
123802 /*
123803 ** Allocate a new porter tokenizer.  Return a pointer to the new
123804 ** tokenizer in *ppModule
123805 */
123806 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
123807   sqlite3_tokenizer_module const**ppModule
123808 ){
123809   *ppModule = &porterTokenizerModule;
123810 }
123811
123812 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123813
123814 /************** End of fts3_porter.c *****************************************/
123815 /************** Begin file fts3_tokenizer.c **********************************/
123816 /*
123817 ** 2007 June 22
123818 **
123819 ** The author disclaims copyright to this source code.  In place of
123820 ** a legal notice, here is a blessing:
123821 **
123822 **    May you do good and not evil.
123823 **    May you find forgiveness for yourself and forgive others.
123824 **    May you share freely, never taking more than you give.
123825 **
123826 ******************************************************************************
123827 **
123828 ** This is part of an SQLite module implementing full-text search.
123829 ** This particular file implements the generic tokenizer interface.
123830 */
123831
123832 /*
123833 ** The code in this file is only compiled if:
123834 **
123835 **     * The FTS3 module is being built as an extension
123836 **       (in which case SQLITE_CORE is not defined), or
123837 **
123838 **     * The FTS3 module is being built into the core of
123839 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123840 */
123841 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123842
123843 /* #include <assert.h> */
123844 /* #include <string.h> */
123845
123846 /*
123847 ** Implementation of the SQL scalar function for accessing the underlying 
123848 ** hash table. This function may be called as follows:
123849 **
123850 **   SELECT <function-name>(<key-name>);
123851 **   SELECT <function-name>(<key-name>, <pointer>);
123852 **
123853 ** where <function-name> is the name passed as the second argument
123854 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
123855 **
123856 ** If the <pointer> argument is specified, it must be a blob value
123857 ** containing a pointer to be stored as the hash data corresponding
123858 ** to the string <key-name>. If <pointer> is not specified, then
123859 ** the string <key-name> must already exist in the has table. Otherwise,
123860 ** an error is returned.
123861 **
123862 ** Whether or not the <pointer> argument is specified, the value returned
123863 ** is a blob containing the pointer stored as the hash data corresponding
123864 ** to string <key-name> (after the hash-table is updated, if applicable).
123865 */
123866 static void scalarFunc(
123867   sqlite3_context *context,
123868   int argc,
123869   sqlite3_value **argv
123870 ){
123871   Fts3Hash *pHash;
123872   void *pPtr = 0;
123873   const unsigned char *zName;
123874   int nName;
123875
123876   assert( argc==1 || argc==2 );
123877
123878   pHash = (Fts3Hash *)sqlite3_user_data(context);
123879
123880   zName = sqlite3_value_text(argv[0]);
123881   nName = sqlite3_value_bytes(argv[0])+1;
123882
123883   if( argc==2 ){
123884     void *pOld;
123885     int n = sqlite3_value_bytes(argv[1]);
123886     if( n!=sizeof(pPtr) ){
123887       sqlite3_result_error(context, "argument type mismatch", -1);
123888       return;
123889     }
123890     pPtr = *(void **)sqlite3_value_blob(argv[1]);
123891     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
123892     if( pOld==pPtr ){
123893       sqlite3_result_error(context, "out of memory", -1);
123894       return;
123895     }
123896   }else{
123897     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
123898     if( !pPtr ){
123899       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
123900       sqlite3_result_error(context, zErr, -1);
123901       sqlite3_free(zErr);
123902       return;
123903     }
123904   }
123905
123906   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
123907 }
123908
123909 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
123910   static const char isFtsIdChar[] = {
123911       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
123912       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
123913       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
123914       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123915       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123916       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123917       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123918       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123919   };
123920   return (c&0x80 || isFtsIdChar[(int)(c)]);
123921 }
123922
123923 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
123924   const char *z1;
123925   const char *z2 = 0;
123926
123927   /* Find the start of the next token. */
123928   z1 = zStr;
123929   while( z2==0 ){
123930     char c = *z1;
123931     switch( c ){
123932       case '\0': return 0;        /* No more tokens here */
123933       case '\'':
123934       case '"':
123935       case '`': {
123936         z2 = z1;
123937         while( *++z2 && (*z2!=c || *++z2==c) );
123938         break;
123939       }
123940       case '[':
123941         z2 = &z1[1];
123942         while( *z2 && z2[0]!=']' ) z2++;
123943         if( *z2 ) z2++;
123944         break;
123945
123946       default:
123947         if( sqlite3Fts3IsIdChar(*z1) ){
123948           z2 = &z1[1];
123949           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
123950         }else{
123951           z1++;
123952         }
123953     }
123954   }
123955
123956   *pn = (int)(z2-z1);
123957   return z1;
123958 }
123959
123960 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
123961   Fts3Hash *pHash,                /* Tokenizer hash table */
123962   const char *zArg,               /* Tokenizer name */
123963   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
123964   char **pzErr                    /* OUT: Set to malloced error message */
123965 ){
123966   int rc;
123967   char *z = (char *)zArg;
123968   int n = 0;
123969   char *zCopy;
123970   char *zEnd;                     /* Pointer to nul-term of zCopy */
123971   sqlite3_tokenizer_module *m;
123972
123973   zCopy = sqlite3_mprintf("%s", zArg);
123974   if( !zCopy ) return SQLITE_NOMEM;
123975   zEnd = &zCopy[strlen(zCopy)];
123976
123977   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
123978   z[n] = '\0';
123979   sqlite3Fts3Dequote(z);
123980
123981   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
123982   if( !m ){
123983     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
123984     rc = SQLITE_ERROR;
123985   }else{
123986     char const **aArg = 0;
123987     int iArg = 0;
123988     z = &z[n+1];
123989     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
123990       int nNew = sizeof(char *)*(iArg+1);
123991       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
123992       if( !aNew ){
123993         sqlite3_free(zCopy);
123994         sqlite3_free((void *)aArg);
123995         return SQLITE_NOMEM;
123996       }
123997       aArg = aNew;
123998       aArg[iArg++] = z;
123999       z[n] = '\0';
124000       sqlite3Fts3Dequote(z);
124001       z = &z[n+1];
124002     }
124003     rc = m->xCreate(iArg, aArg, ppTok);
124004     assert( rc!=SQLITE_OK || *ppTok );
124005     if( rc!=SQLITE_OK ){
124006       *pzErr = sqlite3_mprintf("unknown tokenizer");
124007     }else{
124008       (*ppTok)->pModule = m; 
124009     }
124010     sqlite3_free((void *)aArg);
124011   }
124012
124013   sqlite3_free(zCopy);
124014   return rc;
124015 }
124016
124017
124018 #ifdef SQLITE_TEST
124019
124020 /* #include <tcl.h> */
124021 /* #include <string.h> */
124022
124023 /*
124024 ** Implementation of a special SQL scalar function for testing tokenizers 
124025 ** designed to be used in concert with the Tcl testing framework. This
124026 ** function must be called with two or more arguments:
124027 **
124028 **   SELECT <function-name>(<key-name>, ..., <input-string>);
124029 **
124030 ** where <function-name> is the name passed as the second argument
124031 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
124032 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
124033 **
124034 ** The return value is a string that may be interpreted as a Tcl
124035 ** list. For each token in the <input-string>, three elements are
124036 ** added to the returned list. The first is the token position, the 
124037 ** second is the token text (folded, stemmed, etc.) and the third is the
124038 ** substring of <input-string> associated with the token. For example, 
124039 ** using the built-in "simple" tokenizer:
124040 **
124041 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
124042 **
124043 ** will return the string:
124044 **
124045 **   "{0 i I 1 dont don't 2 see see 3 how how}"
124046 **   
124047 */
124048 static void testFunc(
124049   sqlite3_context *context,
124050   int argc,
124051   sqlite3_value **argv
124052 ){
124053   Fts3Hash *pHash;
124054   sqlite3_tokenizer_module *p;
124055   sqlite3_tokenizer *pTokenizer = 0;
124056   sqlite3_tokenizer_cursor *pCsr = 0;
124057
124058   const char *zErr = 0;
124059
124060   const char *zName;
124061   int nName;
124062   const char *zInput;
124063   int nInput;
124064
124065   const char *azArg[64];
124066
124067   const char *zToken;
124068   int nToken;
124069   int iStart;
124070   int iEnd;
124071   int iPos;
124072   int i;
124073
124074   Tcl_Obj *pRet;
124075
124076   if( argc<2 ){
124077     sqlite3_result_error(context, "insufficient arguments", -1);
124078     return;
124079   }
124080
124081   nName = sqlite3_value_bytes(argv[0]);
124082   zName = (const char *)sqlite3_value_text(argv[0]);
124083   nInput = sqlite3_value_bytes(argv[argc-1]);
124084   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
124085
124086   pHash = (Fts3Hash *)sqlite3_user_data(context);
124087   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
124088
124089   if( !p ){
124090     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124091     sqlite3_result_error(context, zErr, -1);
124092     sqlite3_free(zErr);
124093     return;
124094   }
124095
124096   pRet = Tcl_NewObj();
124097   Tcl_IncrRefCount(pRet);
124098
124099   for(i=1; i<argc-1; i++){
124100     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
124101   }
124102
124103   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
124104     zErr = "error in xCreate()";
124105     goto finish;
124106   }
124107   pTokenizer->pModule = p;
124108   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
124109     zErr = "error in xOpen()";
124110     goto finish;
124111   }
124112
124113   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
124114     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
124115     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124116     zToken = &zInput[iStart];
124117     nToken = iEnd-iStart;
124118     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124119   }
124120
124121   if( SQLITE_OK!=p->xClose(pCsr) ){
124122     zErr = "error in xClose()";
124123     goto finish;
124124   }
124125   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
124126     zErr = "error in xDestroy()";
124127     goto finish;
124128   }
124129
124130 finish:
124131   if( zErr ){
124132     sqlite3_result_error(context, zErr, -1);
124133   }else{
124134     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
124135   }
124136   Tcl_DecrRefCount(pRet);
124137 }
124138
124139 static
124140 int registerTokenizer(
124141   sqlite3 *db, 
124142   char *zName, 
124143   const sqlite3_tokenizer_module *p
124144 ){
124145   int rc;
124146   sqlite3_stmt *pStmt;
124147   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
124148
124149   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124150   if( rc!=SQLITE_OK ){
124151     return rc;
124152   }
124153
124154   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124155   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
124156   sqlite3_step(pStmt);
124157
124158   return sqlite3_finalize(pStmt);
124159 }
124160
124161 static
124162 int queryTokenizer(
124163   sqlite3 *db, 
124164   char *zName,  
124165   const sqlite3_tokenizer_module **pp
124166 ){
124167   int rc;
124168   sqlite3_stmt *pStmt;
124169   const char zSql[] = "SELECT fts3_tokenizer(?)";
124170
124171   *pp = 0;
124172   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124173   if( rc!=SQLITE_OK ){
124174     return rc;
124175   }
124176
124177   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124178   if( SQLITE_ROW==sqlite3_step(pStmt) ){
124179     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124180       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124181     }
124182   }
124183
124184   return sqlite3_finalize(pStmt);
124185 }
124186
124187 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
124188
124189 /*
124190 ** Implementation of the scalar function fts3_tokenizer_internal_test().
124191 ** This function is used for testing only, it is not included in the
124192 ** build unless SQLITE_TEST is defined.
124193 **
124194 ** The purpose of this is to test that the fts3_tokenizer() function
124195 ** can be used as designed by the C-code in the queryTokenizer and
124196 ** registerTokenizer() functions above. These two functions are repeated
124197 ** in the README.tokenizer file as an example, so it is important to
124198 ** test them.
124199 **
124200 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
124201 ** function with no arguments. An assert() will fail if a problem is
124202 ** detected. i.e.:
124203 **
124204 **     SELECT fts3_tokenizer_internal_test();
124205 **
124206 */
124207 static void intTestFunc(
124208   sqlite3_context *context,
124209   int argc,
124210   sqlite3_value **argv
124211 ){
124212   int rc;
124213   const sqlite3_tokenizer_module *p1;
124214   const sqlite3_tokenizer_module *p2;
124215   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
124216
124217   UNUSED_PARAMETER(argc);
124218   UNUSED_PARAMETER(argv);
124219
124220   /* Test the query function */
124221   sqlite3Fts3SimpleTokenizerModule(&p1);
124222   rc = queryTokenizer(db, "simple", &p2);
124223   assert( rc==SQLITE_OK );
124224   assert( p1==p2 );
124225   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124226   assert( rc==SQLITE_ERROR );
124227   assert( p2==0 );
124228   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
124229
124230   /* Test the storage function */
124231   rc = registerTokenizer(db, "nosuchtokenizer", p1);
124232   assert( rc==SQLITE_OK );
124233   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124234   assert( rc==SQLITE_OK );
124235   assert( p2==p1 );
124236
124237   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
124238 }
124239
124240 #endif
124241
124242 /*
124243 ** Set up SQL objects in database db used to access the contents of
124244 ** the hash table pointed to by argument pHash. The hash table must
124245 ** been initialised to use string keys, and to take a private copy 
124246 ** of the key when a value is inserted. i.e. by a call similar to:
124247 **
124248 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
124249 **
124250 ** This function adds a scalar function (see header comment above
124251 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
124252 ** defined at compilation time, a temporary virtual table (see header 
124253 ** comment above struct HashTableVtab) to the database schema. Both 
124254 ** provide read/write access to the contents of *pHash.
124255 **
124256 ** The third argument to this function, zName, is used as the name
124257 ** of both the scalar and, if created, the virtual table.
124258 */
124259 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
124260   sqlite3 *db, 
124261   Fts3Hash *pHash, 
124262   const char *zName
124263 ){
124264   int rc = SQLITE_OK;
124265   void *p = (void *)pHash;
124266   const int any = SQLITE_ANY;
124267
124268 #ifdef SQLITE_TEST
124269   char *zTest = 0;
124270   char *zTest2 = 0;
124271   void *pdb = (void *)db;
124272   zTest = sqlite3_mprintf("%s_test", zName);
124273   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
124274   if( !zTest || !zTest2 ){
124275     rc = SQLITE_NOMEM;
124276   }
124277 #endif
124278
124279   if( SQLITE_OK==rc ){
124280     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
124281   }
124282   if( SQLITE_OK==rc ){
124283     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
124284   }
124285 #ifdef SQLITE_TEST
124286   if( SQLITE_OK==rc ){
124287     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
124288   }
124289   if( SQLITE_OK==rc ){
124290     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
124291   }
124292 #endif
124293
124294 #ifdef SQLITE_TEST
124295   sqlite3_free(zTest);
124296   sqlite3_free(zTest2);
124297 #endif
124298
124299   return rc;
124300 }
124301
124302 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124303
124304 /************** End of fts3_tokenizer.c **************************************/
124305 /************** Begin file fts3_tokenizer1.c *********************************/
124306 /*
124307 ** 2006 Oct 10
124308 **
124309 ** The author disclaims copyright to this source code.  In place of
124310 ** a legal notice, here is a blessing:
124311 **
124312 **    May you do good and not evil.
124313 **    May you find forgiveness for yourself and forgive others.
124314 **    May you share freely, never taking more than you give.
124315 **
124316 ******************************************************************************
124317 **
124318 ** Implementation of the "simple" full-text-search tokenizer.
124319 */
124320
124321 /*
124322 ** The code in this file is only compiled if:
124323 **
124324 **     * The FTS3 module is being built as an extension
124325 **       (in which case SQLITE_CORE is not defined), or
124326 **
124327 **     * The FTS3 module is being built into the core of
124328 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124329 */
124330 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124331
124332 /* #include <assert.h> */
124333 /* #include <stdlib.h> */
124334 /* #include <stdio.h> */
124335 /* #include <string.h> */
124336
124337
124338 typedef struct simple_tokenizer {
124339   sqlite3_tokenizer base;
124340   char delim[128];             /* flag ASCII delimiters */
124341 } simple_tokenizer;
124342
124343 typedef struct simple_tokenizer_cursor {
124344   sqlite3_tokenizer_cursor base;
124345   const char *pInput;          /* input we are tokenizing */
124346   int nBytes;                  /* size of the input */
124347   int iOffset;                 /* current position in pInput */
124348   int iToken;                  /* index of next token to be returned */
124349   char *pToken;                /* storage for current token */
124350   int nTokenAllocated;         /* space allocated to zToken buffer */
124351 } simple_tokenizer_cursor;
124352
124353
124354 static int simpleDelim(simple_tokenizer *t, unsigned char c){
124355   return c<0x80 && t->delim[c];
124356 }
124357 static int fts3_isalnum(int x){
124358   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
124359 }
124360
124361 /*
124362 ** Create a new tokenizer instance.
124363 */
124364 static int simpleCreate(
124365   int argc, const char * const *argv,
124366   sqlite3_tokenizer **ppTokenizer
124367 ){
124368   simple_tokenizer *t;
124369
124370   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
124371   if( t==NULL ) return SQLITE_NOMEM;
124372   memset(t, 0, sizeof(*t));
124373
124374   /* TODO(shess) Delimiters need to remain the same from run to run,
124375   ** else we need to reindex.  One solution would be a meta-table to
124376   ** track such information in the database, then we'd only want this
124377   ** information on the initial create.
124378   */
124379   if( argc>1 ){
124380     int i, n = (int)strlen(argv[1]);
124381     for(i=0; i<n; i++){
124382       unsigned char ch = argv[1][i];
124383       /* We explicitly don't support UTF-8 delimiters for now. */
124384       if( ch>=0x80 ){
124385         sqlite3_free(t);
124386         return SQLITE_ERROR;
124387       }
124388       t->delim[ch] = 1;
124389     }
124390   } else {
124391     /* Mark non-alphanumeric ASCII characters as delimiters */
124392     int i;
124393     for(i=1; i<0x80; i++){
124394       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
124395     }
124396   }
124397
124398   *ppTokenizer = &t->base;
124399   return SQLITE_OK;
124400 }
124401
124402 /*
124403 ** Destroy a tokenizer
124404 */
124405 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
124406   sqlite3_free(pTokenizer);
124407   return SQLITE_OK;
124408 }
124409
124410 /*
124411 ** Prepare to begin tokenizing a particular string.  The input
124412 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
124413 ** used to incrementally tokenize this string is returned in 
124414 ** *ppCursor.
124415 */
124416 static int simpleOpen(
124417   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
124418   const char *pInput, int nBytes,        /* String to be tokenized */
124419   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124420 ){
124421   simple_tokenizer_cursor *c;
124422
124423   UNUSED_PARAMETER(pTokenizer);
124424
124425   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
124426   if( c==NULL ) return SQLITE_NOMEM;
124427
124428   c->pInput = pInput;
124429   if( pInput==0 ){
124430     c->nBytes = 0;
124431   }else if( nBytes<0 ){
124432     c->nBytes = (int)strlen(pInput);
124433   }else{
124434     c->nBytes = nBytes;
124435   }
124436   c->iOffset = 0;                 /* start tokenizing at the beginning */
124437   c->iToken = 0;
124438   c->pToken = NULL;               /* no space allocated, yet. */
124439   c->nTokenAllocated = 0;
124440
124441   *ppCursor = &c->base;
124442   return SQLITE_OK;
124443 }
124444
124445 /*
124446 ** Close a tokenization cursor previously opened by a call to
124447 ** simpleOpen() above.
124448 */
124449 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
124450   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124451   sqlite3_free(c->pToken);
124452   sqlite3_free(c);
124453   return SQLITE_OK;
124454 }
124455
124456 /*
124457 ** Extract the next token from a tokenization cursor.  The cursor must
124458 ** have been opened by a prior call to simpleOpen().
124459 */
124460 static int simpleNext(
124461   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
124462   const char **ppToken,               /* OUT: *ppToken is the token text */
124463   int *pnBytes,                       /* OUT: Number of bytes in token */
124464   int *piStartOffset,                 /* OUT: Starting offset of token */
124465   int *piEndOffset,                   /* OUT: Ending offset of token */
124466   int *piPosition                     /* OUT: Position integer of token */
124467 ){
124468   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124469   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
124470   unsigned char *p = (unsigned char *)c->pInput;
124471
124472   while( c->iOffset<c->nBytes ){
124473     int iStartOffset;
124474
124475     /* Scan past delimiter characters */
124476     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
124477       c->iOffset++;
124478     }
124479
124480     /* Count non-delimiter characters. */
124481     iStartOffset = c->iOffset;
124482     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
124483       c->iOffset++;
124484     }
124485
124486     if( c->iOffset>iStartOffset ){
124487       int i, n = c->iOffset-iStartOffset;
124488       if( n>c->nTokenAllocated ){
124489         char *pNew;
124490         c->nTokenAllocated = n+20;
124491         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
124492         if( !pNew ) return SQLITE_NOMEM;
124493         c->pToken = pNew;
124494       }
124495       for(i=0; i<n; i++){
124496         /* TODO(shess) This needs expansion to handle UTF-8
124497         ** case-insensitivity.
124498         */
124499         unsigned char ch = p[iStartOffset+i];
124500         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
124501       }
124502       *ppToken = c->pToken;
124503       *pnBytes = n;
124504       *piStartOffset = iStartOffset;
124505       *piEndOffset = c->iOffset;
124506       *piPosition = c->iToken++;
124507
124508       return SQLITE_OK;
124509     }
124510   }
124511   return SQLITE_DONE;
124512 }
124513
124514 /*
124515 ** The set of routines that implement the simple tokenizer
124516 */
124517 static const sqlite3_tokenizer_module simpleTokenizerModule = {
124518   0,
124519   simpleCreate,
124520   simpleDestroy,
124521   simpleOpen,
124522   simpleClose,
124523   simpleNext,
124524   0,
124525 };
124526
124527 /*
124528 ** Allocate a new simple tokenizer.  Return a pointer to the new
124529 ** tokenizer in *ppModule
124530 */
124531 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
124532   sqlite3_tokenizer_module const**ppModule
124533 ){
124534   *ppModule = &simpleTokenizerModule;
124535 }
124536
124537 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124538
124539 /************** End of fts3_tokenizer1.c *************************************/
124540 /************** Begin file fts3_write.c **************************************/
124541 /*
124542 ** 2009 Oct 23
124543 **
124544 ** The author disclaims copyright to this source code.  In place of
124545 ** a legal notice, here is a blessing:
124546 **
124547 **    May you do good and not evil.
124548 **    May you find forgiveness for yourself and forgive others.
124549 **    May you share freely, never taking more than you give.
124550 **
124551 ******************************************************************************
124552 **
124553 ** This file is part of the SQLite FTS3 extension module. Specifically,
124554 ** this file contains code to insert, update and delete rows from FTS3
124555 ** tables. It also contains code to merge FTS3 b-tree segments. Some
124556 ** of the sub-routines used to merge segments are also used by the query 
124557 ** code in fts3.c.
124558 */
124559
124560 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124561
124562 /* #include <string.h> */
124563 /* #include <assert.h> */
124564 /* #include <stdlib.h> */
124565
124566
124567 #define FTS_MAX_APPENDABLE_HEIGHT 16
124568
124569 /*
124570 ** When full-text index nodes are loaded from disk, the buffer that they
124571 ** are loaded into has the following number of bytes of padding at the end 
124572 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
124573 ** of 920 bytes is allocated for it.
124574 **
124575 ** This means that if we have a pointer into a buffer containing node data,
124576 ** it is always safe to read up to two varints from it without risking an
124577 ** overread, even if the node data is corrupted.
124578 */
124579 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
124580
124581 /*
124582 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
124583 ** memory incrementally instead of all at once. This can be a big performance
124584 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
124585 ** method before retrieving all query results (as may happen, for example,
124586 ** if a query has a LIMIT clause).
124587 **
124588 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
124589 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
124590 ** The code is written so that the hard lower-limit for each of these values 
124591 ** is 1. Clearly such small values would be inefficient, but can be useful 
124592 ** for testing purposes.
124593 **
124594 ** If this module is built with SQLITE_TEST defined, these constants may
124595 ** be overridden at runtime for testing purposes. File fts3_test.c contains
124596 ** a Tcl interface to read and write the values.
124597 */
124598 #ifdef SQLITE_TEST
124599 int test_fts3_node_chunksize = (4*1024);
124600 int test_fts3_node_chunk_threshold = (4*1024)*4;
124601 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
124602 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
124603 #else
124604 # define FTS3_NODE_CHUNKSIZE (4*1024) 
124605 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
124606 #endif
124607
124608 /*
124609 ** The two values that may be meaningfully bound to the :1 parameter in
124610 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
124611 */
124612 #define FTS_STAT_DOCTOTAL      0
124613 #define FTS_STAT_INCRMERGEHINT 1
124614 #define FTS_STAT_AUTOINCRMERGE 2
124615
124616 /*
124617 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
124618 ** and incremental merge operation that takes place. This is used for 
124619 ** debugging FTS only, it should not usually be turned on in production
124620 ** systems.
124621 */
124622 #ifdef FTS3_LOG_MERGES
124623 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
124624   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
124625 }
124626 #else
124627 #define fts3LogMerge(x, y)
124628 #endif
124629
124630
124631 typedef struct PendingList PendingList;
124632 typedef struct SegmentNode SegmentNode;
124633 typedef struct SegmentWriter SegmentWriter;
124634
124635 /*
124636 ** An instance of the following data structure is used to build doclists
124637 ** incrementally. See function fts3PendingListAppend() for details.
124638 */
124639 struct PendingList {
124640   int nData;
124641   char *aData;
124642   int nSpace;
124643   sqlite3_int64 iLastDocid;
124644   sqlite3_int64 iLastCol;
124645   sqlite3_int64 iLastPos;
124646 };
124647
124648
124649 /*
124650 ** Each cursor has a (possibly empty) linked list of the following objects.
124651 */
124652 struct Fts3DeferredToken {
124653   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
124654   int iCol;                       /* Column token must occur in */
124655   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
124656   PendingList *pList;             /* Doclist is assembled here */
124657 };
124658
124659 /*
124660 ** An instance of this structure is used to iterate through the terms on
124661 ** a contiguous set of segment b-tree leaf nodes. Although the details of
124662 ** this structure are only manipulated by code in this file, opaque handles
124663 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
124664 ** terms when querying the full-text index. See functions:
124665 **
124666 **   sqlite3Fts3SegReaderNew()
124667 **   sqlite3Fts3SegReaderFree()
124668 **   sqlite3Fts3SegReaderIterate()
124669 **
124670 ** Methods used to manipulate Fts3SegReader structures:
124671 **
124672 **   fts3SegReaderNext()
124673 **   fts3SegReaderFirstDocid()
124674 **   fts3SegReaderNextDocid()
124675 */
124676 struct Fts3SegReader {
124677   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
124678   u8 bLookup;                     /* True for a lookup only */
124679   u8 rootOnly;                    /* True for a root-only reader */
124680
124681   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
124682   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
124683   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
124684   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
124685
124686   char *aNode;                    /* Pointer to node data (or NULL) */
124687   int nNode;                      /* Size of buffer at aNode (or 0) */
124688   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
124689   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
124690
124691   Fts3HashElem **ppNextElem;
124692
124693   /* Variables set by fts3SegReaderNext(). These may be read directly
124694   ** by the caller. They are valid from the time SegmentReaderNew() returns
124695   ** until SegmentReaderNext() returns something other than SQLITE_OK
124696   ** (i.e. SQLITE_DONE).
124697   */
124698   int nTerm;                      /* Number of bytes in current term */
124699   char *zTerm;                    /* Pointer to current term */
124700   int nTermAlloc;                 /* Allocated size of zTerm buffer */
124701   char *aDoclist;                 /* Pointer to doclist of current entry */
124702   int nDoclist;                   /* Size of doclist in current entry */
124703
124704   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
124705   ** through the current doclist (aDoclist/nDoclist).
124706   */
124707   char *pOffsetList;
124708   int nOffsetList;                /* For descending pending seg-readers only */
124709   sqlite3_int64 iDocid;
124710 };
124711
124712 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
124713 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
124714
124715 /*
124716 ** An instance of this structure is used to create a segment b-tree in the
124717 ** database. The internal details of this type are only accessed by the
124718 ** following functions:
124719 **
124720 **   fts3SegWriterAdd()
124721 **   fts3SegWriterFlush()
124722 **   fts3SegWriterFree()
124723 */
124724 struct SegmentWriter {
124725   SegmentNode *pTree;             /* Pointer to interior tree structure */
124726   sqlite3_int64 iFirst;           /* First slot in %_segments written */
124727   sqlite3_int64 iFree;            /* Next free slot in %_segments */
124728   char *zTerm;                    /* Pointer to previous term buffer */
124729   int nTerm;                      /* Number of bytes in zTerm */
124730   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124731   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124732   int nSize;                      /* Size of allocation at aData */
124733   int nData;                      /* Bytes of data in aData */
124734   char *aData;                    /* Pointer to block from malloc() */
124735 };
124736
124737 /*
124738 ** Type SegmentNode is used by the following three functions to create
124739 ** the interior part of the segment b+-tree structures (everything except
124740 ** the leaf nodes). These functions and type are only ever used by code
124741 ** within the fts3SegWriterXXX() family of functions described above.
124742 **
124743 **   fts3NodeAddTerm()
124744 **   fts3NodeWrite()
124745 **   fts3NodeFree()
124746 **
124747 ** When a b+tree is written to the database (either as a result of a merge
124748 ** or the pending-terms table being flushed), leaves are written into the 
124749 ** database file as soon as they are completely populated. The interior of
124750 ** the tree is assembled in memory and written out only once all leaves have
124751 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
124752 ** very large, meaning that the interior of the tree consumes relatively 
124753 ** little memory.
124754 */
124755 struct SegmentNode {
124756   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
124757   SegmentNode *pRight;            /* Pointer to right-sibling */
124758   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
124759   int nEntry;                     /* Number of terms written to node so far */
124760   char *zTerm;                    /* Pointer to previous term buffer */
124761   int nTerm;                      /* Number of bytes in zTerm */
124762   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124763   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124764   int nData;                      /* Bytes of valid data so far */
124765   char *aData;                    /* Node data */
124766 };
124767
124768 /*
124769 ** Valid values for the second argument to fts3SqlStmt().
124770 */
124771 #define SQL_DELETE_CONTENT             0
124772 #define SQL_IS_EMPTY                   1
124773 #define SQL_DELETE_ALL_CONTENT         2 
124774 #define SQL_DELETE_ALL_SEGMENTS        3
124775 #define SQL_DELETE_ALL_SEGDIR          4
124776 #define SQL_DELETE_ALL_DOCSIZE         5
124777 #define SQL_DELETE_ALL_STAT            6
124778 #define SQL_SELECT_CONTENT_BY_ROWID    7
124779 #define SQL_NEXT_SEGMENT_INDEX         8
124780 #define SQL_INSERT_SEGMENTS            9
124781 #define SQL_NEXT_SEGMENTS_ID          10
124782 #define SQL_INSERT_SEGDIR             11
124783 #define SQL_SELECT_LEVEL              12
124784 #define SQL_SELECT_LEVEL_RANGE        13
124785 #define SQL_SELECT_LEVEL_COUNT        14
124786 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
124787 #define SQL_DELETE_SEGDIR_LEVEL       16
124788 #define SQL_DELETE_SEGMENTS_RANGE     17
124789 #define SQL_CONTENT_INSERT            18
124790 #define SQL_DELETE_DOCSIZE            19
124791 #define SQL_REPLACE_DOCSIZE           20
124792 #define SQL_SELECT_DOCSIZE            21
124793 #define SQL_SELECT_STAT               22
124794 #define SQL_REPLACE_STAT              23
124795
124796 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
124797 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
124798 #define SQL_DELETE_SEGDIR_RANGE       26
124799 #define SQL_SELECT_ALL_LANGID         27
124800 #define SQL_FIND_MERGE_LEVEL          28
124801 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
124802 #define SQL_DELETE_SEGDIR_ENTRY       30
124803 #define SQL_SHIFT_SEGDIR_ENTRY        31
124804 #define SQL_SELECT_SEGDIR             32
124805 #define SQL_CHOMP_SEGDIR              33
124806 #define SQL_SEGMENT_IS_APPENDABLE     34
124807 #define SQL_SELECT_INDEXES            35
124808 #define SQL_SELECT_MXLEVEL            36
124809
124810 /*
124811 ** This function is used to obtain an SQLite prepared statement handle
124812 ** for the statement identified by the second argument. If successful,
124813 ** *pp is set to the requested statement handle and SQLITE_OK returned.
124814 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
124815 **
124816 ** If argument apVal is not NULL, then it must point to an array with
124817 ** at least as many entries as the requested statement has bound 
124818 ** parameters. The values are bound to the statements parameters before
124819 ** returning.
124820 */
124821 static int fts3SqlStmt(
124822   Fts3Table *p,                   /* Virtual table handle */
124823   int eStmt,                      /* One of the SQL_XXX constants above */
124824   sqlite3_stmt **pp,              /* OUT: Statement handle */
124825   sqlite3_value **apVal           /* Values to bind to statement */
124826 ){
124827   const char *azSql[] = {
124828 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
124829 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
124830 /* 2  */  "DELETE FROM %Q.'%q_content'",
124831 /* 3  */  "DELETE FROM %Q.'%q_segments'",
124832 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
124833 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
124834 /* 6  */  "DELETE FROM %Q.'%q_stat'",
124835 /* 7  */  "SELECT %s WHERE rowid=?",
124836 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
124837 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
124838 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
124839 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
124840
124841           /* Return segments in order from oldest to newest.*/ 
124842 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124843             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
124844 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124845             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
124846             "ORDER BY level DESC, idx ASC",
124847
124848 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
124849 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124850
124851 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
124852 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
124853 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
124854 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
124855 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
124856 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
124857 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
124858 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
124859 /* 24 */  "",
124860 /* 25 */  "",
124861
124862 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124863 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
124864
124865 /* This statement is used to determine which level to read the input from
124866 ** when performing an incremental merge. It returns the absolute level number
124867 ** of the oldest level in the db that contains at least ? segments. Or,
124868 ** if no level in the FTS index contains more than ? segments, the statement
124869 ** returns zero rows.  */
124870 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
124871          "  ORDER BY (level %% 1024) ASC LIMIT 1",
124872
124873 /* Estimate the upper limit on the number of leaf nodes in a new segment
124874 ** created by merging the oldest :2 segments from absolute level :1. See 
124875 ** function sqlite3Fts3Incrmerge() for details.  */
124876 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
124877          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
124878
124879 /* SQL_DELETE_SEGDIR_ENTRY
124880 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
124881 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
124882
124883 /* SQL_SHIFT_SEGDIR_ENTRY
124884 **   Modify the idx value for the segment with idx=:3 on absolute level :2
124885 **   to :1.  */
124886 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
124887
124888 /* SQL_SELECT_SEGDIR
124889 **   Read a single entry from the %_segdir table. The entry from absolute 
124890 **   level :1 with index value :2.  */
124891 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124892             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
124893
124894 /* SQL_CHOMP_SEGDIR
124895 **   Update the start_block (:1) and root (:2) fields of the %_segdir
124896 **   entry located on absolute level :3 with index :4.  */
124897 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
124898             "WHERE level = ? AND idx = ?",
124899
124900 /* SQL_SEGMENT_IS_APPENDABLE
124901 **   Return a single row if the segment with end_block=? is appendable. Or
124902 **   no rows otherwise.  */
124903 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
124904
124905 /* SQL_SELECT_INDEXES
124906 **   Return the list of valid segment indexes for absolute level ?  */
124907 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
124908
124909 /* SQL_SELECT_MXLEVEL
124910 **   Return the largest relative level in the FTS index or indexes.  */
124911 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
124912   };
124913   int rc = SQLITE_OK;
124914   sqlite3_stmt *pStmt;
124915
124916   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
124917   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
124918   
124919   pStmt = p->aStmt[eStmt];
124920   if( !pStmt ){
124921     char *zSql;
124922     if( eStmt==SQL_CONTENT_INSERT ){
124923       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
124924     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
124925       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
124926     }else{
124927       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
124928     }
124929     if( !zSql ){
124930       rc = SQLITE_NOMEM;
124931     }else{
124932       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
124933       sqlite3_free(zSql);
124934       assert( rc==SQLITE_OK || pStmt==0 );
124935       p->aStmt[eStmt] = pStmt;
124936     }
124937   }
124938   if( apVal ){
124939     int i;
124940     int nParam = sqlite3_bind_parameter_count(pStmt);
124941     for(i=0; rc==SQLITE_OK && i<nParam; i++){
124942       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
124943     }
124944   }
124945   *pp = pStmt;
124946   return rc;
124947 }
124948
124949
124950 static int fts3SelectDocsize(
124951   Fts3Table *pTab,                /* FTS3 table handle */
124952   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
124953   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
124954 ){
124955   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
124956   int rc;                         /* Return code */
124957
124958   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
124959   if( rc==SQLITE_OK ){
124960     sqlite3_bind_int64(pStmt, 1, iDocid);
124961     rc = sqlite3_step(pStmt);
124962     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
124963       rc = sqlite3_reset(pStmt);
124964       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
124965       pStmt = 0;
124966     }else{
124967       rc = SQLITE_OK;
124968     }
124969   }
124970
124971   *ppStmt = pStmt;
124972   return rc;
124973 }
124974
124975 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
124976   Fts3Table *pTab,                /* Fts3 table handle */
124977   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
124978 ){
124979   sqlite3_stmt *pStmt = 0;
124980   int rc;
124981   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
124982   if( rc==SQLITE_OK ){
124983     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
124984     if( sqlite3_step(pStmt)!=SQLITE_ROW
124985      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
124986     ){
124987       rc = sqlite3_reset(pStmt);
124988       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
124989       pStmt = 0;
124990     }
124991   }
124992   *ppStmt = pStmt;
124993   return rc;
124994 }
124995
124996 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
124997   Fts3Table *pTab,                /* Fts3 table handle */
124998   sqlite3_int64 iDocid,           /* Docid to read size data for */
124999   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125000 ){
125001   return fts3SelectDocsize(pTab, iDocid, ppStmt);
125002 }
125003
125004 /*
125005 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
125006 ** array apVal[] to the SQL statement identified by eStmt, the statement
125007 ** is executed.
125008 **
125009 ** Returns SQLITE_OK if the statement is successfully executed, or an
125010 ** SQLite error code otherwise.
125011 */
125012 static void fts3SqlExec(
125013   int *pRC,                /* Result code */
125014   Fts3Table *p,            /* The FTS3 table */
125015   int eStmt,               /* Index of statement to evaluate */
125016   sqlite3_value **apVal    /* Parameters to bind */
125017 ){
125018   sqlite3_stmt *pStmt;
125019   int rc;
125020   if( *pRC ) return;
125021   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
125022   if( rc==SQLITE_OK ){
125023     sqlite3_step(pStmt);
125024     rc = sqlite3_reset(pStmt);
125025   }
125026   *pRC = rc;
125027 }
125028
125029
125030 /*
125031 ** This function ensures that the caller has obtained a shared-cache
125032 ** table-lock on the %_content table. This is required before reading
125033 ** data from the fts3 table. If this lock is not acquired first, then
125034 ** the caller may end up holding read-locks on the %_segments and %_segdir
125035 ** tables, but no read-lock on the %_content table. If this happens 
125036 ** a second connection will be able to write to the fts3 table, but
125037 ** attempting to commit those writes might return SQLITE_LOCKED or
125038 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
125039 ** write-locks on the %_segments and %_segdir ** tables). 
125040 **
125041 ** We try to avoid this because if FTS3 returns any error when committing
125042 ** a transaction, the whole transaction will be rolled back. And this is
125043 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
125044 ** still happen if the user reads data directly from the %_segments or
125045 ** %_segdir tables instead of going through FTS3 though.
125046 **
125047 ** This reasoning does not apply to a content=xxx table.
125048 */
125049 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
125050   int rc;                         /* Return code */
125051   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
125052
125053   if( p->zContentTbl==0 ){
125054     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
125055     if( rc==SQLITE_OK ){
125056       sqlite3_bind_null(pStmt, 1);
125057       sqlite3_step(pStmt);
125058       rc = sqlite3_reset(pStmt);
125059     }
125060   }else{
125061     rc = SQLITE_OK;
125062   }
125063
125064   return rc;
125065 }
125066
125067 /*
125068 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
125069 ** Within each language id, a separate index is maintained to store the
125070 ** document terms, and each configured prefix size (configured the FTS 
125071 ** "prefix=" option). And each index consists of multiple levels ("relative
125072 ** levels").
125073 **
125074 ** All three of these values (the language id, the specific index and the
125075 ** level within the index) are encoded in 64-bit integer values stored
125076 ** in the %_segdir table on disk. This function is used to convert three
125077 ** separate component values into the single 64-bit integer value that
125078 ** can be used to query the %_segdir table.
125079 **
125080 ** Specifically, each language-id/index combination is allocated 1024 
125081 ** 64-bit integer level values ("absolute levels"). The main terms index
125082 ** for language-id 0 is allocate values 0-1023. The first prefix index
125083 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
125084 ** Language 1 indexes are allocated immediately following language 0.
125085 **
125086 ** So, for a system with nPrefix prefix indexes configured, the block of
125087 ** absolute levels that corresponds to language-id iLangid and index 
125088 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
125089 */
125090 static sqlite3_int64 getAbsoluteLevel(
125091   Fts3Table *p,                   /* FTS3 table handle */
125092   int iLangid,                    /* Language id */
125093   int iIndex,                     /* Index in p->aIndex[] */
125094   int iLevel                      /* Level of segments */
125095 ){
125096   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
125097   assert( iLangid>=0 );
125098   assert( p->nIndex>0 );
125099   assert( iIndex>=0 && iIndex<p->nIndex );
125100
125101   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
125102   return iBase + iLevel;
125103 }
125104
125105 /*
125106 ** Set *ppStmt to a statement handle that may be used to iterate through
125107 ** all rows in the %_segdir table, from oldest to newest. If successful,
125108 ** return SQLITE_OK. If an error occurs while preparing the statement, 
125109 ** return an SQLite error code.
125110 **
125111 ** There is only ever one instance of this SQL statement compiled for
125112 ** each FTS3 table.
125113 **
125114 ** The statement returns the following columns from the %_segdir table:
125115 **
125116 **   0: idx
125117 **   1: start_block
125118 **   2: leaves_end_block
125119 **   3: end_block
125120 **   4: root
125121 */
125122 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
125123   Fts3Table *p,                   /* FTS3 table */
125124   int iLangid,                    /* Language being queried */
125125   int iIndex,                     /* Index for p->aIndex[] */
125126   int iLevel,                     /* Level to select (relative level) */
125127   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
125128 ){
125129   int rc;
125130   sqlite3_stmt *pStmt = 0;
125131
125132   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
125133   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
125134   assert( iIndex>=0 && iIndex<p->nIndex );
125135
125136   if( iLevel<0 ){
125137     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
125138     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
125139     if( rc==SQLITE_OK ){ 
125140       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
125141       sqlite3_bind_int64(pStmt, 2, 
125142           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
125143       );
125144     }
125145   }else{
125146     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
125147     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
125148     if( rc==SQLITE_OK ){ 
125149       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
125150     }
125151   }
125152   *ppStmt = pStmt;
125153   return rc;
125154 }
125155
125156
125157 /*
125158 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
125159 ** if successful, or an SQLite error code otherwise.
125160 **
125161 ** This function also serves to allocate the PendingList structure itself.
125162 ** For example, to create a new PendingList structure containing two
125163 ** varints:
125164 **
125165 **   PendingList *p = 0;
125166 **   fts3PendingListAppendVarint(&p, 1);
125167 **   fts3PendingListAppendVarint(&p, 2);
125168 */
125169 static int fts3PendingListAppendVarint(
125170   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
125171   sqlite3_int64 i                 /* Value to append to data */
125172 ){
125173   PendingList *p = *pp;
125174
125175   /* Allocate or grow the PendingList as required. */
125176   if( !p ){
125177     p = sqlite3_malloc(sizeof(*p) + 100);
125178     if( !p ){
125179       return SQLITE_NOMEM;
125180     }
125181     p->nSpace = 100;
125182     p->aData = (char *)&p[1];
125183     p->nData = 0;
125184   }
125185   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
125186     int nNew = p->nSpace * 2;
125187     p = sqlite3_realloc(p, sizeof(*p) + nNew);
125188     if( !p ){
125189       sqlite3_free(*pp);
125190       *pp = 0;
125191       return SQLITE_NOMEM;
125192     }
125193     p->nSpace = nNew;
125194     p->aData = (char *)&p[1];
125195   }
125196
125197   /* Append the new serialized varint to the end of the list. */
125198   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
125199   p->aData[p->nData] = '\0';
125200   *pp = p;
125201   return SQLITE_OK;
125202 }
125203
125204 /*
125205 ** Add a docid/column/position entry to a PendingList structure. Non-zero
125206 ** is returned if the structure is sqlite3_realloced as part of adding
125207 ** the entry. Otherwise, zero.
125208 **
125209 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
125210 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
125211 ** it is set to SQLITE_OK.
125212 */
125213 static int fts3PendingListAppend(
125214   PendingList **pp,               /* IN/OUT: PendingList structure */
125215   sqlite3_int64 iDocid,           /* Docid for entry to add */
125216   sqlite3_int64 iCol,             /* Column for entry to add */
125217   sqlite3_int64 iPos,             /* Position of term for entry to add */
125218   int *pRc                        /* OUT: Return code */
125219 ){
125220   PendingList *p = *pp;
125221   int rc = SQLITE_OK;
125222
125223   assert( !p || p->iLastDocid<=iDocid );
125224
125225   if( !p || p->iLastDocid!=iDocid ){
125226     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
125227     if( p ){
125228       assert( p->nData<p->nSpace );
125229       assert( p->aData[p->nData]==0 );
125230       p->nData++;
125231     }
125232     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
125233       goto pendinglistappend_out;
125234     }
125235     p->iLastCol = -1;
125236     p->iLastPos = 0;
125237     p->iLastDocid = iDocid;
125238   }
125239   if( iCol>0 && p->iLastCol!=iCol ){
125240     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
125241      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
125242     ){
125243       goto pendinglistappend_out;
125244     }
125245     p->iLastCol = iCol;
125246     p->iLastPos = 0;
125247   }
125248   if( iCol>=0 ){
125249     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
125250     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
125251     if( rc==SQLITE_OK ){
125252       p->iLastPos = iPos;
125253     }
125254   }
125255
125256  pendinglistappend_out:
125257   *pRc = rc;
125258   if( p!=*pp ){
125259     *pp = p;
125260     return 1;
125261   }
125262   return 0;
125263 }
125264
125265 /*
125266 ** Free a PendingList object allocated by fts3PendingListAppend().
125267 */
125268 static void fts3PendingListDelete(PendingList *pList){
125269   sqlite3_free(pList);
125270 }
125271
125272 /*
125273 ** Add an entry to one of the pending-terms hash tables.
125274 */
125275 static int fts3PendingTermsAddOne(
125276   Fts3Table *p,
125277   int iCol,
125278   int iPos,
125279   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
125280   const char *zToken,
125281   int nToken
125282 ){
125283   PendingList *pList;
125284   int rc = SQLITE_OK;
125285
125286   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
125287   if( pList ){
125288     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
125289   }
125290   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
125291     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
125292       /* Malloc failed while inserting the new entry. This can only 
125293       ** happen if there was no previous entry for this token.
125294       */
125295       assert( 0==fts3HashFind(pHash, zToken, nToken) );
125296       sqlite3_free(pList);
125297       rc = SQLITE_NOMEM;
125298     }
125299   }
125300   if( rc==SQLITE_OK ){
125301     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
125302   }
125303   return rc;
125304 }
125305
125306 /*
125307 ** Tokenize the nul-terminated string zText and add all tokens to the
125308 ** pending-terms hash-table. The docid used is that currently stored in
125309 ** p->iPrevDocid, and the column is specified by argument iCol.
125310 **
125311 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
125312 */
125313 static int fts3PendingTermsAdd(
125314   Fts3Table *p,                   /* Table into which text will be inserted */
125315   int iLangid,                    /* Language id to use */
125316   const char *zText,              /* Text of document to be inserted */
125317   int iCol,                       /* Column into which text is being inserted */
125318   u32 *pnWord                     /* OUT: Number of tokens inserted */
125319 ){
125320   int rc;
125321   int iStart;
125322   int iEnd;
125323   int iPos;
125324   int nWord = 0;
125325
125326   char const *zToken;
125327   int nToken;
125328
125329   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
125330   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125331   sqlite3_tokenizer_cursor *pCsr;
125332   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
125333       const char**,int*,int*,int*,int*);
125334
125335   assert( pTokenizer && pModule );
125336
125337   /* If the user has inserted a NULL value, this function may be called with
125338   ** zText==0. In this case, add zero token entries to the hash table and 
125339   ** return early. */
125340   if( zText==0 ){
125341     *pnWord = 0;
125342     return SQLITE_OK;
125343   }
125344
125345   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
125346   if( rc!=SQLITE_OK ){
125347     return rc;
125348   }
125349
125350   xNext = pModule->xNext;
125351   while( SQLITE_OK==rc
125352       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
125353   ){
125354     int i;
125355     if( iPos>=nWord ) nWord = iPos+1;
125356
125357     /* Positions cannot be negative; we use -1 as a terminator internally.
125358     ** Tokens must have a non-zero length.
125359     */
125360     if( iPos<0 || !zToken || nToken<=0 ){
125361       rc = SQLITE_ERROR;
125362       break;
125363     }
125364
125365     /* Add the term to the terms index */
125366     rc = fts3PendingTermsAddOne(
125367         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
125368     );
125369     
125370     /* Add the term to each of the prefix indexes that it is not too 
125371     ** short for. */
125372     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
125373       struct Fts3Index *pIndex = &p->aIndex[i];
125374       if( nToken<pIndex->nPrefix ) continue;
125375       rc = fts3PendingTermsAddOne(
125376           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
125377       );
125378     }
125379   }
125380
125381   pModule->xClose(pCsr);
125382   *pnWord = nWord;
125383   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
125384 }
125385
125386 /* 
125387 ** Calling this function indicates that subsequent calls to 
125388 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
125389 ** contents of the document with docid iDocid.
125390 */
125391 static int fts3PendingTermsDocid(
125392   Fts3Table *p,                   /* Full-text table handle */
125393   int iLangid,                    /* Language id of row being written */
125394   sqlite_int64 iDocid             /* Docid of row being written */
125395 ){
125396   assert( iLangid>=0 );
125397
125398   /* TODO(shess) Explore whether partially flushing the buffer on
125399   ** forced-flush would provide better performance.  I suspect that if
125400   ** we ordered the doclists by size and flushed the largest until the
125401   ** buffer was half empty, that would let the less frequent terms
125402   ** generate longer doclists.
125403   */
125404   if( iDocid<=p->iPrevDocid 
125405    || p->iPrevLangid!=iLangid
125406    || p->nPendingData>p->nMaxPendingData 
125407   ){
125408     int rc = sqlite3Fts3PendingTermsFlush(p);
125409     if( rc!=SQLITE_OK ) return rc;
125410   }
125411   p->iPrevDocid = iDocid;
125412   p->iPrevLangid = iLangid;
125413   return SQLITE_OK;
125414 }
125415
125416 /*
125417 ** Discard the contents of the pending-terms hash tables. 
125418 */
125419 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
125420   int i;
125421   for(i=0; i<p->nIndex; i++){
125422     Fts3HashElem *pElem;
125423     Fts3Hash *pHash = &p->aIndex[i].hPending;
125424     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
125425       PendingList *pList = (PendingList *)fts3HashData(pElem);
125426       fts3PendingListDelete(pList);
125427     }
125428     fts3HashClear(pHash);
125429   }
125430   p->nPendingData = 0;
125431 }
125432
125433 /*
125434 ** This function is called by the xUpdate() method as part of an INSERT
125435 ** operation. It adds entries for each term in the new record to the
125436 ** pendingTerms hash table.
125437 **
125438 ** Argument apVal is the same as the similarly named argument passed to
125439 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
125440 */
125441 static int fts3InsertTerms(
125442   Fts3Table *p, 
125443   int iLangid, 
125444   sqlite3_value **apVal, 
125445   u32 *aSz
125446 ){
125447   int i;                          /* Iterator variable */
125448   for(i=2; i<p->nColumn+2; i++){
125449     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
125450     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
125451     if( rc!=SQLITE_OK ){
125452       return rc;
125453     }
125454     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
125455   }
125456   return SQLITE_OK;
125457 }
125458
125459 /*
125460 ** This function is called by the xUpdate() method for an INSERT operation.
125461 ** The apVal parameter is passed a copy of the apVal argument passed by
125462 ** SQLite to the xUpdate() method. i.e:
125463 **
125464 **   apVal[0]                Not used for INSERT.
125465 **   apVal[1]                rowid
125466 **   apVal[2]                Left-most user-defined column
125467 **   ...
125468 **   apVal[p->nColumn+1]     Right-most user-defined column
125469 **   apVal[p->nColumn+2]     Hidden column with same name as table
125470 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
125471 **   apVal[p->nColumn+4]     Hidden languageid column
125472 */
125473 static int fts3InsertData(
125474   Fts3Table *p,                   /* Full-text table */
125475   sqlite3_value **apVal,          /* Array of values to insert */
125476   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
125477 ){
125478   int rc;                         /* Return code */
125479   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
125480
125481   if( p->zContentTbl ){
125482     sqlite3_value *pRowid = apVal[p->nColumn+3];
125483     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
125484       pRowid = apVal[1];
125485     }
125486     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
125487       return SQLITE_CONSTRAINT;
125488     }
125489     *piDocid = sqlite3_value_int64(pRowid);
125490     return SQLITE_OK;
125491   }
125492
125493   /* Locate the statement handle used to insert data into the %_content
125494   ** table. The SQL for this statement is:
125495   **
125496   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
125497   **
125498   ** The statement features N '?' variables, where N is the number of user
125499   ** defined columns in the FTS3 table, plus one for the docid field.
125500   */
125501   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
125502   if( rc==SQLITE_OK && p->zLanguageid ){
125503     rc = sqlite3_bind_int(
125504         pContentInsert, p->nColumn+2, 
125505         sqlite3_value_int(apVal[p->nColumn+4])
125506     );
125507   }
125508   if( rc!=SQLITE_OK ) return rc;
125509
125510   /* There is a quirk here. The users INSERT statement may have specified
125511   ** a value for the "rowid" field, for the "docid" field, or for both.
125512   ** Which is a problem, since "rowid" and "docid" are aliases for the
125513   ** same value. For example:
125514   **
125515   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
125516   **
125517   ** In FTS3, this is an error. It is an error to specify non-NULL values
125518   ** for both docid and some other rowid alias.
125519   */
125520   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
125521     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
125522      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
125523     ){
125524       /* A rowid/docid conflict. */
125525       return SQLITE_ERROR;
125526     }
125527     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
125528     if( rc!=SQLITE_OK ) return rc;
125529   }
125530
125531   /* Execute the statement to insert the record. Set *piDocid to the 
125532   ** new docid value. 
125533   */
125534   sqlite3_step(pContentInsert);
125535   rc = sqlite3_reset(pContentInsert);
125536
125537   *piDocid = sqlite3_last_insert_rowid(p->db);
125538   return rc;
125539 }
125540
125541
125542
125543 /*
125544 ** Remove all data from the FTS3 table. Clear the hash table containing
125545 ** pending terms.
125546 */
125547 static int fts3DeleteAll(Fts3Table *p, int bContent){
125548   int rc = SQLITE_OK;             /* Return code */
125549
125550   /* Discard the contents of the pending-terms hash table. */
125551   sqlite3Fts3PendingTermsClear(p);
125552
125553   /* Delete everything from the shadow tables. Except, leave %_content as
125554   ** is if bContent is false.  */
125555   assert( p->zContentTbl==0 || bContent==0 );
125556   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
125557   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
125558   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
125559   if( p->bHasDocsize ){
125560     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
125561   }
125562   if( p->bHasStat ){
125563     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
125564   }
125565   return rc;
125566 }
125567
125568 /*
125569 **
125570 */
125571 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
125572   int iLangid = 0;
125573   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
125574   return iLangid;
125575 }
125576
125577 /*
125578 ** The first element in the apVal[] array is assumed to contain the docid
125579 ** (an integer) of a row about to be deleted. Remove all terms from the
125580 ** full-text index.
125581 */
125582 static void fts3DeleteTerms( 
125583   int *pRC,               /* Result code */
125584   Fts3Table *p,           /* The FTS table to delete from */
125585   sqlite3_value *pRowid,  /* The docid to be deleted */
125586   u32 *aSz                /* Sizes of deleted document written here */
125587 ){
125588   int rc;
125589   sqlite3_stmt *pSelect;
125590
125591   if( *pRC ) return;
125592   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
125593   if( rc==SQLITE_OK ){
125594     if( SQLITE_ROW==sqlite3_step(pSelect) ){
125595       int i;
125596       int iLangid = langidFromSelect(p, pSelect);
125597       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
125598       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
125599         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
125600         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
125601         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
125602       }
125603       if( rc!=SQLITE_OK ){
125604         sqlite3_reset(pSelect);
125605         *pRC = rc;
125606         return;
125607       }
125608     }
125609     rc = sqlite3_reset(pSelect);
125610   }else{
125611     sqlite3_reset(pSelect);
125612   }
125613   *pRC = rc;
125614 }
125615
125616 /*
125617 ** Forward declaration to account for the circular dependency between
125618 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
125619 */
125620 static int fts3SegmentMerge(Fts3Table *, int, int, int);
125621
125622 /* 
125623 ** This function allocates a new level iLevel index in the segdir table.
125624 ** Usually, indexes are allocated within a level sequentially starting
125625 ** with 0, so the allocated index is one greater than the value returned
125626 ** by:
125627 **
125628 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
125629 **
125630 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
125631 ** level, they are merged into a single level (iLevel+1) segment and the 
125632 ** allocated index is 0.
125633 **
125634 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
125635 ** returned. Otherwise, an SQLite error code is returned.
125636 */
125637 static int fts3AllocateSegdirIdx(
125638   Fts3Table *p, 
125639   int iLangid,                    /* Language id */
125640   int iIndex,                     /* Index for p->aIndex */
125641   int iLevel, 
125642   int *piIdx
125643 ){
125644   int rc;                         /* Return Code */
125645   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
125646   int iNext = 0;                  /* Result of query pNextIdx */
125647
125648   assert( iLangid>=0 );
125649   assert( p->nIndex>=1 );
125650
125651   /* Set variable iNext to the next available segdir index at level iLevel. */
125652   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
125653   if( rc==SQLITE_OK ){
125654     sqlite3_bind_int64(
125655         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
125656     );
125657     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
125658       iNext = sqlite3_column_int(pNextIdx, 0);
125659     }
125660     rc = sqlite3_reset(pNextIdx);
125661   }
125662
125663   if( rc==SQLITE_OK ){
125664     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
125665     ** full, merge all segments in level iLevel into a single iLevel+1
125666     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
125667     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
125668     */
125669     if( iNext>=FTS3_MERGE_COUNT ){
125670       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
125671       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
125672       *piIdx = 0;
125673     }else{
125674       *piIdx = iNext;
125675     }
125676   }
125677
125678   return rc;
125679 }
125680
125681 /*
125682 ** The %_segments table is declared as follows:
125683 **
125684 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
125685 **
125686 ** This function reads data from a single row of the %_segments table. The
125687 ** specific row is identified by the iBlockid parameter. If paBlob is not
125688 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
125689 ** with the contents of the blob stored in the "block" column of the 
125690 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
125691 ** to the size of the blob in bytes before returning.
125692 **
125693 ** If an error occurs, or the table does not contain the specified row,
125694 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
125695 ** paBlob is non-NULL, then it is the responsibility of the caller to
125696 ** eventually free the returned buffer.
125697 **
125698 ** This function may leave an open sqlite3_blob* handle in the
125699 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
125700 ** to this function. The handle may be closed by calling the
125701 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
125702 ** performance improvement, but the blob handle should always be closed
125703 ** before control is returned to the user (to prevent a lock being held
125704 ** on the database file for longer than necessary). Thus, any virtual table
125705 ** method (xFilter etc.) that may directly or indirectly call this function
125706 ** must call sqlite3Fts3SegmentsClose() before returning.
125707 */
125708 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
125709   Fts3Table *p,                   /* FTS3 table handle */
125710   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
125711   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
125712   int *pnBlob,                    /* OUT: Size of blob data */
125713   int *pnLoad                     /* OUT: Bytes actually loaded */
125714 ){
125715   int rc;                         /* Return code */
125716
125717   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
125718   assert( pnBlob );
125719
125720   if( p->pSegments ){
125721     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
125722   }else{
125723     if( 0==p->zSegmentsTbl ){
125724       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
125725       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
125726     }
125727     rc = sqlite3_blob_open(
125728        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
125729     );
125730   }
125731
125732   if( rc==SQLITE_OK ){
125733     int nByte = sqlite3_blob_bytes(p->pSegments);
125734     *pnBlob = nByte;
125735     if( paBlob ){
125736       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
125737       if( !aByte ){
125738         rc = SQLITE_NOMEM;
125739       }else{
125740         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
125741           nByte = FTS3_NODE_CHUNKSIZE;
125742           *pnLoad = nByte;
125743         }
125744         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
125745         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
125746         if( rc!=SQLITE_OK ){
125747           sqlite3_free(aByte);
125748           aByte = 0;
125749         }
125750       }
125751       *paBlob = aByte;
125752     }
125753   }
125754
125755   return rc;
125756 }
125757
125758 /*
125759 ** Close the blob handle at p->pSegments, if it is open. See comments above
125760 ** the sqlite3Fts3ReadBlock() function for details.
125761 */
125762 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
125763   sqlite3_blob_close(p->pSegments);
125764   p->pSegments = 0;
125765 }
125766     
125767 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
125768   int nRead;                      /* Number of bytes to read */
125769   int rc;                         /* Return code */
125770
125771   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
125772   rc = sqlite3_blob_read(
125773       pReader->pBlob, 
125774       &pReader->aNode[pReader->nPopulate],
125775       nRead,
125776       pReader->nPopulate
125777   );
125778
125779   if( rc==SQLITE_OK ){
125780     pReader->nPopulate += nRead;
125781     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
125782     if( pReader->nPopulate==pReader->nNode ){
125783       sqlite3_blob_close(pReader->pBlob);
125784       pReader->pBlob = 0;
125785       pReader->nPopulate = 0;
125786     }
125787   }
125788   return rc;
125789 }
125790
125791 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
125792   int rc = SQLITE_OK;
125793   assert( !pReader->pBlob 
125794        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
125795   );
125796   while( pReader->pBlob && rc==SQLITE_OK 
125797      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
125798   ){
125799     rc = fts3SegReaderIncrRead(pReader);
125800   }
125801   return rc;
125802 }
125803
125804 /*
125805 ** Set an Fts3SegReader cursor to point at EOF.
125806 */
125807 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
125808   if( !fts3SegReaderIsRootOnly(pSeg) ){
125809     sqlite3_free(pSeg->aNode);
125810     sqlite3_blob_close(pSeg->pBlob);
125811     pSeg->pBlob = 0;
125812   }
125813   pSeg->aNode = 0;
125814 }
125815
125816 /*
125817 ** Move the iterator passed as the first argument to the next term in the
125818 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
125819 ** SQLITE_DONE. Otherwise, an SQLite error code.
125820 */
125821 static int fts3SegReaderNext(
125822   Fts3Table *p, 
125823   Fts3SegReader *pReader,
125824   int bIncr
125825 ){
125826   int rc;                         /* Return code of various sub-routines */
125827   char *pNext;                    /* Cursor variable */
125828   int nPrefix;                    /* Number of bytes in term prefix */
125829   int nSuffix;                    /* Number of bytes in term suffix */
125830
125831   if( !pReader->aDoclist ){
125832     pNext = pReader->aNode;
125833   }else{
125834     pNext = &pReader->aDoclist[pReader->nDoclist];
125835   }
125836
125837   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
125838
125839     if( fts3SegReaderIsPending(pReader) ){
125840       Fts3HashElem *pElem = *(pReader->ppNextElem);
125841       if( pElem==0 ){
125842         pReader->aNode = 0;
125843       }else{
125844         PendingList *pList = (PendingList *)fts3HashData(pElem);
125845         pReader->zTerm = (char *)fts3HashKey(pElem);
125846         pReader->nTerm = fts3HashKeysize(pElem);
125847         pReader->nNode = pReader->nDoclist = pList->nData + 1;
125848         pReader->aNode = pReader->aDoclist = pList->aData;
125849         pReader->ppNextElem++;
125850         assert( pReader->aNode );
125851       }
125852       return SQLITE_OK;
125853     }
125854
125855     fts3SegReaderSetEof(pReader);
125856
125857     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
125858     ** blocks have already been traversed.  */
125859     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
125860     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
125861       return SQLITE_OK;
125862     }
125863
125864     rc = sqlite3Fts3ReadBlock(
125865         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
125866         (bIncr ? &pReader->nPopulate : 0)
125867     );
125868     if( rc!=SQLITE_OK ) return rc;
125869     assert( pReader->pBlob==0 );
125870     if( bIncr && pReader->nPopulate<pReader->nNode ){
125871       pReader->pBlob = p->pSegments;
125872       p->pSegments = 0;
125873     }
125874     pNext = pReader->aNode;
125875   }
125876
125877   assert( !fts3SegReaderIsPending(pReader) );
125878
125879   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
125880   if( rc!=SQLITE_OK ) return rc;
125881   
125882   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
125883   ** safe (no risk of overread) even if the node data is corrupted. */
125884   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
125885   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
125886   if( nPrefix<0 || nSuffix<=0 
125887    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
125888   ){
125889     return FTS_CORRUPT_VTAB;
125890   }
125891
125892   if( nPrefix+nSuffix>pReader->nTermAlloc ){
125893     int nNew = (nPrefix+nSuffix)*2;
125894     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
125895     if( !zNew ){
125896       return SQLITE_NOMEM;
125897     }
125898     pReader->zTerm = zNew;
125899     pReader->nTermAlloc = nNew;
125900   }
125901
125902   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
125903   if( rc!=SQLITE_OK ) return rc;
125904
125905   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
125906   pReader->nTerm = nPrefix+nSuffix;
125907   pNext += nSuffix;
125908   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
125909   pReader->aDoclist = pNext;
125910   pReader->pOffsetList = 0;
125911
125912   /* Check that the doclist does not appear to extend past the end of the
125913   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
125914   ** of these statements is untrue, then the data structure is corrupt.
125915   */
125916   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
125917    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
125918   ){
125919     return FTS_CORRUPT_VTAB;
125920   }
125921   return SQLITE_OK;
125922 }
125923
125924 /*
125925 ** Set the SegReader to point to the first docid in the doclist associated
125926 ** with the current term.
125927 */
125928 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
125929   int rc = SQLITE_OK;
125930   assert( pReader->aDoclist );
125931   assert( !pReader->pOffsetList );
125932   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125933     u8 bEof = 0;
125934     pReader->iDocid = 0;
125935     pReader->nOffsetList = 0;
125936     sqlite3Fts3DoclistPrev(0,
125937         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
125938         &pReader->iDocid, &pReader->nOffsetList, &bEof
125939     );
125940   }else{
125941     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
125942     if( rc==SQLITE_OK ){
125943       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
125944       pReader->pOffsetList = &pReader->aDoclist[n];
125945     }
125946   }
125947   return rc;
125948 }
125949
125950 /*
125951 ** Advance the SegReader to point to the next docid in the doclist
125952 ** associated with the current term.
125953 ** 
125954 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
125955 ** *ppOffsetList is set to point to the first column-offset list
125956 ** in the doclist entry (i.e. immediately past the docid varint).
125957 ** *pnOffsetList is set to the length of the set of column-offset
125958 ** lists, not including the nul-terminator byte. For example:
125959 */
125960 static int fts3SegReaderNextDocid(
125961   Fts3Table *pTab,
125962   Fts3SegReader *pReader,         /* Reader to advance to next docid */
125963   char **ppOffsetList,            /* OUT: Pointer to current position-list */
125964   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
125965 ){
125966   int rc = SQLITE_OK;
125967   char *p = pReader->pOffsetList;
125968   char c = 0;
125969
125970   assert( p );
125971
125972   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125973     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
125974     ** Pending-terms doclists are always built up in ascending order, so
125975     ** we have to iterate through them backwards here. */
125976     u8 bEof = 0;
125977     if( ppOffsetList ){
125978       *ppOffsetList = pReader->pOffsetList;
125979       *pnOffsetList = pReader->nOffsetList - 1;
125980     }
125981     sqlite3Fts3DoclistPrev(0,
125982         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
125983         &pReader->nOffsetList, &bEof
125984     );
125985     if( bEof ){
125986       pReader->pOffsetList = 0;
125987     }else{
125988       pReader->pOffsetList = p;
125989     }
125990   }else{
125991     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
125992
125993     /* Pointer p currently points at the first byte of an offset list. The
125994     ** following block advances it to point one byte past the end of
125995     ** the same offset list. */
125996     while( 1 ){
125997   
125998       /* The following line of code (and the "p++" below the while() loop) is
125999       ** normally all that is required to move pointer p to the desired 
126000       ** position. The exception is if this node is being loaded from disk
126001       ** incrementally and pointer "p" now points to the first byte passed
126002       ** the populated part of pReader->aNode[].
126003       */
126004       while( *p | c ) c = *p++ & 0x80;
126005       assert( *p==0 );
126006   
126007       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
126008       rc = fts3SegReaderIncrRead(pReader);
126009       if( rc!=SQLITE_OK ) return rc;
126010     }
126011     p++;
126012   
126013     /* If required, populate the output variables with a pointer to and the
126014     ** size of the previous offset-list.
126015     */
126016     if( ppOffsetList ){
126017       *ppOffsetList = pReader->pOffsetList;
126018       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
126019     }
126020
126021     while( p<pEnd && *p==0 ) p++;
126022   
126023     /* If there are no more entries in the doclist, set pOffsetList to
126024     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
126025     ** Fts3SegReader.pOffsetList to point to the next offset list before
126026     ** returning.
126027     */
126028     if( p>=pEnd ){
126029       pReader->pOffsetList = 0;
126030     }else{
126031       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
126032       if( rc==SQLITE_OK ){
126033         sqlite3_int64 iDelta;
126034         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
126035         if( pTab->bDescIdx ){
126036           pReader->iDocid -= iDelta;
126037         }else{
126038           pReader->iDocid += iDelta;
126039         }
126040       }
126041     }
126042   }
126043
126044   return SQLITE_OK;
126045 }
126046
126047
126048 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
126049   Fts3Cursor *pCsr, 
126050   Fts3MultiSegReader *pMsr,
126051   int *pnOvfl
126052 ){
126053   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
126054   int nOvfl = 0;
126055   int ii;
126056   int rc = SQLITE_OK;
126057   int pgsz = p->nPgsz;
126058
126059   assert( p->bFts4 );
126060   assert( pgsz>0 );
126061
126062   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
126063     Fts3SegReader *pReader = pMsr->apSegment[ii];
126064     if( !fts3SegReaderIsPending(pReader) 
126065      && !fts3SegReaderIsRootOnly(pReader) 
126066     ){
126067       sqlite3_int64 jj;
126068       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
126069         int nBlob;
126070         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
126071         if( rc!=SQLITE_OK ) break;
126072         if( (nBlob+35)>pgsz ){
126073           nOvfl += (nBlob + 34)/pgsz;
126074         }
126075       }
126076     }
126077   }
126078   *pnOvfl = nOvfl;
126079   return rc;
126080 }
126081
126082 /*
126083 ** Free all allocations associated with the iterator passed as the 
126084 ** second argument.
126085 */
126086 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
126087   if( pReader && !fts3SegReaderIsPending(pReader) ){
126088     sqlite3_free(pReader->zTerm);
126089     if( !fts3SegReaderIsRootOnly(pReader) ){
126090       sqlite3_free(pReader->aNode);
126091       sqlite3_blob_close(pReader->pBlob);
126092     }
126093   }
126094   sqlite3_free(pReader);
126095 }
126096
126097 /*
126098 ** Allocate a new SegReader object.
126099 */
126100 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
126101   int iAge,                       /* Segment "age". */
126102   int bLookup,                    /* True for a lookup only */
126103   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
126104   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
126105   sqlite3_int64 iEndBlock,        /* Final block of segment */
126106   const char *zRoot,              /* Buffer containing root node */
126107   int nRoot,                      /* Size of buffer containing root node */
126108   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
126109 ){
126110   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
126111   int nExtra = 0;                 /* Bytes to allocate segment root node */
126112
126113   assert( iStartLeaf<=iEndLeaf );
126114   if( iStartLeaf==0 ){
126115     nExtra = nRoot + FTS3_NODE_PADDING;
126116   }
126117
126118   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
126119   if( !pReader ){
126120     return SQLITE_NOMEM;
126121   }
126122   memset(pReader, 0, sizeof(Fts3SegReader));
126123   pReader->iIdx = iAge;
126124   pReader->bLookup = bLookup!=0;
126125   pReader->iStartBlock = iStartLeaf;
126126   pReader->iLeafEndBlock = iEndLeaf;
126127   pReader->iEndBlock = iEndBlock;
126128
126129   if( nExtra ){
126130     /* The entire segment is stored in the root node. */
126131     pReader->aNode = (char *)&pReader[1];
126132     pReader->rootOnly = 1;
126133     pReader->nNode = nRoot;
126134     memcpy(pReader->aNode, zRoot, nRoot);
126135     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
126136   }else{
126137     pReader->iCurrentBlock = iStartLeaf-1;
126138   }
126139   *ppReader = pReader;
126140   return SQLITE_OK;
126141 }
126142
126143 /*
126144 ** This is a comparison function used as a qsort() callback when sorting
126145 ** an array of pending terms by term. This occurs as part of flushing
126146 ** the contents of the pending-terms hash table to the database.
126147 */
126148 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
126149   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
126150   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
126151   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
126152   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
126153
126154   int n = (n1<n2 ? n1 : n2);
126155   int c = memcmp(z1, z2, n);
126156   if( c==0 ){
126157     c = n1 - n2;
126158   }
126159   return c;
126160 }
126161
126162 /*
126163 ** This function is used to allocate an Fts3SegReader that iterates through
126164 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
126165 **
126166 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
126167 ** through each term in the pending-terms table. Or, if isPrefixIter is
126168 ** non-zero, it iterates through each term and its prefixes. For example, if
126169 ** the pending terms hash table contains the terms "sqlite", "mysql" and
126170 ** "firebird", then the iterator visits the following 'terms' (in the order
126171 ** shown):
126172 **
126173 **   f fi fir fire fireb firebi firebir firebird
126174 **   m my mys mysq mysql
126175 **   s sq sql sqli sqlit sqlite
126176 **
126177 ** Whereas if isPrefixIter is zero, the terms visited are:
126178 **
126179 **   firebird mysql sqlite
126180 */
126181 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
126182   Fts3Table *p,                   /* Virtual table handle */
126183   int iIndex,                     /* Index for p->aIndex */
126184   const char *zTerm,              /* Term to search for */
126185   int nTerm,                      /* Size of buffer zTerm */
126186   int bPrefix,                    /* True for a prefix iterator */
126187   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
126188 ){
126189   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
126190   Fts3HashElem *pE;               /* Iterator variable */
126191   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
126192   int nElem = 0;                  /* Size of array at aElem */
126193   int rc = SQLITE_OK;             /* Return Code */
126194   Fts3Hash *pHash;
126195
126196   pHash = &p->aIndex[iIndex].hPending;
126197   if( bPrefix ){
126198     int nAlloc = 0;               /* Size of allocated array at aElem */
126199
126200     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
126201       char *zKey = (char *)fts3HashKey(pE);
126202       int nKey = fts3HashKeysize(pE);
126203       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
126204         if( nElem==nAlloc ){
126205           Fts3HashElem **aElem2;
126206           nAlloc += 16;
126207           aElem2 = (Fts3HashElem **)sqlite3_realloc(
126208               aElem, nAlloc*sizeof(Fts3HashElem *)
126209           );
126210           if( !aElem2 ){
126211             rc = SQLITE_NOMEM;
126212             nElem = 0;
126213             break;
126214           }
126215           aElem = aElem2;
126216         }
126217
126218         aElem[nElem++] = pE;
126219       }
126220     }
126221
126222     /* If more than one term matches the prefix, sort the Fts3HashElem
126223     ** objects in term order using qsort(). This uses the same comparison
126224     ** callback as is used when flushing terms to disk.
126225     */
126226     if( nElem>1 ){
126227       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
126228     }
126229
126230   }else{
126231     /* The query is a simple term lookup that matches at most one term in
126232     ** the index. All that is required is a straight hash-lookup. 
126233     **
126234     ** Because the stack address of pE may be accessed via the aElem pointer
126235     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
126236     ** within this entire function, not just this "else{...}" block.
126237     */
126238     pE = fts3HashFindElem(pHash, zTerm, nTerm);
126239     if( pE ){
126240       aElem = &pE;
126241       nElem = 1;
126242     }
126243   }
126244
126245   if( nElem>0 ){
126246     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
126247     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
126248     if( !pReader ){
126249       rc = SQLITE_NOMEM;
126250     }else{
126251       memset(pReader, 0, nByte);
126252       pReader->iIdx = 0x7FFFFFFF;
126253       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
126254       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
126255     }
126256   }
126257
126258   if( bPrefix ){
126259     sqlite3_free(aElem);
126260   }
126261   *ppReader = pReader;
126262   return rc;
126263 }
126264
126265 /*
126266 ** Compare the entries pointed to by two Fts3SegReader structures. 
126267 ** Comparison is as follows:
126268 **
126269 **   1) EOF is greater than not EOF.
126270 **
126271 **   2) The current terms (if any) are compared using memcmp(). If one
126272 **      term is a prefix of another, the longer term is considered the
126273 **      larger.
126274 **
126275 **   3) By segment age. An older segment is considered larger.
126276 */
126277 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126278   int rc;
126279   if( pLhs->aNode && pRhs->aNode ){
126280     int rc2 = pLhs->nTerm - pRhs->nTerm;
126281     if( rc2<0 ){
126282       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
126283     }else{
126284       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
126285     }
126286     if( rc==0 ){
126287       rc = rc2;
126288     }
126289   }else{
126290     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
126291   }
126292   if( rc==0 ){
126293     rc = pRhs->iIdx - pLhs->iIdx;
126294   }
126295   assert( rc!=0 );
126296   return rc;
126297 }
126298
126299 /*
126300 ** A different comparison function for SegReader structures. In this
126301 ** version, it is assumed that each SegReader points to an entry in
126302 ** a doclist for identical terms. Comparison is made as follows:
126303 **
126304 **   1) EOF (end of doclist in this case) is greater than not EOF.
126305 **
126306 **   2) By current docid.
126307 **
126308 **   3) By segment age. An older segment is considered larger.
126309 */
126310 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126311   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126312   if( rc==0 ){
126313     if( pLhs->iDocid==pRhs->iDocid ){
126314       rc = pRhs->iIdx - pLhs->iIdx;
126315     }else{
126316       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
126317     }
126318   }
126319   assert( pLhs->aNode && pRhs->aNode );
126320   return rc;
126321 }
126322 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126323   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126324   if( rc==0 ){
126325     if( pLhs->iDocid==pRhs->iDocid ){
126326       rc = pRhs->iIdx - pLhs->iIdx;
126327     }else{
126328       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
126329     }
126330   }
126331   assert( pLhs->aNode && pRhs->aNode );
126332   return rc;
126333 }
126334
126335 /*
126336 ** Compare the term that the Fts3SegReader object passed as the first argument
126337 ** points to with the term specified by arguments zTerm and nTerm. 
126338 **
126339 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
126340 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
126341 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
126342 */
126343 static int fts3SegReaderTermCmp(
126344   Fts3SegReader *pSeg,            /* Segment reader object */
126345   const char *zTerm,              /* Term to compare to */
126346   int nTerm                       /* Size of term zTerm in bytes */
126347 ){
126348   int res = 0;
126349   if( pSeg->aNode ){
126350     if( pSeg->nTerm>nTerm ){
126351       res = memcmp(pSeg->zTerm, zTerm, nTerm);
126352     }else{
126353       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
126354     }
126355     if( res==0 ){
126356       res = pSeg->nTerm-nTerm;
126357     }
126358   }
126359   return res;
126360 }
126361
126362 /*
126363 ** Argument apSegment is an array of nSegment elements. It is known that
126364 ** the final (nSegment-nSuspect) members are already in sorted order
126365 ** (according to the comparison function provided). This function shuffles
126366 ** the array around until all entries are in sorted order.
126367 */
126368 static void fts3SegReaderSort(
126369   Fts3SegReader **apSegment,                     /* Array to sort entries of */
126370   int nSegment,                                  /* Size of apSegment array */
126371   int nSuspect,                                  /* Unsorted entry count */
126372   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
126373 ){
126374   int i;                          /* Iterator variable */
126375
126376   assert( nSuspect<=nSegment );
126377
126378   if( nSuspect==nSegment ) nSuspect--;
126379   for(i=nSuspect-1; i>=0; i--){
126380     int j;
126381     for(j=i; j<(nSegment-1); j++){
126382       Fts3SegReader *pTmp;
126383       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
126384       pTmp = apSegment[j+1];
126385       apSegment[j+1] = apSegment[j];
126386       apSegment[j] = pTmp;
126387     }
126388   }
126389
126390 #ifndef NDEBUG
126391   /* Check that the list really is sorted now. */
126392   for(i=0; i<(nSuspect-1); i++){
126393     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
126394   }
126395 #endif
126396 }
126397
126398 /* 
126399 ** Insert a record into the %_segments table.
126400 */
126401 static int fts3WriteSegment(
126402   Fts3Table *p,                   /* Virtual table handle */
126403   sqlite3_int64 iBlock,           /* Block id for new block */
126404   char *z,                        /* Pointer to buffer containing block data */
126405   int n                           /* Size of buffer z in bytes */
126406 ){
126407   sqlite3_stmt *pStmt;
126408   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
126409   if( rc==SQLITE_OK ){
126410     sqlite3_bind_int64(pStmt, 1, iBlock);
126411     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
126412     sqlite3_step(pStmt);
126413     rc = sqlite3_reset(pStmt);
126414   }
126415   return rc;
126416 }
126417
126418 /*
126419 ** Find the largest relative level number in the table. If successful, set
126420 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
126421 ** set *pnMax to zero and return an SQLite error code.
126422 */
126423 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
126424   int rc;
126425   int mxLevel = 0;
126426   sqlite3_stmt *pStmt = 0;
126427
126428   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
126429   if( rc==SQLITE_OK ){
126430     if( SQLITE_ROW==sqlite3_step(pStmt) ){
126431       mxLevel = sqlite3_column_int(pStmt, 0);
126432     }
126433     rc = sqlite3_reset(pStmt);
126434   }
126435   *pnMax = mxLevel;
126436   return rc;
126437 }
126438
126439 /* 
126440 ** Insert a record into the %_segdir table.
126441 */
126442 static int fts3WriteSegdir(
126443   Fts3Table *p,                   /* Virtual table handle */
126444   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
126445   int iIdx,                       /* Value for "idx" field */
126446   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
126447   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
126448   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
126449   char *zRoot,                    /* Blob value for "root" field */
126450   int nRoot                       /* Number of bytes in buffer zRoot */
126451 ){
126452   sqlite3_stmt *pStmt;
126453   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
126454   if( rc==SQLITE_OK ){
126455     sqlite3_bind_int64(pStmt, 1, iLevel);
126456     sqlite3_bind_int(pStmt, 2, iIdx);
126457     sqlite3_bind_int64(pStmt, 3, iStartBlock);
126458     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
126459     sqlite3_bind_int64(pStmt, 5, iEndBlock);
126460     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
126461     sqlite3_step(pStmt);
126462     rc = sqlite3_reset(pStmt);
126463   }
126464   return rc;
126465 }
126466
126467 /*
126468 ** Return the size of the common prefix (if any) shared by zPrev and
126469 ** zNext, in bytes. For example, 
126470 **
126471 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
126472 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
126473 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
126474 */
126475 static int fts3PrefixCompress(
126476   const char *zPrev,              /* Buffer containing previous term */
126477   int nPrev,                      /* Size of buffer zPrev in bytes */
126478   const char *zNext,              /* Buffer containing next term */
126479   int nNext                       /* Size of buffer zNext in bytes */
126480 ){
126481   int n;
126482   UNUSED_PARAMETER(nNext);
126483   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
126484   return n;
126485 }
126486
126487 /*
126488 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
126489 ** (according to memcmp) than the previous term.
126490 */
126491 static int fts3NodeAddTerm(
126492   Fts3Table *p,                   /* Virtual table handle */
126493   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
126494   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
126495   const char *zTerm,              /* Pointer to buffer containing term */
126496   int nTerm                       /* Size of term in bytes */
126497 ){
126498   SegmentNode *pTree = *ppTree;
126499   int rc;
126500   SegmentNode *pNew;
126501
126502   /* First try to append the term to the current node. Return early if 
126503   ** this is possible.
126504   */
126505   if( pTree ){
126506     int nData = pTree->nData;     /* Current size of node in bytes */
126507     int nReq = nData;             /* Required space after adding zTerm */
126508     int nPrefix;                  /* Number of bytes of prefix compression */
126509     int nSuffix;                  /* Suffix length */
126510
126511     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
126512     nSuffix = nTerm-nPrefix;
126513
126514     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
126515     if( nReq<=p->nNodeSize || !pTree->zTerm ){
126516
126517       if( nReq>p->nNodeSize ){
126518         /* An unusual case: this is the first term to be added to the node
126519         ** and the static node buffer (p->nNodeSize bytes) is not large
126520         ** enough. Use a separately malloced buffer instead This wastes
126521         ** p->nNodeSize bytes, but since this scenario only comes about when
126522         ** the database contain two terms that share a prefix of almost 2KB, 
126523         ** this is not expected to be a serious problem. 
126524         */
126525         assert( pTree->aData==(char *)&pTree[1] );
126526         pTree->aData = (char *)sqlite3_malloc(nReq);
126527         if( !pTree->aData ){
126528           return SQLITE_NOMEM;
126529         }
126530       }
126531
126532       if( pTree->zTerm ){
126533         /* There is no prefix-length field for first term in a node */
126534         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
126535       }
126536
126537       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
126538       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
126539       pTree->nData = nData + nSuffix;
126540       pTree->nEntry++;
126541
126542       if( isCopyTerm ){
126543         if( pTree->nMalloc<nTerm ){
126544           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
126545           if( !zNew ){
126546             return SQLITE_NOMEM;
126547           }
126548           pTree->nMalloc = nTerm*2;
126549           pTree->zMalloc = zNew;
126550         }
126551         pTree->zTerm = pTree->zMalloc;
126552         memcpy(pTree->zTerm, zTerm, nTerm);
126553         pTree->nTerm = nTerm;
126554       }else{
126555         pTree->zTerm = (char *)zTerm;
126556         pTree->nTerm = nTerm;
126557       }
126558       return SQLITE_OK;
126559     }
126560   }
126561
126562   /* If control flows to here, it was not possible to append zTerm to the
126563   ** current node. Create a new node (a right-sibling of the current node).
126564   ** If this is the first node in the tree, the term is added to it.
126565   **
126566   ** Otherwise, the term is not added to the new node, it is left empty for
126567   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
126568   ** has no parent, one is created here.
126569   */
126570   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
126571   if( !pNew ){
126572     return SQLITE_NOMEM;
126573   }
126574   memset(pNew, 0, sizeof(SegmentNode));
126575   pNew->nData = 1 + FTS3_VARINT_MAX;
126576   pNew->aData = (char *)&pNew[1];
126577
126578   if( pTree ){
126579     SegmentNode *pParent = pTree->pParent;
126580     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
126581     if( pTree->pParent==0 ){
126582       pTree->pParent = pParent;
126583     }
126584     pTree->pRight = pNew;
126585     pNew->pLeftmost = pTree->pLeftmost;
126586     pNew->pParent = pParent;
126587     pNew->zMalloc = pTree->zMalloc;
126588     pNew->nMalloc = pTree->nMalloc;
126589     pTree->zMalloc = 0;
126590   }else{
126591     pNew->pLeftmost = pNew;
126592     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
126593   }
126594
126595   *ppTree = pNew;
126596   return rc;
126597 }
126598
126599 /*
126600 ** Helper function for fts3NodeWrite().
126601 */
126602 static int fts3TreeFinishNode(
126603   SegmentNode *pTree, 
126604   int iHeight, 
126605   sqlite3_int64 iLeftChild
126606 ){
126607   int nStart;
126608   assert( iHeight>=1 && iHeight<128 );
126609   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
126610   pTree->aData[nStart] = (char)iHeight;
126611   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
126612   return nStart;
126613 }
126614
126615 /*
126616 ** Write the buffer for the segment node pTree and all of its peers to the
126617 ** database. Then call this function recursively to write the parent of 
126618 ** pTree and its peers to the database. 
126619 **
126620 ** Except, if pTree is a root node, do not write it to the database. Instead,
126621 ** set output variables *paRoot and *pnRoot to contain the root node.
126622 **
126623 ** If successful, SQLITE_OK is returned and output variable *piLast is
126624 ** set to the largest blockid written to the database (or zero if no
126625 ** blocks were written to the db). Otherwise, an SQLite error code is 
126626 ** returned.
126627 */
126628 static int fts3NodeWrite(
126629   Fts3Table *p,                   /* Virtual table handle */
126630   SegmentNode *pTree,             /* SegmentNode handle */
126631   int iHeight,                    /* Height of this node in tree */
126632   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
126633   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
126634   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
126635   char **paRoot,                  /* OUT: Data for root node */
126636   int *pnRoot                     /* OUT: Size of root node in bytes */
126637 ){
126638   int rc = SQLITE_OK;
126639
126640   if( !pTree->pParent ){
126641     /* Root node of the tree. */
126642     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
126643     *piLast = iFree-1;
126644     *pnRoot = pTree->nData - nStart;
126645     *paRoot = &pTree->aData[nStart];
126646   }else{
126647     SegmentNode *pIter;
126648     sqlite3_int64 iNextFree = iFree;
126649     sqlite3_int64 iNextLeaf = iLeaf;
126650     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
126651       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
126652       int nWrite = pIter->nData - nStart;
126653   
126654       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
126655       iNextFree++;
126656       iNextLeaf += (pIter->nEntry+1);
126657     }
126658     if( rc==SQLITE_OK ){
126659       assert( iNextLeaf==iFree );
126660       rc = fts3NodeWrite(
126661           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
126662       );
126663     }
126664   }
126665
126666   return rc;
126667 }
126668
126669 /*
126670 ** Free all memory allocations associated with the tree pTree.
126671 */
126672 static void fts3NodeFree(SegmentNode *pTree){
126673   if( pTree ){
126674     SegmentNode *p = pTree->pLeftmost;
126675     fts3NodeFree(p->pParent);
126676     while( p ){
126677       SegmentNode *pRight = p->pRight;
126678       if( p->aData!=(char *)&p[1] ){
126679         sqlite3_free(p->aData);
126680       }
126681       assert( pRight==0 || p->zMalloc==0 );
126682       sqlite3_free(p->zMalloc);
126683       sqlite3_free(p);
126684       p = pRight;
126685     }
126686   }
126687 }
126688
126689 /*
126690 ** Add a term to the segment being constructed by the SegmentWriter object
126691 ** *ppWriter. When adding the first term to a segment, *ppWriter should
126692 ** be passed NULL. This function will allocate a new SegmentWriter object
126693 ** and return it via the input/output variable *ppWriter in this case.
126694 **
126695 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
126696 */
126697 static int fts3SegWriterAdd(
126698   Fts3Table *p,                   /* Virtual table handle */
126699   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
126700   int isCopyTerm,                 /* True if buffer zTerm must be copied */
126701   const char *zTerm,              /* Pointer to buffer containing term */
126702   int nTerm,                      /* Size of term in bytes */
126703   const char *aDoclist,           /* Pointer to buffer containing doclist */
126704   int nDoclist                    /* Size of doclist in bytes */
126705 ){
126706   int nPrefix;                    /* Size of term prefix in bytes */
126707   int nSuffix;                    /* Size of term suffix in bytes */
126708   int nReq;                       /* Number of bytes required on leaf page */
126709   int nData;
126710   SegmentWriter *pWriter = *ppWriter;
126711
126712   if( !pWriter ){
126713     int rc;
126714     sqlite3_stmt *pStmt;
126715
126716     /* Allocate the SegmentWriter structure */
126717     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
126718     if( !pWriter ) return SQLITE_NOMEM;
126719     memset(pWriter, 0, sizeof(SegmentWriter));
126720     *ppWriter = pWriter;
126721
126722     /* Allocate a buffer in which to accumulate data */
126723     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
126724     if( !pWriter->aData ) return SQLITE_NOMEM;
126725     pWriter->nSize = p->nNodeSize;
126726
126727     /* Find the next free blockid in the %_segments table */
126728     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
126729     if( rc!=SQLITE_OK ) return rc;
126730     if( SQLITE_ROW==sqlite3_step(pStmt) ){
126731       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
126732       pWriter->iFirst = pWriter->iFree;
126733     }
126734     rc = sqlite3_reset(pStmt);
126735     if( rc!=SQLITE_OK ) return rc;
126736   }
126737   nData = pWriter->nData;
126738
126739   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
126740   nSuffix = nTerm-nPrefix;
126741
126742   /* Figure out how many bytes are required by this new entry */
126743   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
126744     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
126745     nSuffix +                               /* Term suffix */
126746     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
126747     nDoclist;                               /* Doclist data */
126748
126749   if( nData>0 && nData+nReq>p->nNodeSize ){
126750     int rc;
126751
126752     /* The current leaf node is full. Write it out to the database. */
126753     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
126754     if( rc!=SQLITE_OK ) return rc;
126755     p->nLeafAdd++;
126756
126757     /* Add the current term to the interior node tree. The term added to
126758     ** the interior tree must:
126759     **
126760     **   a) be greater than the largest term on the leaf node just written
126761     **      to the database (still available in pWriter->zTerm), and
126762     **
126763     **   b) be less than or equal to the term about to be added to the new
126764     **      leaf node (zTerm/nTerm).
126765     **
126766     ** In other words, it must be the prefix of zTerm 1 byte longer than
126767     ** the common prefix (if any) of zTerm and pWriter->zTerm.
126768     */
126769     assert( nPrefix<nTerm );
126770     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
126771     if( rc!=SQLITE_OK ) return rc;
126772
126773     nData = 0;
126774     pWriter->nTerm = 0;
126775
126776     nPrefix = 0;
126777     nSuffix = nTerm;
126778     nReq = 1 +                              /* varint containing prefix size */
126779       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
126780       nTerm +                               /* Term suffix */
126781       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
126782       nDoclist;                             /* Doclist data */
126783   }
126784
126785   /* If the buffer currently allocated is too small for this entry, realloc
126786   ** the buffer to make it large enough.
126787   */
126788   if( nReq>pWriter->nSize ){
126789     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
126790     if( !aNew ) return SQLITE_NOMEM;
126791     pWriter->aData = aNew;
126792     pWriter->nSize = nReq;
126793   }
126794   assert( nData+nReq<=pWriter->nSize );
126795
126796   /* Append the prefix-compressed term and doclist to the buffer. */
126797   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
126798   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
126799   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
126800   nData += nSuffix;
126801   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
126802   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
126803   pWriter->nData = nData + nDoclist;
126804
126805   /* Save the current term so that it can be used to prefix-compress the next.
126806   ** If the isCopyTerm parameter is true, then the buffer pointed to by
126807   ** zTerm is transient, so take a copy of the term data. Otherwise, just
126808   ** store a copy of the pointer.
126809   */
126810   if( isCopyTerm ){
126811     if( nTerm>pWriter->nMalloc ){
126812       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
126813       if( !zNew ){
126814         return SQLITE_NOMEM;
126815       }
126816       pWriter->nMalloc = nTerm*2;
126817       pWriter->zMalloc = zNew;
126818       pWriter->zTerm = zNew;
126819     }
126820     assert( pWriter->zTerm==pWriter->zMalloc );
126821     memcpy(pWriter->zTerm, zTerm, nTerm);
126822   }else{
126823     pWriter->zTerm = (char *)zTerm;
126824   }
126825   pWriter->nTerm = nTerm;
126826
126827   return SQLITE_OK;
126828 }
126829
126830 /*
126831 ** Flush all data associated with the SegmentWriter object pWriter to the
126832 ** database. This function must be called after all terms have been added
126833 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
126834 ** returned. Otherwise, an SQLite error code.
126835 */
126836 static int fts3SegWriterFlush(
126837   Fts3Table *p,                   /* Virtual table handle */
126838   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
126839   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
126840   int iIdx                        /* Value for 'idx' column of %_segdir */
126841 ){
126842   int rc;                         /* Return code */
126843   if( pWriter->pTree ){
126844     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
126845     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
126846     char *zRoot = NULL;           /* Pointer to buffer containing root node */
126847     int nRoot = 0;                /* Size of buffer zRoot */
126848
126849     iLastLeaf = pWriter->iFree;
126850     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
126851     if( rc==SQLITE_OK ){
126852       rc = fts3NodeWrite(p, pWriter->pTree, 1,
126853           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
126854     }
126855     if( rc==SQLITE_OK ){
126856       rc = fts3WriteSegdir(
126857           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
126858     }
126859   }else{
126860     /* The entire tree fits on the root node. Write it to the segdir table. */
126861     rc = fts3WriteSegdir(
126862         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
126863   }
126864   p->nLeafAdd++;
126865   return rc;
126866 }
126867
126868 /*
126869 ** Release all memory held by the SegmentWriter object passed as the 
126870 ** first argument.
126871 */
126872 static void fts3SegWriterFree(SegmentWriter *pWriter){
126873   if( pWriter ){
126874     sqlite3_free(pWriter->aData);
126875     sqlite3_free(pWriter->zMalloc);
126876     fts3NodeFree(pWriter->pTree);
126877     sqlite3_free(pWriter);
126878   }
126879 }
126880
126881 /*
126882 ** The first value in the apVal[] array is assumed to contain an integer.
126883 ** This function tests if there exist any documents with docid values that
126884 ** are different from that integer. i.e. if deleting the document with docid
126885 ** pRowid would mean the FTS3 table were empty.
126886 **
126887 ** If successful, *pisEmpty is set to true if the table is empty except for
126888 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
126889 ** error occurs, an SQLite error code is returned.
126890 */
126891 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
126892   sqlite3_stmt *pStmt;
126893   int rc;
126894   if( p->zContentTbl ){
126895     /* If using the content=xxx option, assume the table is never empty */
126896     *pisEmpty = 0;
126897     rc = SQLITE_OK;
126898   }else{
126899     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
126900     if( rc==SQLITE_OK ){
126901       if( SQLITE_ROW==sqlite3_step(pStmt) ){
126902         *pisEmpty = sqlite3_column_int(pStmt, 0);
126903       }
126904       rc = sqlite3_reset(pStmt);
126905     }
126906   }
126907   return rc;
126908 }
126909
126910 /*
126911 ** Set *pnMax to the largest segment level in the database for the index
126912 ** iIndex.
126913 **
126914 ** Segment levels are stored in the 'level' column of the %_segdir table.
126915 **
126916 ** Return SQLITE_OK if successful, or an SQLite error code if not.
126917 */
126918 static int fts3SegmentMaxLevel(
126919   Fts3Table *p, 
126920   int iLangid,
126921   int iIndex, 
126922   sqlite3_int64 *pnMax
126923 ){
126924   sqlite3_stmt *pStmt;
126925   int rc;
126926   assert( iIndex>=0 && iIndex<p->nIndex );
126927
126928   /* Set pStmt to the compiled version of:
126929   **
126930   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
126931   **
126932   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
126933   */
126934   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
126935   if( rc!=SQLITE_OK ) return rc;
126936   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
126937   sqlite3_bind_int64(pStmt, 2, 
126938       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
126939   );
126940   if( SQLITE_ROW==sqlite3_step(pStmt) ){
126941     *pnMax = sqlite3_column_int64(pStmt, 0);
126942   }
126943   return sqlite3_reset(pStmt);
126944 }
126945
126946 /*
126947 ** Delete all entries in the %_segments table associated with the segment
126948 ** opened with seg-reader pSeg. This function does not affect the contents
126949 ** of the %_segdir table.
126950 */
126951 static int fts3DeleteSegment(
126952   Fts3Table *p,                   /* FTS table handle */
126953   Fts3SegReader *pSeg             /* Segment to delete */
126954 ){
126955   int rc = SQLITE_OK;             /* Return code */
126956   if( pSeg->iStartBlock ){
126957     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
126958     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
126959     if( rc==SQLITE_OK ){
126960       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
126961       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
126962       sqlite3_step(pDelete);
126963       rc = sqlite3_reset(pDelete);
126964     }
126965   }
126966   return rc;
126967 }
126968
126969 /*
126970 ** This function is used after merging multiple segments into a single large
126971 ** segment to delete the old, now redundant, segment b-trees. Specifically,
126972 ** it:
126973 ** 
126974 **   1) Deletes all %_segments entries for the segments associated with 
126975 **      each of the SegReader objects in the array passed as the third 
126976 **      argument, and
126977 **
126978 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
126979 **      entries regardless of level if (iLevel<0).
126980 **
126981 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
126982 */
126983 static int fts3DeleteSegdir(
126984   Fts3Table *p,                   /* Virtual table handle */
126985   int iLangid,                    /* Language id */
126986   int iIndex,                     /* Index for p->aIndex */
126987   int iLevel,                     /* Level of %_segdir entries to delete */
126988   Fts3SegReader **apSegment,      /* Array of SegReader objects */
126989   int nReader                     /* Size of array apSegment */
126990 ){
126991   int rc = SQLITE_OK;             /* Return Code */
126992   int i;                          /* Iterator variable */
126993   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
126994
126995   for(i=0; rc==SQLITE_OK && i<nReader; i++){
126996     rc = fts3DeleteSegment(p, apSegment[i]);
126997   }
126998   if( rc!=SQLITE_OK ){
126999     return rc;
127000   }
127001
127002   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
127003   if( iLevel==FTS3_SEGCURSOR_ALL ){
127004     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
127005     if( rc==SQLITE_OK ){
127006       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127007       sqlite3_bind_int64(pDelete, 2, 
127008           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127009       );
127010     }
127011   }else{
127012     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
127013     if( rc==SQLITE_OK ){
127014       sqlite3_bind_int64(
127015           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127016       );
127017     }
127018   }
127019
127020   if( rc==SQLITE_OK ){
127021     sqlite3_step(pDelete);
127022     rc = sqlite3_reset(pDelete);
127023   }
127024
127025   return rc;
127026 }
127027
127028 /*
127029 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
127030 ** a position list that may (or may not) feature multiple columns. This
127031 ** function adjusts the pointer *ppList and the length *pnList so that they
127032 ** identify the subset of the position list that corresponds to column iCol.
127033 **
127034 ** If there are no entries in the input position list for column iCol, then
127035 ** *pnList is set to zero before returning.
127036 */
127037 static void fts3ColumnFilter(
127038   int iCol,                       /* Column to filter on */
127039   char **ppList,                  /* IN/OUT: Pointer to position list */
127040   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
127041 ){
127042   char *pList = *ppList;
127043   int nList = *pnList;
127044   char *pEnd = &pList[nList];
127045   int iCurrent = 0;
127046   char *p = pList;
127047
127048   assert( iCol>=0 );
127049   while( 1 ){
127050     char c = 0;
127051     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
127052   
127053     if( iCol==iCurrent ){
127054       nList = (int)(p - pList);
127055       break;
127056     }
127057
127058     nList -= (int)(p - pList);
127059     pList = p;
127060     if( nList==0 ){
127061       break;
127062     }
127063     p = &pList[1];
127064     p += sqlite3Fts3GetVarint32(p, &iCurrent);
127065   }
127066
127067   *ppList = pList;
127068   *pnList = nList;
127069 }
127070
127071 /*
127072 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
127073 ** existing data). Grow the buffer if required.
127074 **
127075 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
127076 ** trying to resize the buffer, return SQLITE_NOMEM.
127077 */
127078 static int fts3MsrBufferData(
127079   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127080   char *pList,
127081   int nList
127082 ){
127083   if( nList>pMsr->nBuffer ){
127084     char *pNew;
127085     pMsr->nBuffer = nList*2;
127086     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
127087     if( !pNew ) return SQLITE_NOMEM;
127088     pMsr->aBuffer = pNew;
127089   }
127090
127091   memcpy(pMsr->aBuffer, pList, nList);
127092   return SQLITE_OK;
127093 }
127094
127095 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
127096   Fts3Table *p,                   /* Virtual table handle */
127097   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127098   sqlite3_int64 *piDocid,         /* OUT: Docid value */
127099   char **paPoslist,               /* OUT: Pointer to position list */
127100   int *pnPoslist                  /* OUT: Size of position list in bytes */
127101 ){
127102   int nMerge = pMsr->nAdvance;
127103   Fts3SegReader **apSegment = pMsr->apSegment;
127104   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127105     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127106   );
127107
127108   if( nMerge==0 ){
127109     *paPoslist = 0;
127110     return SQLITE_OK;
127111   }
127112
127113   while( 1 ){
127114     Fts3SegReader *pSeg;
127115     pSeg = pMsr->apSegment[0];
127116
127117     if( pSeg->pOffsetList==0 ){
127118       *paPoslist = 0;
127119       break;
127120     }else{
127121       int rc;
127122       char *pList;
127123       int nList;
127124       int j;
127125       sqlite3_int64 iDocid = apSegment[0]->iDocid;
127126
127127       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127128       j = 1;
127129       while( rc==SQLITE_OK 
127130         && j<nMerge
127131         && apSegment[j]->pOffsetList
127132         && apSegment[j]->iDocid==iDocid
127133       ){
127134         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127135         j++;
127136       }
127137       if( rc!=SQLITE_OK ) return rc;
127138       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
127139
127140       if( pMsr->iColFilter>=0 ){
127141         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
127142       }
127143
127144       if( nList>0 ){
127145         if( fts3SegReaderIsPending(apSegment[0]) ){
127146           rc = fts3MsrBufferData(pMsr, pList, nList+1);
127147           if( rc!=SQLITE_OK ) return rc;
127148           *paPoslist = pMsr->aBuffer;
127149           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
127150         }else{
127151           *paPoslist = pList;
127152         }
127153         *piDocid = iDocid;
127154         *pnPoslist = nList;
127155         break;
127156       }
127157     }
127158   }
127159
127160   return SQLITE_OK;
127161 }
127162
127163 static int fts3SegReaderStart(
127164   Fts3Table *p,                   /* Virtual table handle */
127165   Fts3MultiSegReader *pCsr,       /* Cursor object */
127166   const char *zTerm,              /* Term searched for (or NULL) */
127167   int nTerm                       /* Length of zTerm in bytes */
127168 ){
127169   int i;
127170   int nSeg = pCsr->nSegment;
127171
127172   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
127173   ** for, then advance each segment iterator until it points to a term of
127174   ** equal or greater value than the specified term. This prevents many
127175   ** unnecessary merge/sort operations for the case where single segment
127176   ** b-tree leaf nodes contain more than one term.
127177   */
127178   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
127179     int res = 0;
127180     Fts3SegReader *pSeg = pCsr->apSegment[i];
127181     do {
127182       int rc = fts3SegReaderNext(p, pSeg, 0);
127183       if( rc!=SQLITE_OK ) return rc;
127184     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
127185
127186     if( pSeg->bLookup && res!=0 ){
127187       fts3SegReaderSetEof(pSeg);
127188     }
127189   }
127190   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
127191
127192   return SQLITE_OK;
127193 }
127194
127195 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
127196   Fts3Table *p,                   /* Virtual table handle */
127197   Fts3MultiSegReader *pCsr,       /* Cursor object */
127198   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
127199 ){
127200   pCsr->pFilter = pFilter;
127201   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
127202 }
127203
127204 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
127205   Fts3Table *p,                   /* Virtual table handle */
127206   Fts3MultiSegReader *pCsr,       /* Cursor object */
127207   int iCol,                       /* Column to match on. */
127208   const char *zTerm,              /* Term to iterate through a doclist for */
127209   int nTerm                       /* Number of bytes in zTerm */
127210 ){
127211   int i;
127212   int rc;
127213   int nSegment = pCsr->nSegment;
127214   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127215     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127216   );
127217
127218   assert( pCsr->pFilter==0 );
127219   assert( zTerm && nTerm>0 );
127220
127221   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
127222   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
127223   if( rc!=SQLITE_OK ) return rc;
127224
127225   /* Determine how many of the segments actually point to zTerm/nTerm. */
127226   for(i=0; i<nSegment; i++){
127227     Fts3SegReader *pSeg = pCsr->apSegment[i];
127228     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
127229       break;
127230     }
127231   }
127232   pCsr->nAdvance = i;
127233
127234   /* Advance each of the segments to point to the first docid. */
127235   for(i=0; i<pCsr->nAdvance; i++){
127236     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
127237     if( rc!=SQLITE_OK ) return rc;
127238   }
127239   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
127240
127241   assert( iCol<0 || iCol<p->nColumn );
127242   pCsr->iColFilter = iCol;
127243
127244   return SQLITE_OK;
127245 }
127246
127247 /*
127248 ** This function is called on a MultiSegReader that has been started using
127249 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
127250 ** have been made. Calling this function puts the MultiSegReader in such
127251 ** a state that if the next two calls are:
127252 **
127253 **   sqlite3Fts3SegReaderStart()
127254 **   sqlite3Fts3SegReaderStep()
127255 **
127256 ** then the entire doclist for the term is available in 
127257 ** MultiSegReader.aDoclist/nDoclist.
127258 */
127259 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
127260   int i;                          /* Used to iterate through segment-readers */
127261
127262   assert( pCsr->zTerm==0 );
127263   assert( pCsr->nTerm==0 );
127264   assert( pCsr->aDoclist==0 );
127265   assert( pCsr->nDoclist==0 );
127266
127267   pCsr->nAdvance = 0;
127268   pCsr->bRestart = 1;
127269   for(i=0; i<pCsr->nSegment; i++){
127270     pCsr->apSegment[i]->pOffsetList = 0;
127271     pCsr->apSegment[i]->nOffsetList = 0;
127272     pCsr->apSegment[i]->iDocid = 0;
127273   }
127274
127275   return SQLITE_OK;
127276 }
127277
127278
127279 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
127280   Fts3Table *p,                   /* Virtual table handle */
127281   Fts3MultiSegReader *pCsr        /* Cursor object */
127282 ){
127283   int rc = SQLITE_OK;
127284
127285   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
127286   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
127287   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
127288   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
127289   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
127290   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
127291
127292   Fts3SegReader **apSegment = pCsr->apSegment;
127293   int nSegment = pCsr->nSegment;
127294   Fts3SegFilter *pFilter = pCsr->pFilter;
127295   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127296     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127297   );
127298
127299   if( pCsr->nSegment==0 ) return SQLITE_OK;
127300
127301   do {
127302     int nMerge;
127303     int i;
127304   
127305     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
127306     ** forward. Then sort the list in order of current term again.  
127307     */
127308     for(i=0; i<pCsr->nAdvance; i++){
127309       Fts3SegReader *pSeg = apSegment[i];
127310       if( pSeg->bLookup ){
127311         fts3SegReaderSetEof(pSeg);
127312       }else{
127313         rc = fts3SegReaderNext(p, pSeg, 0);
127314       }
127315       if( rc!=SQLITE_OK ) return rc;
127316     }
127317     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
127318     pCsr->nAdvance = 0;
127319
127320     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
127321     assert( rc==SQLITE_OK );
127322     if( apSegment[0]->aNode==0 ) break;
127323
127324     pCsr->nTerm = apSegment[0]->nTerm;
127325     pCsr->zTerm = apSegment[0]->zTerm;
127326
127327     /* If this is a prefix-search, and if the term that apSegment[0] points
127328     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
127329     ** required callbacks have been made. In this case exit early.
127330     **
127331     ** Similarly, if this is a search for an exact match, and the first term
127332     ** of segment apSegment[0] is not a match, exit early.
127333     */
127334     if( pFilter->zTerm && !isScan ){
127335       if( pCsr->nTerm<pFilter->nTerm 
127336        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
127337        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
127338       ){
127339         break;
127340       }
127341     }
127342
127343     nMerge = 1;
127344     while( nMerge<nSegment 
127345         && apSegment[nMerge]->aNode
127346         && apSegment[nMerge]->nTerm==pCsr->nTerm 
127347         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
127348     ){
127349       nMerge++;
127350     }
127351
127352     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
127353     if( nMerge==1 
127354      && !isIgnoreEmpty 
127355      && !isFirst 
127356      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
127357     ){
127358       pCsr->nDoclist = apSegment[0]->nDoclist;
127359       if( fts3SegReaderIsPending(apSegment[0]) ){
127360         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
127361         pCsr->aDoclist = pCsr->aBuffer;
127362       }else{
127363         pCsr->aDoclist = apSegment[0]->aDoclist;
127364       }
127365       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
127366     }else{
127367       int nDoclist = 0;           /* Size of doclist */
127368       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
127369
127370       /* The current term of the first nMerge entries in the array
127371       ** of Fts3SegReader objects is the same. The doclists must be merged
127372       ** and a single term returned with the merged doclist.
127373       */
127374       for(i=0; i<nMerge; i++){
127375         fts3SegReaderFirstDocid(p, apSegment[i]);
127376       }
127377       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
127378       while( apSegment[0]->pOffsetList ){
127379         int j;                    /* Number of segments that share a docid */
127380         char *pList;
127381         int nList;
127382         int nByte;
127383         sqlite3_int64 iDocid = apSegment[0]->iDocid;
127384         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127385         j = 1;
127386         while( j<nMerge
127387             && apSegment[j]->pOffsetList
127388             && apSegment[j]->iDocid==iDocid
127389         ){
127390           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127391           j++;
127392         }
127393
127394         if( isColFilter ){
127395           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
127396         }
127397
127398         if( !isIgnoreEmpty || nList>0 ){
127399
127400           /* Calculate the 'docid' delta value to write into the merged 
127401           ** doclist. */
127402           sqlite3_int64 iDelta;
127403           if( p->bDescIdx && nDoclist>0 ){
127404             iDelta = iPrev - iDocid;
127405           }else{
127406             iDelta = iDocid - iPrev;
127407           }
127408           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
127409           assert( nDoclist>0 || iDelta==iDocid );
127410
127411           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
127412           if( nDoclist+nByte>pCsr->nBuffer ){
127413             char *aNew;
127414             pCsr->nBuffer = (nDoclist+nByte)*2;
127415             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
127416             if( !aNew ){
127417               return SQLITE_NOMEM;
127418             }
127419             pCsr->aBuffer = aNew;
127420           }
127421
127422           if( isFirst ){
127423             char *a = &pCsr->aBuffer[nDoclist];
127424             int nWrite;
127425            
127426             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
127427             if( nWrite ){
127428               iPrev = iDocid;
127429               nDoclist += nWrite;
127430             }
127431           }else{
127432             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
127433             iPrev = iDocid;
127434             if( isRequirePos ){
127435               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
127436               nDoclist += nList;
127437               pCsr->aBuffer[nDoclist++] = '\0';
127438             }
127439           }
127440         }
127441
127442         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
127443       }
127444       if( nDoclist>0 ){
127445         pCsr->aDoclist = pCsr->aBuffer;
127446         pCsr->nDoclist = nDoclist;
127447         rc = SQLITE_ROW;
127448       }
127449     }
127450     pCsr->nAdvance = nMerge;
127451   }while( rc==SQLITE_OK );
127452
127453   return rc;
127454 }
127455
127456
127457 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
127458   Fts3MultiSegReader *pCsr       /* Cursor object */
127459 ){
127460   if( pCsr ){
127461     int i;
127462     for(i=0; i<pCsr->nSegment; i++){
127463       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
127464     }
127465     sqlite3_free(pCsr->apSegment);
127466     sqlite3_free(pCsr->aBuffer);
127467
127468     pCsr->nSegment = 0;
127469     pCsr->apSegment = 0;
127470     pCsr->aBuffer = 0;
127471   }
127472 }
127473
127474 /*
127475 ** Merge all level iLevel segments in the database into a single 
127476 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
127477 ** single segment with a level equal to the numerically largest level 
127478 ** currently present in the database.
127479 **
127480 ** If this function is called with iLevel<0, but there is only one
127481 ** segment in the database, SQLITE_DONE is returned immediately. 
127482 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
127483 ** an SQLite error code is returned.
127484 */
127485 static int fts3SegmentMerge(
127486   Fts3Table *p, 
127487   int iLangid,                    /* Language id to merge */
127488   int iIndex,                     /* Index in p->aIndex[] to merge */
127489   int iLevel                      /* Level to merge */
127490 ){
127491   int rc;                         /* Return code */
127492   int iIdx = 0;                   /* Index of new segment */
127493   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
127494   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
127495   Fts3SegFilter filter;           /* Segment term filter condition */
127496   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
127497   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
127498
127499   assert( iLevel==FTS3_SEGCURSOR_ALL
127500        || iLevel==FTS3_SEGCURSOR_PENDING
127501        || iLevel>=0
127502   );
127503   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127504   assert( iIndex>=0 && iIndex<p->nIndex );
127505
127506   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
127507   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
127508
127509   if( iLevel==FTS3_SEGCURSOR_ALL ){
127510     /* This call is to merge all segments in the database to a single
127511     ** segment. The level of the new segment is equal to the numerically
127512     ** greatest segment level currently present in the database for this
127513     ** index. The idx of the new segment is always 0.  */
127514     if( csr.nSegment==1 ){
127515       rc = SQLITE_DONE;
127516       goto finished;
127517     }
127518     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
127519     bIgnoreEmpty = 1;
127520
127521   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
127522     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
127523     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
127524   }else{
127525     /* This call is to merge all segments at level iLevel. find the next
127526     ** available segment index at level iLevel+1. The call to
127527     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
127528     ** a single iLevel+2 segment if necessary.  */
127529     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
127530     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
127531   }
127532   if( rc!=SQLITE_OK ) goto finished;
127533   assert( csr.nSegment>0 );
127534   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
127535   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
127536
127537   memset(&filter, 0, sizeof(Fts3SegFilter));
127538   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
127539   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
127540
127541   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
127542   while( SQLITE_OK==rc ){
127543     rc = sqlite3Fts3SegReaderStep(p, &csr);
127544     if( rc!=SQLITE_ROW ) break;
127545     rc = fts3SegWriterAdd(p, &pWriter, 1, 
127546         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
127547   }
127548   if( rc!=SQLITE_OK ) goto finished;
127549   assert( pWriter );
127550
127551   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
127552     rc = fts3DeleteSegdir(
127553         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
127554     );
127555     if( rc!=SQLITE_OK ) goto finished;
127556   }
127557   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
127558
127559  finished:
127560   fts3SegWriterFree(pWriter);
127561   sqlite3Fts3SegReaderFinish(&csr);
127562   return rc;
127563 }
127564
127565
127566 /* 
127567 ** Flush the contents of pendingTerms to level 0 segments.
127568 */
127569 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
127570   int rc = SQLITE_OK;
127571   int i;
127572         
127573   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
127574     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
127575     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
127576   }
127577   sqlite3Fts3PendingTermsClear(p);
127578
127579   /* Determine the auto-incr-merge setting if unknown.  If enabled,
127580   ** estimate the number of leaf blocks of content to be written
127581   */
127582   if( rc==SQLITE_OK && p->bHasStat
127583    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
127584   ){
127585     sqlite3_stmt *pStmt = 0;
127586     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
127587     if( rc==SQLITE_OK ){
127588       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
127589       rc = sqlite3_step(pStmt);
127590       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
127591       rc = sqlite3_reset(pStmt);
127592     }
127593   }
127594   return rc;
127595 }
127596
127597 /*
127598 ** Encode N integers as varints into a blob.
127599 */
127600 static void fts3EncodeIntArray(
127601   int N,             /* The number of integers to encode */
127602   u32 *a,            /* The integer values */
127603   char *zBuf,        /* Write the BLOB here */
127604   int *pNBuf         /* Write number of bytes if zBuf[] used here */
127605 ){
127606   int i, j;
127607   for(i=j=0; i<N; i++){
127608     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
127609   }
127610   *pNBuf = j;
127611 }
127612
127613 /*
127614 ** Decode a blob of varints into N integers
127615 */
127616 static void fts3DecodeIntArray(
127617   int N,             /* The number of integers to decode */
127618   u32 *a,            /* Write the integer values */
127619   const char *zBuf,  /* The BLOB containing the varints */
127620   int nBuf           /* size of the BLOB */
127621 ){
127622   int i, j;
127623   UNUSED_PARAMETER(nBuf);
127624   for(i=j=0; i<N; i++){
127625     sqlite3_int64 x;
127626     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
127627     assert(j<=nBuf);
127628     a[i] = (u32)(x & 0xffffffff);
127629   }
127630 }
127631
127632 /*
127633 ** Insert the sizes (in tokens) for each column of the document
127634 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
127635 ** a blob of varints.
127636 */
127637 static void fts3InsertDocsize(
127638   int *pRC,                       /* Result code */
127639   Fts3Table *p,                   /* Table into which to insert */
127640   u32 *aSz                        /* Sizes of each column, in tokens */
127641 ){
127642   char *pBlob;             /* The BLOB encoding of the document size */
127643   int nBlob;               /* Number of bytes in the BLOB */
127644   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
127645   int rc;                  /* Result code from subfunctions */
127646
127647   if( *pRC ) return;
127648   pBlob = sqlite3_malloc( 10*p->nColumn );
127649   if( pBlob==0 ){
127650     *pRC = SQLITE_NOMEM;
127651     return;
127652   }
127653   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
127654   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
127655   if( rc ){
127656     sqlite3_free(pBlob);
127657     *pRC = rc;
127658     return;
127659   }
127660   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
127661   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
127662   sqlite3_step(pStmt);
127663   *pRC = sqlite3_reset(pStmt);
127664 }
127665
127666 /*
127667 ** Record 0 of the %_stat table contains a blob consisting of N varints,
127668 ** where N is the number of user defined columns in the fts3 table plus
127669 ** two. If nCol is the number of user defined columns, then values of the 
127670 ** varints are set as follows:
127671 **
127672 **   Varint 0:       Total number of rows in the table.
127673 **
127674 **   Varint 1..nCol: For each column, the total number of tokens stored in
127675 **                   the column for all rows of the table.
127676 **
127677 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
127678 **                   columns of all rows of the table.
127679 **
127680 */
127681 static void fts3UpdateDocTotals(
127682   int *pRC,                       /* The result code */
127683   Fts3Table *p,                   /* Table being updated */
127684   u32 *aSzIns,                    /* Size increases */
127685   u32 *aSzDel,                    /* Size decreases */
127686   int nChng                       /* Change in the number of documents */
127687 ){
127688   char *pBlob;             /* Storage for BLOB written into %_stat */
127689   int nBlob;               /* Size of BLOB written into %_stat */
127690   u32 *a;                  /* Array of integers that becomes the BLOB */
127691   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
127692   int i;                   /* Loop counter */
127693   int rc;                  /* Result code from subfunctions */
127694
127695   const int nStat = p->nColumn+2;
127696
127697   if( *pRC ) return;
127698   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
127699   if( a==0 ){
127700     *pRC = SQLITE_NOMEM;
127701     return;
127702   }
127703   pBlob = (char*)&a[nStat];
127704   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
127705   if( rc ){
127706     sqlite3_free(a);
127707     *pRC = rc;
127708     return;
127709   }
127710   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
127711   if( sqlite3_step(pStmt)==SQLITE_ROW ){
127712     fts3DecodeIntArray(nStat, a,
127713          sqlite3_column_blob(pStmt, 0),
127714          sqlite3_column_bytes(pStmt, 0));
127715   }else{
127716     memset(a, 0, sizeof(u32)*(nStat) );
127717   }
127718   rc = sqlite3_reset(pStmt);
127719   if( rc!=SQLITE_OK ){
127720     sqlite3_free(a);
127721     *pRC = rc;
127722     return;
127723   }
127724   if( nChng<0 && a[0]<(u32)(-nChng) ){
127725     a[0] = 0;
127726   }else{
127727     a[0] += nChng;
127728   }
127729   for(i=0; i<p->nColumn+1; i++){
127730     u32 x = a[i+1];
127731     if( x+aSzIns[i] < aSzDel[i] ){
127732       x = 0;
127733     }else{
127734       x = x + aSzIns[i] - aSzDel[i];
127735     }
127736     a[i+1] = x;
127737   }
127738   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
127739   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
127740   if( rc ){
127741     sqlite3_free(a);
127742     *pRC = rc;
127743     return;
127744   }
127745   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
127746   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
127747   sqlite3_step(pStmt);
127748   *pRC = sqlite3_reset(pStmt);
127749   sqlite3_free(a);
127750 }
127751
127752 /*
127753 ** Merge the entire database so that there is one segment for each 
127754 ** iIndex/iLangid combination.
127755 */
127756 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
127757   int bSeenDone = 0;
127758   int rc;
127759   sqlite3_stmt *pAllLangid = 0;
127760
127761   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
127762   if( rc==SQLITE_OK ){
127763     int rc2;
127764     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
127765     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
127766       int i;
127767       int iLangid = sqlite3_column_int(pAllLangid, 0);
127768       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
127769         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
127770         if( rc==SQLITE_DONE ){
127771           bSeenDone = 1;
127772           rc = SQLITE_OK;
127773         }
127774       }
127775     }
127776     rc2 = sqlite3_reset(pAllLangid);
127777     if( rc==SQLITE_OK ) rc = rc2;
127778   }
127779
127780   sqlite3Fts3SegmentsClose(p);
127781   sqlite3Fts3PendingTermsClear(p);
127782
127783   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
127784 }
127785
127786 /*
127787 ** This function is called when the user executes the following statement:
127788 **
127789 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
127790 **
127791 ** The entire FTS index is discarded and rebuilt. If the table is one 
127792 ** created using the content=xxx option, then the new index is based on
127793 ** the current contents of the xxx table. Otherwise, it is rebuilt based
127794 ** on the contents of the %_content table.
127795 */
127796 static int fts3DoRebuild(Fts3Table *p){
127797   int rc;                         /* Return Code */
127798
127799   rc = fts3DeleteAll(p, 0);
127800   if( rc==SQLITE_OK ){
127801     u32 *aSz = 0;
127802     u32 *aSzIns = 0;
127803     u32 *aSzDel = 0;
127804     sqlite3_stmt *pStmt = 0;
127805     int nEntry = 0;
127806
127807     /* Compose and prepare an SQL statement to loop through the content table */
127808     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
127809     if( !zSql ){
127810       rc = SQLITE_NOMEM;
127811     }else{
127812       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
127813       sqlite3_free(zSql);
127814     }
127815
127816     if( rc==SQLITE_OK ){
127817       int nByte = sizeof(u32) * (p->nColumn+1)*3;
127818       aSz = (u32 *)sqlite3_malloc(nByte);
127819       if( aSz==0 ){
127820         rc = SQLITE_NOMEM;
127821       }else{
127822         memset(aSz, 0, nByte);
127823         aSzIns = &aSz[p->nColumn+1];
127824         aSzDel = &aSzIns[p->nColumn+1];
127825       }
127826     }
127827
127828     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
127829       int iCol;
127830       int iLangid = langidFromSelect(p, pStmt);
127831       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
127832       aSz[p->nColumn] = 0;
127833       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
127834         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
127835         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
127836         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
127837       }
127838       if( p->bHasDocsize ){
127839         fts3InsertDocsize(&rc, p, aSz);
127840       }
127841       if( rc!=SQLITE_OK ){
127842         sqlite3_finalize(pStmt);
127843         pStmt = 0;
127844       }else{
127845         nEntry++;
127846         for(iCol=0; iCol<=p->nColumn; iCol++){
127847           aSzIns[iCol] += aSz[iCol];
127848         }
127849       }
127850     }
127851     if( p->bFts4 ){
127852       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
127853     }
127854     sqlite3_free(aSz);
127855
127856     if( pStmt ){
127857       int rc2 = sqlite3_finalize(pStmt);
127858       if( rc==SQLITE_OK ){
127859         rc = rc2;
127860       }
127861     }
127862   }
127863
127864   return rc;
127865 }
127866
127867
127868 /*
127869 ** This function opens a cursor used to read the input data for an 
127870 ** incremental merge operation. Specifically, it opens a cursor to scan
127871 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
127872 ** level iAbsLevel.
127873 */
127874 static int fts3IncrmergeCsr(
127875   Fts3Table *p,                   /* FTS3 table handle */
127876   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
127877   int nSeg,                       /* Number of segments to merge */
127878   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
127879 ){
127880   int rc;                         /* Return Code */
127881   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
127882   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
127883
127884   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
127885   memset(pCsr, 0, sizeof(*pCsr));
127886   nByte = sizeof(Fts3SegReader *) * nSeg;
127887   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
127888
127889   if( pCsr->apSegment==0 ){
127890     rc = SQLITE_NOMEM;
127891   }else{
127892     memset(pCsr->apSegment, 0, nByte);
127893     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
127894   }
127895   if( rc==SQLITE_OK ){
127896     int i;
127897     int rc2;
127898     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
127899     assert( pCsr->nSegment==0 );
127900     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
127901       rc = sqlite3Fts3SegReaderNew(i, 0,
127902           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
127903           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
127904           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
127905           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
127906           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
127907           &pCsr->apSegment[i]
127908       );
127909       pCsr->nSegment++;
127910     }
127911     rc2 = sqlite3_reset(pStmt);
127912     if( rc==SQLITE_OK ) rc = rc2;
127913   }
127914
127915   return rc;
127916 }
127917
127918 typedef struct IncrmergeWriter IncrmergeWriter;
127919 typedef struct NodeWriter NodeWriter;
127920 typedef struct Blob Blob;
127921 typedef struct NodeReader NodeReader;
127922
127923 /*
127924 ** An instance of the following structure is used as a dynamic buffer
127925 ** to build up nodes or other blobs of data in.
127926 **
127927 ** The function blobGrowBuffer() is used to extend the allocation.
127928 */
127929 struct Blob {
127930   char *a;                        /* Pointer to allocation */
127931   int n;                          /* Number of valid bytes of data in a[] */
127932   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
127933 };
127934
127935 /*
127936 ** This structure is used to build up buffers containing segment b-tree 
127937 ** nodes (blocks).
127938 */
127939 struct NodeWriter {
127940   sqlite3_int64 iBlock;           /* Current block id */
127941   Blob key;                       /* Last key written to the current block */
127942   Blob block;                     /* Current block image */
127943 };
127944
127945 /*
127946 ** An object of this type contains the state required to create or append
127947 ** to an appendable b-tree segment.
127948 */
127949 struct IncrmergeWriter {
127950   int nLeafEst;                   /* Space allocated for leaf blocks */
127951   int nWork;                      /* Number of leaf pages flushed */
127952   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
127953   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
127954   sqlite3_int64 iStart;           /* Block number of first allocated block */
127955   sqlite3_int64 iEnd;             /* Block number of last allocated block */
127956   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
127957 };
127958
127959 /*
127960 ** An object of the following type is used to read data from a single
127961 ** FTS segment node. See the following functions:
127962 **
127963 **     nodeReaderInit()
127964 **     nodeReaderNext()
127965 **     nodeReaderRelease()
127966 */
127967 struct NodeReader {
127968   const char *aNode;
127969   int nNode;
127970   int iOff;                       /* Current offset within aNode[] */
127971
127972   /* Output variables. Containing the current node entry. */
127973   sqlite3_int64 iChild;           /* Pointer to child node */
127974   Blob term;                      /* Current term */
127975   const char *aDoclist;           /* Pointer to doclist */
127976   int nDoclist;                   /* Size of doclist in bytes */
127977 };
127978
127979 /*
127980 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
127981 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
127982 ** bytes in size, extend (realloc) it to be so.
127983 **
127984 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
127985 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
127986 ** to reflect the new size of the pBlob->a[] buffer.
127987 */
127988 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
127989   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
127990     int nAlloc = nMin;
127991     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
127992     if( a ){
127993       pBlob->nAlloc = nAlloc;
127994       pBlob->a = a;
127995     }else{
127996       *pRc = SQLITE_NOMEM;
127997     }
127998   }
127999 }
128000
128001 /*
128002 ** Attempt to advance the node-reader object passed as the first argument to
128003 ** the next entry on the node. 
128004 **
128005 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
128006 ** Otherwise return SQLITE_OK. If there is no next entry on the node
128007 ** (e.g. because the current entry is the last) set NodeReader->aNode to
128008 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
128009 ** variables for the new entry.
128010 */
128011 static int nodeReaderNext(NodeReader *p){
128012   int bFirst = (p->term.n==0);    /* True for first term on the node */
128013   int nPrefix = 0;                /* Bytes to copy from previous term */
128014   int nSuffix = 0;                /* Bytes to append to the prefix */
128015   int rc = SQLITE_OK;             /* Return code */
128016
128017   assert( p->aNode );
128018   if( p->iChild && bFirst==0 ) p->iChild++;
128019   if( p->iOff>=p->nNode ){
128020     /* EOF */
128021     p->aNode = 0;
128022   }else{
128023     if( bFirst==0 ){
128024       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
128025     }
128026     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
128027
128028     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
128029     if( rc==SQLITE_OK ){
128030       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
128031       p->term.n = nPrefix+nSuffix;
128032       p->iOff += nSuffix;
128033       if( p->iChild==0 ){
128034         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
128035         p->aDoclist = &p->aNode[p->iOff];
128036         p->iOff += p->nDoclist;
128037       }
128038     }
128039   }
128040
128041   assert( p->iOff<=p->nNode );
128042
128043   return rc;
128044 }
128045
128046 /*
128047 ** Release all dynamic resources held by node-reader object *p.
128048 */
128049 static void nodeReaderRelease(NodeReader *p){
128050   sqlite3_free(p->term.a);
128051 }
128052
128053 /*
128054 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
128055 **
128056 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
128057 ** point to the first entry on the node (if any). Otherwise, an SQLite
128058 ** error code is returned.
128059 */
128060 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
128061   memset(p, 0, sizeof(NodeReader));
128062   p->aNode = aNode;
128063   p->nNode = nNode;
128064
128065   /* Figure out if this is a leaf or an internal node. */
128066   if( p->aNode[0] ){
128067     /* An internal node. */
128068     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
128069   }else{
128070     p->iOff = 1;
128071   }
128072
128073   return nodeReaderNext(p);
128074 }
128075
128076 /*
128077 ** This function is called while writing an FTS segment each time a leaf o
128078 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
128079 ** to be greater than the largest key on the node just written, but smaller
128080 ** than or equal to the first key that will be written to the next leaf
128081 ** node.
128082 **
128083 ** The block id of the leaf node just written to disk may be found in
128084 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
128085 */
128086 static int fts3IncrmergePush(
128087   Fts3Table *p,                   /* Fts3 table handle */
128088   IncrmergeWriter *pWriter,       /* Writer object */
128089   const char *zTerm,              /* Term to write to internal node */
128090   int nTerm                       /* Bytes at zTerm */
128091 ){
128092   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
128093   int iLayer;
128094
128095   assert( nTerm>0 );
128096   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
128097     sqlite3_int64 iNextPtr = 0;
128098     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
128099     int rc = SQLITE_OK;
128100     int nPrefix;
128101     int nSuffix;
128102     int nSpace;
128103
128104     /* Figure out how much space the key will consume if it is written to
128105     ** the current node of layer iLayer. Due to the prefix compression, 
128106     ** the space required changes depending on which node the key is to
128107     ** be added to.  */
128108     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
128109     nSuffix = nTerm - nPrefix;
128110     nSpace  = sqlite3Fts3VarintLen(nPrefix);
128111     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
128112
128113     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
128114       /* If the current node of layer iLayer contains zero keys, or if adding
128115       ** the key to it will not cause it to grow to larger than nNodeSize 
128116       ** bytes in size, write the key here.  */
128117
128118       Blob *pBlk = &pNode->block;
128119       if( pBlk->n==0 ){
128120         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
128121         if( rc==SQLITE_OK ){
128122           pBlk->a[0] = (char)iLayer;
128123           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
128124         }
128125       }
128126       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
128127       blobGrowBuffer(&pNode->key, nTerm, &rc);
128128
128129       if( rc==SQLITE_OK ){
128130         if( pNode->key.n ){
128131           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
128132         }
128133         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
128134         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
128135         pBlk->n += nSuffix;
128136
128137         memcpy(pNode->key.a, zTerm, nTerm);
128138         pNode->key.n = nTerm;
128139       }
128140     }else{
128141       /* Otherwise, flush the current node of layer iLayer to disk.
128142       ** Then allocate a new, empty sibling node. The key will be written
128143       ** into the parent of this node. */
128144       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
128145
128146       assert( pNode->block.nAlloc>=p->nNodeSize );
128147       pNode->block.a[0] = (char)iLayer;
128148       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
128149
128150       iNextPtr = pNode->iBlock;
128151       pNode->iBlock++;
128152       pNode->key.n = 0;
128153     }
128154
128155     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
128156     iPtr = iNextPtr;
128157   }
128158
128159   assert( 0 );
128160   return 0;
128161 }
128162
128163 /*
128164 ** Append a term and (optionally) doclist to the FTS segment node currently
128165 ** stored in blob *pNode. The node need not contain any terms, but the
128166 ** header must be written before this function is called.
128167 **
128168 ** A node header is a single 0x00 byte for a leaf node, or a height varint
128169 ** followed by the left-hand-child varint for an internal node.
128170 **
128171 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
128172 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
128173 ** node, both aDoclist and nDoclist must be passed 0.
128174 **
128175 ** If the size of the value in blob pPrev is zero, then this is the first
128176 ** term written to the node. Otherwise, pPrev contains a copy of the 
128177 ** previous term. Before this function returns, it is updated to contain a
128178 ** copy of zTerm/nTerm.
128179 **
128180 ** It is assumed that the buffer associated with pNode is already large
128181 ** enough to accommodate the new entry. The buffer associated with pPrev
128182 ** is extended by this function if requrired.
128183 **
128184 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
128185 ** returned. Otherwise, SQLITE_OK.
128186 */
128187 static int fts3AppendToNode(
128188   Blob *pNode,                    /* Current node image to append to */
128189   Blob *pPrev,                    /* Buffer containing previous term written */
128190   const char *zTerm,              /* New term to write */
128191   int nTerm,                      /* Size of zTerm in bytes */
128192   const char *aDoclist,           /* Doclist (or NULL) to write */
128193   int nDoclist                    /* Size of aDoclist in bytes */ 
128194 ){
128195   int rc = SQLITE_OK;             /* Return code */
128196   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
128197   int nPrefix;                    /* Size of term prefix in bytes */
128198   int nSuffix;                    /* Size of term suffix in bytes */
128199
128200   /* Node must have already been started. There must be a doclist for a
128201   ** leaf node, and there must not be a doclist for an internal node.  */
128202   assert( pNode->n>0 );
128203   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
128204
128205   blobGrowBuffer(pPrev, nTerm, &rc);
128206   if( rc!=SQLITE_OK ) return rc;
128207
128208   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
128209   nSuffix = nTerm - nPrefix;
128210   memcpy(pPrev->a, zTerm, nTerm);
128211   pPrev->n = nTerm;
128212
128213   if( bFirst==0 ){
128214     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
128215   }
128216   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
128217   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
128218   pNode->n += nSuffix;
128219
128220   if( aDoclist ){
128221     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
128222     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
128223     pNode->n += nDoclist;
128224   }
128225
128226   assert( pNode->n<=pNode->nAlloc );
128227
128228   return SQLITE_OK;
128229 }
128230
128231 /*
128232 ** Append the current term and doclist pointed to by cursor pCsr to the
128233 ** appendable b-tree segment opened for writing by pWriter.
128234 **
128235 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
128236 */
128237 static int fts3IncrmergeAppend(
128238   Fts3Table *p,                   /* Fts3 table handle */
128239   IncrmergeWriter *pWriter,       /* Writer object */
128240   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
128241 ){
128242   const char *zTerm = pCsr->zTerm;
128243   int nTerm = pCsr->nTerm;
128244   const char *aDoclist = pCsr->aDoclist;
128245   int nDoclist = pCsr->nDoclist;
128246   int rc = SQLITE_OK;           /* Return code */
128247   int nSpace;                   /* Total space in bytes required on leaf */
128248   int nPrefix;                  /* Size of prefix shared with previous term */
128249   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
128250   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
128251
128252   pLeaf = &pWriter->aNodeWriter[0];
128253   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
128254   nSuffix = nTerm - nPrefix;
128255
128256   nSpace  = sqlite3Fts3VarintLen(nPrefix);
128257   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
128258   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
128259
128260   /* If the current block is not empty, and if adding this term/doclist
128261   ** to the current block would make it larger than Fts3Table.nNodeSize
128262   ** bytes, write this block out to the database. */
128263   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
128264     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
128265     pWriter->nWork++;
128266
128267     /* Add the current term to the parent node. The term added to the 
128268     ** parent must:
128269     **
128270     **   a) be greater than the largest term on the leaf node just written
128271     **      to the database (still available in pLeaf->key), and
128272     **
128273     **   b) be less than or equal to the term about to be added to the new
128274     **      leaf node (zTerm/nTerm).
128275     **
128276     ** In other words, it must be the prefix of zTerm 1 byte longer than
128277     ** the common prefix (if any) of zTerm and pWriter->zTerm.
128278     */
128279     if( rc==SQLITE_OK ){
128280       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
128281     }
128282
128283     /* Advance to the next output block */
128284     pLeaf->iBlock++;
128285     pLeaf->key.n = 0;
128286     pLeaf->block.n = 0;
128287
128288     nSuffix = nTerm;
128289     nSpace  = 1;
128290     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
128291     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
128292   }
128293
128294   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
128295
128296   if( rc==SQLITE_OK ){
128297     if( pLeaf->block.n==0 ){
128298       pLeaf->block.n = 1;
128299       pLeaf->block.a[0] = '\0';
128300     }
128301     rc = fts3AppendToNode(
128302         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
128303     );
128304   }
128305
128306   return rc;
128307 }
128308
128309 /*
128310 ** This function is called to release all dynamic resources held by the
128311 ** merge-writer object pWriter, and if no error has occurred, to flush
128312 ** all outstanding node buffers held by pWriter to disk.
128313 **
128314 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
128315 ** is made to write any data to disk. Instead, this function serves only
128316 ** to release outstanding resources.
128317 **
128318 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
128319 ** flushing buffers to disk, *pRc is set to an SQLite error code before
128320 ** returning.
128321 */
128322 static void fts3IncrmergeRelease(
128323   Fts3Table *p,                   /* FTS3 table handle */
128324   IncrmergeWriter *pWriter,       /* Merge-writer object */
128325   int *pRc                        /* IN/OUT: Error code */
128326 ){
128327   int i;                          /* Used to iterate through non-root layers */
128328   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
128329   NodeWriter *pRoot;              /* NodeWriter for root node */
128330   int rc = *pRc;                  /* Error code */
128331
128332   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
128333   ** root node. If the segment fits entirely on a single leaf node, iRoot
128334   ** will be set to 0. If the root node is the parent of the leaves, iRoot
128335   ** will be 1. And so on.  */
128336   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
128337     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
128338     if( pNode->block.n>0 ) break;
128339     assert( *pRc || pNode->block.nAlloc==0 );
128340     assert( *pRc || pNode->key.nAlloc==0 );
128341     sqlite3_free(pNode->block.a);
128342     sqlite3_free(pNode->key.a);
128343   }
128344
128345   /* Empty output segment. This is a no-op. */
128346   if( iRoot<0 ) return;
128347
128348   /* The entire output segment fits on a single node. Normally, this means
128349   ** the node would be stored as a blob in the "root" column of the %_segdir
128350   ** table. However, this is not permitted in this case. The problem is that 
128351   ** space has already been reserved in the %_segments table, and so the 
128352   ** start_block and end_block fields of the %_segdir table must be populated. 
128353   ** And, by design or by accident, released versions of FTS cannot handle 
128354   ** segments that fit entirely on the root node with start_block!=0.
128355   **
128356   ** Instead, create a synthetic root node that contains nothing but a 
128357   ** pointer to the single content node. So that the segment consists of a
128358   ** single leaf and a single interior (root) node.
128359   **
128360   ** Todo: Better might be to defer allocating space in the %_segments 
128361   ** table until we are sure it is needed.
128362   */
128363   if( iRoot==0 ){
128364     Blob *pBlock = &pWriter->aNodeWriter[1].block;
128365     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
128366     if( rc==SQLITE_OK ){
128367       pBlock->a[0] = 0x01;
128368       pBlock->n = 1 + sqlite3Fts3PutVarint(
128369           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
128370       );
128371     }
128372     iRoot = 1;
128373   }
128374   pRoot = &pWriter->aNodeWriter[iRoot];
128375
128376   /* Flush all currently outstanding nodes to disk. */
128377   for(i=0; i<iRoot; i++){
128378     NodeWriter *pNode = &pWriter->aNodeWriter[i];
128379     if( pNode->block.n>0 && rc==SQLITE_OK ){
128380       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
128381     }
128382     sqlite3_free(pNode->block.a);
128383     sqlite3_free(pNode->key.a);
128384   }
128385
128386   /* Write the %_segdir record. */
128387   if( rc==SQLITE_OK ){
128388     rc = fts3WriteSegdir(p, 
128389         pWriter->iAbsLevel+1,               /* level */
128390         pWriter->iIdx,                      /* idx */
128391         pWriter->iStart,                    /* start_block */
128392         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
128393         pWriter->iEnd,                      /* end_block */
128394         pRoot->block.a, pRoot->block.n      /* root */
128395     );
128396   }
128397   sqlite3_free(pRoot->block.a);
128398   sqlite3_free(pRoot->key.a);
128399
128400   *pRc = rc;
128401 }
128402
128403 /*
128404 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
128405 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
128406 ** the other, it is considered to be smaller than the other.
128407 **
128408 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
128409 ** if it is greater.
128410 */
128411 static int fts3TermCmp(
128412   const char *zLhs, int nLhs,     /* LHS of comparison */
128413   const char *zRhs, int nRhs      /* RHS of comparison */
128414 ){
128415   int nCmp = MIN(nLhs, nRhs);
128416   int res;
128417
128418   res = memcmp(zLhs, zRhs, nCmp);
128419   if( res==0 ) res = nLhs - nRhs;
128420
128421   return res;
128422 }
128423
128424
128425 /*
128426 ** Query to see if the entry in the %_segments table with blockid iEnd is 
128427 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
128428 ** returning. Otherwise, set *pbRes to 0. 
128429 **
128430 ** Or, if an error occurs while querying the database, return an SQLite 
128431 ** error code. The final value of *pbRes is undefined in this case.
128432 **
128433 ** This is used to test if a segment is an "appendable" segment. If it
128434 ** is, then a NULL entry has been inserted into the %_segments table
128435 ** with blockid %_segdir.end_block.
128436 */
128437 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
128438   int bRes = 0;                   /* Result to set *pbRes to */
128439   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
128440   int rc;                         /* Return code */
128441
128442   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
128443   if( rc==SQLITE_OK ){
128444     sqlite3_bind_int64(pCheck, 1, iEnd);
128445     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
128446     rc = sqlite3_reset(pCheck);
128447   }
128448   
128449   *pbRes = bRes;
128450   return rc;
128451 }
128452
128453 /*
128454 ** This function is called when initializing an incremental-merge operation.
128455 ** It checks if the existing segment with index value iIdx at absolute level 
128456 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
128457 ** merge-writer object *pWriter is initialized to write to it.
128458 **
128459 ** An existing segment can be appended to by an incremental merge if:
128460 **
128461 **   * It was initially created as an appendable segment (with all required
128462 **     space pre-allocated), and
128463 **
128464 **   * The first key read from the input (arguments zKey and nKey) is 
128465 **     greater than the largest key currently stored in the potential
128466 **     output segment.
128467 */
128468 static int fts3IncrmergeLoad(
128469   Fts3Table *p,                   /* Fts3 table handle */
128470   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
128471   int iIdx,                       /* Index of candidate output segment */
128472   const char *zKey,               /* First key to write */
128473   int nKey,                       /* Number of bytes in nKey */
128474   IncrmergeWriter *pWriter        /* Populate this object */
128475 ){
128476   int rc;                         /* Return code */
128477   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
128478
128479   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
128480   if( rc==SQLITE_OK ){
128481     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
128482     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
128483     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
128484     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
128485     int nRoot = 0;                /* Size of aRoot[] in bytes */
128486     int rc2;                      /* Return code from sqlite3_reset() */
128487     int bAppendable = 0;          /* Set to true if segment is appendable */
128488
128489     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
128490     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
128491     sqlite3_bind_int(pSelect, 2, iIdx);
128492     if( sqlite3_step(pSelect)==SQLITE_ROW ){
128493       iStart = sqlite3_column_int64(pSelect, 1);
128494       iLeafEnd = sqlite3_column_int64(pSelect, 2);
128495       iEnd = sqlite3_column_int64(pSelect, 3);
128496       nRoot = sqlite3_column_bytes(pSelect, 4);
128497       aRoot = sqlite3_column_blob(pSelect, 4);
128498     }else{
128499       return sqlite3_reset(pSelect);
128500     }
128501
128502     /* Check for the zero-length marker in the %_segments table */
128503     rc = fts3IsAppendable(p, iEnd, &bAppendable);
128504
128505     /* Check that zKey/nKey is larger than the largest key the candidate */
128506     if( rc==SQLITE_OK && bAppendable ){
128507       char *aLeaf = 0;
128508       int nLeaf = 0;
128509
128510       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
128511       if( rc==SQLITE_OK ){
128512         NodeReader reader;
128513         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
128514             rc==SQLITE_OK && reader.aNode;
128515             rc = nodeReaderNext(&reader)
128516         ){
128517           assert( reader.aNode );
128518         }
128519         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
128520           bAppendable = 0;
128521         }
128522         nodeReaderRelease(&reader);
128523       }
128524       sqlite3_free(aLeaf);
128525     }
128526
128527     if( rc==SQLITE_OK && bAppendable ){
128528       /* It is possible to append to this segment. Set up the IncrmergeWriter
128529       ** object to do so.  */
128530       int i;
128531       int nHeight = (int)aRoot[0];
128532       NodeWriter *pNode;
128533
128534       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
128535       pWriter->iStart = iStart;
128536       pWriter->iEnd = iEnd;
128537       pWriter->iAbsLevel = iAbsLevel;
128538       pWriter->iIdx = iIdx;
128539
128540       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
128541         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
128542       }
128543
128544       pNode = &pWriter->aNodeWriter[nHeight];
128545       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
128546       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
128547       if( rc==SQLITE_OK ){
128548         memcpy(pNode->block.a, aRoot, nRoot);
128549         pNode->block.n = nRoot;
128550       }
128551
128552       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
128553         NodeReader reader;
128554         pNode = &pWriter->aNodeWriter[i];
128555
128556         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
128557         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
128558         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
128559         if( rc==SQLITE_OK ){
128560           memcpy(pNode->key.a, reader.term.a, reader.term.n);
128561           pNode->key.n = reader.term.n;
128562           if( i>0 ){
128563             char *aBlock = 0;
128564             int nBlock = 0;
128565             pNode = &pWriter->aNodeWriter[i-1];
128566             pNode->iBlock = reader.iChild;
128567             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
128568             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
128569             if( rc==SQLITE_OK ){
128570               memcpy(pNode->block.a, aBlock, nBlock);
128571               pNode->block.n = nBlock;
128572             }
128573             sqlite3_free(aBlock);
128574           }
128575         }
128576         nodeReaderRelease(&reader);
128577       }
128578     }
128579
128580     rc2 = sqlite3_reset(pSelect);
128581     if( rc==SQLITE_OK ) rc = rc2;
128582   }
128583
128584   return rc;
128585 }
128586
128587 /*
128588 ** Determine the largest segment index value that exists within absolute
128589 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
128590 ** one before returning SQLITE_OK. Or, if there are no segments at all 
128591 ** within level iAbsLevel, set *piIdx to zero.
128592 **
128593 ** If an error occurs, return an SQLite error code. The final value of
128594 ** *piIdx is undefined in this case.
128595 */
128596 static int fts3IncrmergeOutputIdx( 
128597   Fts3Table *p,                   /* FTS Table handle */
128598   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
128599   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
128600 ){
128601   int rc;
128602   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
128603
128604   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
128605   if( rc==SQLITE_OK ){
128606     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
128607     sqlite3_step(pOutputIdx);
128608     *piIdx = sqlite3_column_int(pOutputIdx, 0);
128609     rc = sqlite3_reset(pOutputIdx);
128610   }
128611
128612   return rc;
128613 }
128614
128615 /* 
128616 ** Allocate an appendable output segment on absolute level iAbsLevel+1
128617 ** with idx value iIdx.
128618 **
128619 ** In the %_segdir table, a segment is defined by the values in three
128620 ** columns:
128621 **
128622 **     start_block
128623 **     leaves_end_block
128624 **     end_block
128625 **
128626 ** When an appendable segment is allocated, it is estimated that the
128627 ** maximum number of leaf blocks that may be required is the sum of the
128628 ** number of leaf blocks consumed by the input segments, plus the number
128629 ** of input segments, multiplied by two. This value is stored in stack 
128630 ** variable nLeafEst.
128631 **
128632 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
128633 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
128634 ** array of leaf nodes starts at the first block allocated. The array
128635 ** of interior nodes that are parents of the leaf nodes start at block
128636 ** (start_block + (1 + end_block - start_block) / 16). And so on.
128637 **
128638 ** In the actual code below, the value "16" is replaced with the 
128639 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
128640 */
128641 static int fts3IncrmergeWriter( 
128642   Fts3Table *p,                   /* Fts3 table handle */
128643   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
128644   int iIdx,                       /* Index of new output segment */
128645   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
128646   IncrmergeWriter *pWriter        /* Populate this object */
128647 ){
128648   int rc;                         /* Return Code */
128649   int i;                          /* Iterator variable */
128650   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
128651   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
128652   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
128653
128654   /* Calculate nLeafEst. */
128655   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
128656   if( rc==SQLITE_OK ){
128657     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
128658     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
128659     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
128660       nLeafEst = sqlite3_column_int(pLeafEst, 0);
128661     }
128662     rc = sqlite3_reset(pLeafEst);
128663   }
128664   if( rc!=SQLITE_OK ) return rc;
128665
128666   /* Calculate the first block to use in the output segment */
128667   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
128668   if( rc==SQLITE_OK ){
128669     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
128670       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
128671       pWriter->iEnd = pWriter->iStart - 1;
128672       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
128673     }
128674     rc = sqlite3_reset(pFirstBlock);
128675   }
128676   if( rc!=SQLITE_OK ) return rc;
128677
128678   /* Insert the marker in the %_segments table to make sure nobody tries
128679   ** to steal the space just allocated. This is also used to identify 
128680   ** appendable segments.  */
128681   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
128682   if( rc!=SQLITE_OK ) return rc;
128683
128684   pWriter->iAbsLevel = iAbsLevel;
128685   pWriter->nLeafEst = nLeafEst;
128686   pWriter->iIdx = iIdx;
128687
128688   /* Set up the array of NodeWriter objects */
128689   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
128690     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
128691   }
128692   return SQLITE_OK;
128693 }
128694
128695 /*
128696 ** Remove an entry from the %_segdir table. This involves running the 
128697 ** following two statements:
128698 **
128699 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
128700 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
128701 **
128702 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
128703 ** statement ensures that the remaining segments have contiguously allocated
128704 ** idx values.
128705 */
128706 static int fts3RemoveSegdirEntry(
128707   Fts3Table *p,                   /* FTS3 table handle */
128708   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
128709   int iIdx                        /* Index of %_segdir entry to delete */
128710 ){
128711   int rc;                         /* Return code */
128712   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
128713
128714   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
128715   if( rc==SQLITE_OK ){
128716     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
128717     sqlite3_bind_int(pDelete, 2, iIdx);
128718     sqlite3_step(pDelete);
128719     rc = sqlite3_reset(pDelete);
128720   }
128721
128722   return rc;
128723 }
128724
128725 /*
128726 ** One or more segments have just been removed from absolute level iAbsLevel.
128727 ** Update the 'idx' values of the remaining segments in the level so that
128728 ** the idx values are a contiguous sequence starting from 0.
128729 */
128730 static int fts3RepackSegdirLevel(
128731   Fts3Table *p,                   /* FTS3 table handle */
128732   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
128733 ){
128734   int rc;                         /* Return code */
128735   int *aIdx = 0;                  /* Array of remaining idx values */
128736   int nIdx = 0;                   /* Valid entries in aIdx[] */
128737   int nAlloc = 0;                 /* Allocated size of aIdx[] */
128738   int i;                          /* Iterator variable */
128739   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
128740   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
128741
128742   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
128743   if( rc==SQLITE_OK ){
128744     int rc2;
128745     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
128746     while( SQLITE_ROW==sqlite3_step(pSelect) ){
128747       if( nIdx>=nAlloc ){
128748         int *aNew;
128749         nAlloc += 16;
128750         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
128751         if( !aNew ){
128752           rc = SQLITE_NOMEM;
128753           break;
128754         }
128755         aIdx = aNew;
128756       }
128757       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
128758     }
128759     rc2 = sqlite3_reset(pSelect);
128760     if( rc==SQLITE_OK ) rc = rc2;
128761   }
128762
128763   if( rc==SQLITE_OK ){
128764     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
128765   }
128766   if( rc==SQLITE_OK ){
128767     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
128768   }
128769
128770   assert( p->bIgnoreSavepoint==0 );
128771   p->bIgnoreSavepoint = 1;
128772   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
128773     if( aIdx[i]!=i ){
128774       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
128775       sqlite3_bind_int(pUpdate, 1, i);
128776       sqlite3_step(pUpdate);
128777       rc = sqlite3_reset(pUpdate);
128778     }
128779   }
128780   p->bIgnoreSavepoint = 0;
128781
128782   sqlite3_free(aIdx);
128783   return rc;
128784 }
128785
128786 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
128787   pNode->a[0] = (char)iHeight;
128788   if( iChild ){
128789     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
128790     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
128791   }else{
128792     assert( pNode->nAlloc>=1 );
128793     pNode->n = 1;
128794   }
128795 }
128796
128797 /*
128798 ** The first two arguments are a pointer to and the size of a segment b-tree
128799 ** node. The node may be a leaf or an internal node.
128800 **
128801 ** This function creates a new node image in blob object *pNew by copying
128802 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
128803 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
128804 */
128805 static int fts3TruncateNode(
128806   const char *aNode,              /* Current node image */
128807   int nNode,                      /* Size of aNode in bytes */
128808   Blob *pNew,                     /* OUT: Write new node image here */
128809   const char *zTerm,              /* Omit all terms smaller than this */
128810   int nTerm,                      /* Size of zTerm in bytes */
128811   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
128812 ){
128813   NodeReader reader;              /* Reader object */
128814   Blob prev = {0, 0, 0};          /* Previous term written to new node */
128815   int rc = SQLITE_OK;             /* Return code */
128816   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
128817
128818   /* Allocate required output space */
128819   blobGrowBuffer(pNew, nNode, &rc);
128820   if( rc!=SQLITE_OK ) return rc;
128821   pNew->n = 0;
128822
128823   /* Populate new node buffer */
128824   for(rc = nodeReaderInit(&reader, aNode, nNode); 
128825       rc==SQLITE_OK && reader.aNode; 
128826       rc = nodeReaderNext(&reader)
128827   ){
128828     if( pNew->n==0 ){
128829       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
128830       if( res<0 || (bLeaf==0 && res==0) ) continue;
128831       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
128832       *piBlock = reader.iChild;
128833     }
128834     rc = fts3AppendToNode(
128835         pNew, &prev, reader.term.a, reader.term.n,
128836         reader.aDoclist, reader.nDoclist
128837     );
128838     if( rc!=SQLITE_OK ) break;
128839   }
128840   if( pNew->n==0 ){
128841     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
128842     *piBlock = reader.iChild;
128843   }
128844   assert( pNew->n<=pNew->nAlloc );
128845
128846   nodeReaderRelease(&reader);
128847   sqlite3_free(prev.a);
128848   return rc;
128849 }
128850
128851 /*
128852 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
128853 ** level iAbsLevel. This may involve deleting entries from the %_segments
128854 ** table, and modifying existing entries in both the %_segments and %_segdir
128855 ** tables.
128856 **
128857 ** SQLITE_OK is returned if the segment is updated successfully. Or an
128858 ** SQLite error code otherwise.
128859 */
128860 static int fts3TruncateSegment(
128861   Fts3Table *p,                   /* FTS3 table handle */
128862   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
128863   int iIdx,                       /* Index within level of segment to modify */
128864   const char *zTerm,              /* Remove terms smaller than this */
128865   int nTerm                      /* Number of bytes in buffer zTerm */
128866 ){
128867   int rc = SQLITE_OK;             /* Return code */
128868   Blob root = {0,0,0};            /* New root page image */
128869   Blob block = {0,0,0};           /* Buffer used for any other block */
128870   sqlite3_int64 iBlock = 0;       /* Block id */
128871   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
128872   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
128873   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
128874
128875   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
128876   if( rc==SQLITE_OK ){
128877     int rc2;                      /* sqlite3_reset() return code */
128878     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
128879     sqlite3_bind_int(pFetch, 2, iIdx);
128880     if( SQLITE_ROW==sqlite3_step(pFetch) ){
128881       const char *aRoot = sqlite3_column_blob(pFetch, 4);
128882       int nRoot = sqlite3_column_bytes(pFetch, 4);
128883       iOldStart = sqlite3_column_int64(pFetch, 1);
128884       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
128885     }
128886     rc2 = sqlite3_reset(pFetch);
128887     if( rc==SQLITE_OK ) rc = rc2;
128888   }
128889
128890   while( rc==SQLITE_OK && iBlock ){
128891     char *aBlock = 0;
128892     int nBlock = 0;
128893     iNewStart = iBlock;
128894
128895     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
128896     if( rc==SQLITE_OK ){
128897       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
128898     }
128899     if( rc==SQLITE_OK ){
128900       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
128901     }
128902     sqlite3_free(aBlock);
128903   }
128904
128905   /* Variable iNewStart now contains the first valid leaf node. */
128906   if( rc==SQLITE_OK && iNewStart ){
128907     sqlite3_stmt *pDel = 0;
128908     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
128909     if( rc==SQLITE_OK ){
128910       sqlite3_bind_int64(pDel, 1, iOldStart);
128911       sqlite3_bind_int64(pDel, 2, iNewStart-1);
128912       sqlite3_step(pDel);
128913       rc = sqlite3_reset(pDel);
128914     }
128915   }
128916
128917   if( rc==SQLITE_OK ){
128918     sqlite3_stmt *pChomp = 0;
128919     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
128920     if( rc==SQLITE_OK ){
128921       sqlite3_bind_int64(pChomp, 1, iNewStart);
128922       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
128923       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
128924       sqlite3_bind_int(pChomp, 4, iIdx);
128925       sqlite3_step(pChomp);
128926       rc = sqlite3_reset(pChomp);
128927     }
128928   }
128929
128930   sqlite3_free(root.a);
128931   sqlite3_free(block.a);
128932   return rc;
128933 }
128934
128935 /*
128936 ** This function is called after an incrmental-merge operation has run to
128937 ** merge (or partially merge) two or more segments from absolute level
128938 ** iAbsLevel.
128939 **
128940 ** Each input segment is either removed from the db completely (if all of
128941 ** its data was copied to the output segment by the incrmerge operation)
128942 ** or modified in place so that it no longer contains those entries that
128943 ** have been duplicated in the output segment.
128944 */
128945 static int fts3IncrmergeChomp(
128946   Fts3Table *p,                   /* FTS table handle */
128947   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
128948   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
128949   int *pnRem                      /* Number of segments not deleted */
128950 ){
128951   int i;
128952   int nRem = 0;
128953   int rc = SQLITE_OK;
128954
128955   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
128956     Fts3SegReader *pSeg = 0;
128957     int j;
128958
128959     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
128960     ** somewhere in the pCsr->apSegment[] array.  */
128961     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
128962       pSeg = pCsr->apSegment[j];
128963       if( pSeg->iIdx==i ) break;
128964     }
128965     assert( j<pCsr->nSegment && pSeg->iIdx==i );
128966
128967     if( pSeg->aNode==0 ){
128968       /* Seg-reader is at EOF. Remove the entire input segment. */
128969       rc = fts3DeleteSegment(p, pSeg);
128970       if( rc==SQLITE_OK ){
128971         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
128972       }
128973       *pnRem = 0;
128974     }else{
128975       /* The incremental merge did not copy all the data from this 
128976       ** segment to the upper level. The segment is modified in place
128977       ** so that it contains no keys smaller than zTerm/nTerm. */ 
128978       const char *zTerm = pSeg->zTerm;
128979       int nTerm = pSeg->nTerm;
128980       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
128981       nRem++;
128982     }
128983   }
128984
128985   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
128986     rc = fts3RepackSegdirLevel(p, iAbsLevel);
128987   }
128988
128989   *pnRem = nRem;
128990   return rc;
128991 }
128992
128993 /*
128994 ** Store an incr-merge hint in the database.
128995 */
128996 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
128997   sqlite3_stmt *pReplace = 0;
128998   int rc;                         /* Return code */
128999
129000   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
129001   if( rc==SQLITE_OK ){
129002     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
129003     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
129004     sqlite3_step(pReplace);
129005     rc = sqlite3_reset(pReplace);
129006   }
129007
129008   return rc;
129009 }
129010
129011 /*
129012 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
129013 ** exists, is stored in the rowid==1 row of the %_stat table.
129014 **
129015 ** If successful, populate blob *pHint with the value read from the %_stat
129016 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
129017 ** SQLite error code.
129018 */
129019 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
129020   sqlite3_stmt *pSelect = 0;
129021   int rc;
129022
129023   pHint->n = 0;
129024   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
129025   if( rc==SQLITE_OK ){
129026     int rc2;
129027     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
129028     if( SQLITE_ROW==sqlite3_step(pSelect) ){
129029       const char *aHint = sqlite3_column_blob(pSelect, 0);
129030       int nHint = sqlite3_column_bytes(pSelect, 0);
129031       if( aHint ){
129032         blobGrowBuffer(pHint, nHint, &rc);
129033         if( rc==SQLITE_OK ){
129034           memcpy(pHint->a, aHint, nHint);
129035           pHint->n = nHint;
129036         }
129037       }
129038     }
129039     rc2 = sqlite3_reset(pSelect);
129040     if( rc==SQLITE_OK ) rc = rc2;
129041   }
129042
129043   return rc;
129044 }
129045
129046 /*
129047 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129048 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
129049 ** consists of two varints, the absolute level number of the input segments 
129050 ** and the number of input segments.
129051 **
129052 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
129053 ** set *pRc to an SQLite error code before returning.
129054 */
129055 static void fts3IncrmergeHintPush(
129056   Blob *pHint,                    /* Hint blob to append to */
129057   i64 iAbsLevel,                  /* First varint to store in hint */
129058   int nInput,                     /* Second varint to store in hint */
129059   int *pRc                        /* IN/OUT: Error code */
129060 ){
129061   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
129062   if( *pRc==SQLITE_OK ){
129063     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
129064     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
129065   }
129066 }
129067
129068 /*
129069 ** Read the last entry (most recently pushed) from the hint blob *pHint
129070 ** and then remove the entry. Write the two values read to *piAbsLevel and 
129071 ** *pnInput before returning.
129072 **
129073 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
129074 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
129075 */
129076 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
129077   const int nHint = pHint->n;
129078   int i;
129079
129080   i = pHint->n-2;
129081   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
129082   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
129083
129084   pHint->n = i;
129085   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
129086   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
129087   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
129088
129089   return SQLITE_OK;
129090 }
129091
129092
129093 /*
129094 ** Attempt an incremental merge that writes nMerge leaf blocks.
129095 **
129096 ** Incremental merges happen nMin segments at a time. The two
129097 ** segments to be merged are the nMin oldest segments (the ones with
129098 ** the smallest indexes) in the highest level that contains at least
129099 ** nMin segments. Multiple merges might occur in an attempt to write the 
129100 ** quota of nMerge leaf blocks.
129101 */
129102 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
129103   int rc;                         /* Return code */
129104   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
129105   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
129106   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
129107   IncrmergeWriter *pWriter;       /* Writer object */
129108   int nSeg = 0;                   /* Number of input segments */
129109   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
129110   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
129111   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
129112
129113   /* Allocate space for the cursor, filter and writer objects */
129114   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
129115   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
129116   if( !pWriter ) return SQLITE_NOMEM;
129117   pFilter = (Fts3SegFilter *)&pWriter[1];
129118   pCsr = (Fts3MultiSegReader *)&pFilter[1];
129119
129120   rc = fts3IncrmergeHintLoad(p, &hint);
129121   while( rc==SQLITE_OK && nRem>0 ){
129122     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
129123     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
129124     int bUseHint = 0;             /* True if attempting to append */
129125
129126     /* Search the %_segdir table for the absolute level with the smallest
129127     ** relative level number that contains at least nMin segments, if any.
129128     ** If one is found, set iAbsLevel to the absolute level number and
129129     ** nSeg to nMin. If no level with at least nMin segments can be found, 
129130     ** set nSeg to -1.
129131     */
129132     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
129133     sqlite3_bind_int(pFindLevel, 1, nMin);
129134     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
129135       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
129136       nSeg = nMin;
129137     }else{
129138       nSeg = -1;
129139     }
129140     rc = sqlite3_reset(pFindLevel);
129141
129142     /* If the hint read from the %_stat table is not empty, check if the
129143     ** last entry in it specifies a relative level smaller than or equal
129144     ** to the level identified by the block above (if any). If so, this 
129145     ** iteration of the loop will work on merging at the hinted level.
129146     */
129147     if( rc==SQLITE_OK && hint.n ){
129148       int nHint = hint.n;
129149       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
129150       int nHintSeg = 0;                     /* Hint number of segments */
129151
129152       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
129153       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
129154         iAbsLevel = iHintAbsLevel;
129155         nSeg = nHintSeg;
129156         bUseHint = 1;
129157         bDirtyHint = 1;
129158       }else{
129159         /* This undoes the effect of the HintPop() above - so that no entry
129160         ** is removed from the hint blob.  */
129161         hint.n = nHint;
129162       }
129163     }
129164
129165     /* If nSeg is less that zero, then there is no level with at least
129166     ** nMin segments and no hint in the %_stat table. No work to do.
129167     ** Exit early in this case.  */
129168     if( nSeg<0 ) break;
129169
129170     /* Open a cursor to iterate through the contents of the oldest nSeg 
129171     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
129172     ** the 'hint' parameters, it is possible that there are less than nSeg
129173     ** segments available in level iAbsLevel. In this case, no work is
129174     ** done on iAbsLevel - fall through to the next iteration of the loop 
129175     ** to start work on some other level.  */
129176     memset(pWriter, 0, nAlloc);
129177     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
129178     if( rc==SQLITE_OK ){
129179       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
129180     }
129181     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
129182      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
129183      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
129184     ){
129185       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
129186       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
129187       if( rc==SQLITE_OK ){
129188         if( bUseHint && iIdx>0 ){
129189           const char *zKey = pCsr->zTerm;
129190           int nKey = pCsr->nTerm;
129191           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
129192         }else{
129193           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
129194         }
129195       }
129196
129197       if( rc==SQLITE_OK && pWriter->nLeafEst ){
129198         fts3LogMerge(nSeg, iAbsLevel);
129199         do {
129200           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
129201           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
129202           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
129203         }while( rc==SQLITE_ROW );
129204
129205         /* Update or delete the input segments */
129206         if( rc==SQLITE_OK ){
129207           nRem -= (1 + pWriter->nWork);
129208           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
129209           if( nSeg!=0 ){
129210             bDirtyHint = 1;
129211             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
129212           }
129213         }
129214       }
129215
129216       fts3IncrmergeRelease(p, pWriter, &rc);
129217     }
129218
129219     sqlite3Fts3SegReaderFinish(pCsr);
129220   }
129221
129222   /* Write the hint values into the %_stat table for the next incr-merger */
129223   if( bDirtyHint && rc==SQLITE_OK ){
129224     rc = fts3IncrmergeHintStore(p, &hint);
129225   }
129226
129227   sqlite3_free(pWriter);
129228   sqlite3_free(hint.a);
129229   return rc;
129230 }
129231
129232 /*
129233 ** Convert the text beginning at *pz into an integer and return
129234 ** its value.  Advance *pz to point to the first character past
129235 ** the integer.
129236 */
129237 static int fts3Getint(const char **pz){
129238   const char *z = *pz;
129239   int i = 0;
129240   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
129241   *pz = z;
129242   return i;
129243 }
129244
129245 /*
129246 ** Process statements of the form:
129247 **
129248 **    INSERT INTO table(table) VALUES('merge=A,B');
129249 **
129250 ** A and B are integers that decode to be the number of leaf pages
129251 ** written for the merge, and the minimum number of segments on a level
129252 ** before it will be selected for a merge, respectively.
129253 */
129254 static int fts3DoIncrmerge(
129255   Fts3Table *p,                   /* FTS3 table handle */
129256   const char *zParam              /* Nul-terminated string containing "A,B" */
129257 ){
129258   int rc;
129259   int nMin = (FTS3_MERGE_COUNT / 2);
129260   int nMerge = 0;
129261   const char *z = zParam;
129262
129263   /* Read the first integer value */
129264   nMerge = fts3Getint(&z);
129265
129266   /* If the first integer value is followed by a ',',  read the second
129267   ** integer value. */
129268   if( z[0]==',' && z[1]!='\0' ){
129269     z++;
129270     nMin = fts3Getint(&z);
129271   }
129272
129273   if( z[0]!='\0' || nMin<2 ){
129274     rc = SQLITE_ERROR;
129275   }else{
129276     rc = SQLITE_OK;
129277     if( !p->bHasStat ){
129278       assert( p->bFts4==0 );
129279       sqlite3Fts3CreateStatTable(&rc, p);
129280     }
129281     if( rc==SQLITE_OK ){
129282       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
129283     }
129284     sqlite3Fts3SegmentsClose(p);
129285   }
129286   return rc;
129287 }
129288
129289 /*
129290 ** Process statements of the form:
129291 **
129292 **    INSERT INTO table(table) VALUES('automerge=X');
129293 **
129294 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
129295 ** turn it on.  The setting is persistent.
129296 */
129297 static int fts3DoAutoincrmerge(
129298   Fts3Table *p,                   /* FTS3 table handle */
129299   const char *zParam              /* Nul-terminated string containing boolean */
129300 ){
129301   int rc = SQLITE_OK;
129302   sqlite3_stmt *pStmt = 0;
129303   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
129304   if( !p->bHasStat ){
129305     assert( p->bFts4==0 );
129306     sqlite3Fts3CreateStatTable(&rc, p);
129307     if( rc ) return rc;
129308   }
129309   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
129310   if( rc ) return rc;;
129311   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
129312   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
129313   sqlite3_step(pStmt);
129314   rc = sqlite3_reset(pStmt);
129315   return rc;
129316 }
129317
129318 /*
129319 ** Return a 64-bit checksum for the FTS index entry specified by the
129320 ** arguments to this function.
129321 */
129322 static u64 fts3ChecksumEntry(
129323   const char *zTerm,              /* Pointer to buffer containing term */
129324   int nTerm,                      /* Size of zTerm in bytes */
129325   int iLangid,                    /* Language id for current row */
129326   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
129327   i64 iDocid,                     /* Docid for current row. */
129328   int iCol,                       /* Column number */
129329   int iPos                        /* Position */
129330 ){
129331   int i;
129332   u64 ret = (u64)iDocid;
129333
129334   ret += (ret<<3) + iLangid;
129335   ret += (ret<<3) + iIndex;
129336   ret += (ret<<3) + iCol;
129337   ret += (ret<<3) + iPos;
129338   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
129339
129340   return ret;
129341 }
129342
129343 /*
129344 ** Return a checksum of all entries in the FTS index that correspond to
129345 ** language id iLangid. The checksum is calculated by XORing the checksums
129346 ** of each individual entry (see fts3ChecksumEntry()) together.
129347 **
129348 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
129349 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
129350 ** return value is undefined in this case.
129351 */
129352 static u64 fts3ChecksumIndex(
129353   Fts3Table *p,                   /* FTS3 table handle */
129354   int iLangid,                    /* Language id to return cksum for */
129355   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
129356   int *pRc                        /* OUT: Return code */
129357 ){
129358   Fts3SegFilter filter;
129359   Fts3MultiSegReader csr;
129360   int rc;
129361   u64 cksum = 0;
129362
129363   assert( *pRc==SQLITE_OK );
129364
129365   memset(&filter, 0, sizeof(filter));
129366   memset(&csr, 0, sizeof(csr));
129367   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
129368   filter.flags |= FTS3_SEGMENT_SCAN;
129369
129370   rc = sqlite3Fts3SegReaderCursor(
129371       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
129372   );
129373   if( rc==SQLITE_OK ){
129374     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
129375   }
129376
129377   if( rc==SQLITE_OK ){
129378     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
129379       char *pCsr = csr.aDoclist;
129380       char *pEnd = &pCsr[csr.nDoclist];
129381
129382       i64 iDocid = 0;
129383       i64 iCol = 0;
129384       i64 iPos = 0;
129385
129386       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
129387       while( pCsr<pEnd ){
129388         i64 iVal = 0;
129389         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
129390         if( pCsr<pEnd ){
129391           if( iVal==0 || iVal==1 ){
129392             iCol = 0;
129393             iPos = 0;
129394             if( iVal ){
129395               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
129396             }else{
129397               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
129398               iDocid += iVal;
129399             }
129400           }else{
129401             iPos += (iVal - 2);
129402             cksum = cksum ^ fts3ChecksumEntry(
129403                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
129404                 (int)iCol, (int)iPos
129405             );
129406           }
129407         }
129408       }
129409     }
129410   }
129411   sqlite3Fts3SegReaderFinish(&csr);
129412
129413   *pRc = rc;
129414   return cksum;
129415 }
129416
129417 /*
129418 ** Check if the contents of the FTS index match the current contents of the
129419 ** content table. If no error occurs and the contents do match, set *pbOk
129420 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
129421 ** to false before returning.
129422 **
129423 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
129424 ** code. The final value of *pbOk is undefined in this case.
129425 */
129426 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
129427   int rc = SQLITE_OK;             /* Return code */
129428   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
129429   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
129430   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
129431
129432   /* This block calculates the checksum according to the FTS index. */
129433   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
129434   if( rc==SQLITE_OK ){
129435     int rc2;
129436     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
129437     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
129438       int iLangid = sqlite3_column_int(pAllLangid, 0);
129439       int i;
129440       for(i=0; i<p->nIndex; i++){
129441         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
129442       }
129443     }
129444     rc2 = sqlite3_reset(pAllLangid);
129445     if( rc==SQLITE_OK ) rc = rc2;
129446   }
129447
129448   /* This block calculates the checksum according to the %_content table */
129449   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
129450   if( rc==SQLITE_OK ){
129451     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
129452     sqlite3_stmt *pStmt = 0;
129453     char *zSql;
129454    
129455     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
129456     if( !zSql ){
129457       rc = SQLITE_NOMEM;
129458     }else{
129459       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
129460       sqlite3_free(zSql);
129461     }
129462
129463     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
129464       i64 iDocid = sqlite3_column_int64(pStmt, 0);
129465       int iLang = langidFromSelect(p, pStmt);
129466       int iCol;
129467
129468       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
129469         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
129470         int nText = sqlite3_column_bytes(pStmt, iCol+1);
129471         sqlite3_tokenizer_cursor *pT = 0;
129472
129473         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
129474         while( rc==SQLITE_OK ){
129475           char const *zToken;       /* Buffer containing token */
129476           int nToken;               /* Number of bytes in token */
129477           int iDum1, iDum2;         /* Dummy variables */
129478           int iPos;                 /* Position of token in zText */
129479
129480           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
129481           if( rc==SQLITE_OK ){
129482             int i;
129483             cksum2 = cksum2 ^ fts3ChecksumEntry(
129484                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
129485             );
129486             for(i=1; i<p->nIndex; i++){
129487               if( p->aIndex[i].nPrefix<=nToken ){
129488                 cksum2 = cksum2 ^ fts3ChecksumEntry(
129489                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
129490                 );
129491               }
129492             }
129493           }
129494         }
129495         if( pT ) pModule->xClose(pT);
129496         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129497       }
129498     }
129499
129500     sqlite3_finalize(pStmt);
129501   }
129502
129503   *pbOk = (cksum1==cksum2);
129504   return rc;
129505 }
129506
129507 /*
129508 ** Run the integrity-check. If no error occurs and the current contents of
129509 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
129510 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
129511 **
129512 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
129513 ** error code.
129514 **
129515 ** The integrity-check works as follows. For each token and indexed token
129516 ** prefix in the document set, a 64-bit checksum is calculated (by code
129517 ** in fts3ChecksumEntry()) based on the following:
129518 **
129519 **     + The index number (0 for the main index, 1 for the first prefix
129520 **       index etc.),
129521 **     + The token (or token prefix) text itself, 
129522 **     + The language-id of the row it appears in,
129523 **     + The docid of the row it appears in,
129524 **     + The column it appears in, and
129525 **     + The tokens position within that column.
129526 **
129527 ** The checksums for all entries in the index are XORed together to create
129528 ** a single checksum for the entire index.
129529 **
129530 ** The integrity-check code calculates the same checksum in two ways:
129531 **
129532 **     1. By scanning the contents of the FTS index, and 
129533 **     2. By scanning and tokenizing the content table.
129534 **
129535 ** If the two checksums are identical, the integrity-check is deemed to have
129536 ** passed.
129537 */
129538 static int fts3DoIntegrityCheck(
129539   Fts3Table *p                    /* FTS3 table handle */
129540 ){
129541   int rc;
129542   int bOk = 0;
129543   rc = fts3IntegrityCheck(p, &bOk);
129544   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
129545   return rc;
129546 }
129547
129548 /*
129549 ** Handle a 'special' INSERT of the form:
129550 **
129551 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
129552 **
129553 ** Argument pVal contains the result of <expr>. Currently the only 
129554 ** meaningful value to insert is the text 'optimize'.
129555 */
129556 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
129557   int rc;                         /* Return Code */
129558   const char *zVal = (const char *)sqlite3_value_text(pVal);
129559   int nVal = sqlite3_value_bytes(pVal);
129560
129561   if( !zVal ){
129562     return SQLITE_NOMEM;
129563   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
129564     rc = fts3DoOptimize(p, 0);
129565   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
129566     rc = fts3DoRebuild(p);
129567   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
129568     rc = fts3DoIntegrityCheck(p);
129569   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
129570     rc = fts3DoIncrmerge(p, &zVal[6]);
129571   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
129572     rc = fts3DoAutoincrmerge(p, &zVal[10]);
129573 #ifdef SQLITE_TEST
129574   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
129575     p->nNodeSize = atoi(&zVal[9]);
129576     rc = SQLITE_OK;
129577   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
129578     p->nMaxPendingData = atoi(&zVal[11]);
129579     rc = SQLITE_OK;
129580 #endif
129581   }else{
129582     rc = SQLITE_ERROR;
129583   }
129584
129585   return rc;
129586 }
129587
129588 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
129589 /*
129590 ** Delete all cached deferred doclists. Deferred doclists are cached
129591 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
129592 */
129593 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
129594   Fts3DeferredToken *pDef;
129595   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
129596     fts3PendingListDelete(pDef->pList);
129597     pDef->pList = 0;
129598   }
129599 }
129600
129601 /*
129602 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
129603 ** this list using sqlite3Fts3DeferToken().
129604 */
129605 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
129606   Fts3DeferredToken *pDef;
129607   Fts3DeferredToken *pNext;
129608   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
129609     pNext = pDef->pNext;
129610     fts3PendingListDelete(pDef->pList);
129611     sqlite3_free(pDef);
129612   }
129613   pCsr->pDeferred = 0;
129614 }
129615
129616 /*
129617 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
129618 ** based on the row that pCsr currently points to.
129619 **
129620 ** A deferred-doclist is like any other doclist with position information
129621 ** included, except that it only contains entries for a single row of the
129622 ** table, not for all rows.
129623 */
129624 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
129625   int rc = SQLITE_OK;             /* Return code */
129626   if( pCsr->pDeferred ){
129627     int i;                        /* Used to iterate through table columns */
129628     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
129629     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
129630   
129631     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
129632     sqlite3_tokenizer *pT = p->pTokenizer;
129633     sqlite3_tokenizer_module const *pModule = pT->pModule;
129634    
129635     assert( pCsr->isRequireSeek==0 );
129636     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
129637   
129638     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
129639       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
129640       sqlite3_tokenizer_cursor *pTC = 0;
129641   
129642       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
129643       while( rc==SQLITE_OK ){
129644         char const *zToken;       /* Buffer containing token */
129645         int nToken;               /* Number of bytes in token */
129646         int iDum1, iDum2;         /* Dummy variables */
129647         int iPos;                 /* Position of token in zText */
129648   
129649         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
129650         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
129651           Fts3PhraseToken *pPT = pDef->pToken;
129652           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
129653            && (pPT->bFirst==0 || iPos==0)
129654            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
129655            && (0==memcmp(zToken, pPT->z, pPT->n))
129656           ){
129657             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
129658           }
129659         }
129660       }
129661       if( pTC ) pModule->xClose(pTC);
129662       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129663     }
129664   
129665     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
129666       if( pDef->pList ){
129667         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
129668       }
129669     }
129670   }
129671
129672   return rc;
129673 }
129674
129675 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
129676   Fts3DeferredToken *p, 
129677   char **ppData, 
129678   int *pnData
129679 ){
129680   char *pRet;
129681   int nSkip;
129682   sqlite3_int64 dummy;
129683
129684   *ppData = 0;
129685   *pnData = 0;
129686
129687   if( p->pList==0 ){
129688     return SQLITE_OK;
129689   }
129690
129691   pRet = (char *)sqlite3_malloc(p->pList->nData);
129692   if( !pRet ) return SQLITE_NOMEM;
129693
129694   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
129695   *pnData = p->pList->nData - nSkip;
129696   *ppData = pRet;
129697   
129698   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
129699   return SQLITE_OK;
129700 }
129701
129702 /*
129703 ** Add an entry for token pToken to the pCsr->pDeferred list.
129704 */
129705 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
129706   Fts3Cursor *pCsr,               /* Fts3 table cursor */
129707   Fts3PhraseToken *pToken,        /* Token to defer */
129708   int iCol                        /* Column that token must appear in (or -1) */
129709 ){
129710   Fts3DeferredToken *pDeferred;
129711   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
129712   if( !pDeferred ){
129713     return SQLITE_NOMEM;
129714   }
129715   memset(pDeferred, 0, sizeof(*pDeferred));
129716   pDeferred->pToken = pToken;
129717   pDeferred->pNext = pCsr->pDeferred; 
129718   pDeferred->iCol = iCol;
129719   pCsr->pDeferred = pDeferred;
129720
129721   assert( pToken->pDeferred==0 );
129722   pToken->pDeferred = pDeferred;
129723
129724   return SQLITE_OK;
129725 }
129726 #endif
129727
129728 /*
129729 ** SQLite value pRowid contains the rowid of a row that may or may not be
129730 ** present in the FTS3 table. If it is, delete it and adjust the contents
129731 ** of subsiduary data structures accordingly.
129732 */
129733 static int fts3DeleteByRowid(
129734   Fts3Table *p, 
129735   sqlite3_value *pRowid, 
129736   int *pnDoc,
129737   u32 *aSzDel
129738 ){
129739   int isEmpty = 0;
129740   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
129741   if( rc==SQLITE_OK ){
129742     if( isEmpty ){
129743       /* Deleting this row means the whole table is empty. In this case
129744       ** delete the contents of all three tables and throw away any
129745       ** data in the pendingTerms hash table.  */
129746       rc = fts3DeleteAll(p, 1);
129747       *pnDoc = *pnDoc - 1;
129748     }else{
129749       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
129750       if( p->zContentTbl==0 ){
129751         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
129752         if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
129753       }else{
129754         *pnDoc = *pnDoc - 1;
129755       }
129756       if( p->bHasDocsize ){
129757         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
129758       }
129759     }
129760   }
129761
129762   return rc;
129763 }
129764
129765 /*
129766 ** This function does the work for the xUpdate method of FTS3 virtual
129767 ** tables. The schema of the virtual table being:
129768 **
129769 **     CREATE TABLE <table name>( 
129770 **       <user columns>,
129771 **       <table name> HIDDEN, 
129772 **       docid HIDDEN, 
129773 **       <langid> HIDDEN
129774 **     );
129775 **
129776 ** 
129777 */
129778 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
129779   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
129780   int nArg,                       /* Size of argument array */
129781   sqlite3_value **apVal,          /* Array of arguments */
129782   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
129783 ){
129784   Fts3Table *p = (Fts3Table *)pVtab;
129785   int rc = SQLITE_OK;             /* Return Code */
129786   int isRemove = 0;               /* True for an UPDATE or DELETE */
129787   u32 *aSzIns = 0;                /* Sizes of inserted documents */
129788   u32 *aSzDel;                    /* Sizes of deleted documents */
129789   int nChng = 0;                  /* Net change in number of documents */
129790   int bInsertDone = 0;
129791
129792   assert( p->pSegments==0 );
129793   assert( 
129794       nArg==1                     /* DELETE operations */
129795    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
129796   );
129797
129798   /* Check for a "special" INSERT operation. One of the form:
129799   **
129800   **   INSERT INTO xyz(xyz) VALUES('command');
129801   */
129802   if( nArg>1 
129803    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
129804    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
129805   ){
129806     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
129807     goto update_out;
129808   }
129809
129810   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
129811     rc = SQLITE_CONSTRAINT;
129812     goto update_out;
129813   }
129814
129815   /* Allocate space to hold the change in document sizes */
129816   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
129817   if( aSzIns==0 ){
129818     rc = SQLITE_NOMEM;
129819     goto update_out;
129820   }
129821   aSzDel = &aSzIns[p->nColumn+1];
129822   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
129823
129824   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
129825   ** value, then this operation requires constraint handling.
129826   **
129827   ** If the on-conflict mode is REPLACE, this means that the existing row
129828   ** should be deleted from the database before inserting the new row. Or,
129829   ** if the on-conflict mode is other than REPLACE, then this method must
129830   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
129831   ** modify the database file.
129832   */
129833   if( nArg>1 && p->zContentTbl==0 ){
129834     /* Find the value object that holds the new rowid value. */
129835     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
129836     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
129837       pNewRowid = apVal[1];
129838     }
129839
129840     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
129841         sqlite3_value_type(apVal[0])==SQLITE_NULL
129842      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
129843     )){
129844       /* The new rowid is not NULL (in this case the rowid will be
129845       ** automatically assigned and there is no chance of a conflict), and 
129846       ** the statement is either an INSERT or an UPDATE that modifies the
129847       ** rowid column. So if the conflict mode is REPLACE, then delete any
129848       ** existing row with rowid=pNewRowid. 
129849       **
129850       ** Or, if the conflict mode is not REPLACE, insert the new record into 
129851       ** the %_content table. If we hit the duplicate rowid constraint (or any
129852       ** other error) while doing so, return immediately.
129853       **
129854       ** This branch may also run if pNewRowid contains a value that cannot
129855       ** be losslessly converted to an integer. In this case, the eventual 
129856       ** call to fts3InsertData() (either just below or further on in this
129857       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
129858       ** invoked, it will delete zero rows (since no row will have
129859       ** docid=$pNewRowid if $pNewRowid is not an integer value).
129860       */
129861       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
129862         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
129863       }else{
129864         rc = fts3InsertData(p, apVal, pRowid);
129865         bInsertDone = 1;
129866       }
129867     }
129868   }
129869   if( rc!=SQLITE_OK ){
129870     goto update_out;
129871   }
129872
129873   /* If this is a DELETE or UPDATE operation, remove the old record. */
129874   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
129875     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
129876     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
129877     isRemove = 1;
129878   }
129879   
129880   /* If this is an INSERT or UPDATE operation, insert the new record. */
129881   if( nArg>1 && rc==SQLITE_OK ){
129882     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
129883     if( bInsertDone==0 ){
129884       rc = fts3InsertData(p, apVal, pRowid);
129885       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
129886         rc = FTS_CORRUPT_VTAB;
129887       }
129888     }
129889     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
129890       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
129891     }
129892     if( rc==SQLITE_OK ){
129893       assert( p->iPrevDocid==*pRowid );
129894       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
129895     }
129896     if( p->bHasDocsize ){
129897       fts3InsertDocsize(&rc, p, aSzIns);
129898     }
129899     nChng++;
129900   }
129901
129902   if( p->bFts4 ){
129903     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
129904   }
129905
129906  update_out:
129907   sqlite3_free(aSzIns);
129908   sqlite3Fts3SegmentsClose(p);
129909   return rc;
129910 }
129911
129912 /* 
129913 ** Flush any data in the pending-terms hash table to disk. If successful,
129914 ** merge all segments in the database (including the new segment, if 
129915 ** there was any data to flush) into a single segment. 
129916 */
129917 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
129918   int rc;
129919   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
129920   if( rc==SQLITE_OK ){
129921     rc = fts3DoOptimize(p, 1);
129922     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
129923       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
129924       if( rc2!=SQLITE_OK ) rc = rc2;
129925     }else{
129926       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
129927       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
129928     }
129929   }
129930   sqlite3Fts3SegmentsClose(p);
129931   return rc;
129932 }
129933
129934 #endif
129935
129936 /************** End of fts3_write.c ******************************************/
129937 /************** Begin file fts3_snippet.c ************************************/
129938 /*
129939 ** 2009 Oct 23
129940 **
129941 ** The author disclaims copyright to this source code.  In place of
129942 ** a legal notice, here is a blessing:
129943 **
129944 **    May you do good and not evil.
129945 **    May you find forgiveness for yourself and forgive others.
129946 **    May you share freely, never taking more than you give.
129947 **
129948 ******************************************************************************
129949 */
129950
129951 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129952
129953 /* #include <string.h> */
129954 /* #include <assert.h> */
129955
129956 /*
129957 ** Characters that may appear in the second argument to matchinfo().
129958 */
129959 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
129960 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
129961 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
129962 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
129963 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
129964 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
129965 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
129966
129967 /*
129968 ** The default value for the second argument to matchinfo(). 
129969 */
129970 #define FTS3_MATCHINFO_DEFAULT   "pcx"
129971
129972
129973 /*
129974 ** Used as an fts3ExprIterate() context when loading phrase doclists to
129975 ** Fts3Expr.aDoclist[]/nDoclist.
129976 */
129977 typedef struct LoadDoclistCtx LoadDoclistCtx;
129978 struct LoadDoclistCtx {
129979   Fts3Cursor *pCsr;               /* FTS3 Cursor */
129980   int nPhrase;                    /* Number of phrases seen so far */
129981   int nToken;                     /* Number of tokens seen so far */
129982 };
129983
129984 /*
129985 ** The following types are used as part of the implementation of the 
129986 ** fts3BestSnippet() routine.
129987 */
129988 typedef struct SnippetIter SnippetIter;
129989 typedef struct SnippetPhrase SnippetPhrase;
129990 typedef struct SnippetFragment SnippetFragment;
129991
129992 struct SnippetIter {
129993   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
129994   int iCol;                       /* Extract snippet from this column */
129995   int nSnippet;                   /* Requested snippet length (in tokens) */
129996   int nPhrase;                    /* Number of phrases in query */
129997   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
129998   int iCurrent;                   /* First token of current snippet */
129999 };
130000
130001 struct SnippetPhrase {
130002   int nToken;                     /* Number of tokens in phrase */
130003   char *pList;                    /* Pointer to start of phrase position list */
130004   int iHead;                      /* Next value in position list */
130005   char *pHead;                    /* Position list data following iHead */
130006   int iTail;                      /* Next value in trailing position list */
130007   char *pTail;                    /* Position list data following iTail */
130008 };
130009
130010 struct SnippetFragment {
130011   int iCol;                       /* Column snippet is extracted from */
130012   int iPos;                       /* Index of first token in snippet */
130013   u64 covered;                    /* Mask of query phrases covered */
130014   u64 hlmask;                     /* Mask of snippet terms to highlight */
130015 };
130016
130017 /*
130018 ** This type is used as an fts3ExprIterate() context object while 
130019 ** accumulating the data returned by the matchinfo() function.
130020 */
130021 typedef struct MatchInfo MatchInfo;
130022 struct MatchInfo {
130023   Fts3Cursor *pCursor;            /* FTS3 Cursor */
130024   int nCol;                       /* Number of columns in table */
130025   int nPhrase;                    /* Number of matchable phrases in query */
130026   sqlite3_int64 nDoc;             /* Number of docs in database */
130027   u32 *aMatchinfo;                /* Pre-allocated buffer */
130028 };
130029
130030
130031
130032 /*
130033 ** The snippet() and offsets() functions both return text values. An instance
130034 ** of the following structure is used to accumulate those values while the
130035 ** functions are running. See fts3StringAppend() for details.
130036 */
130037 typedef struct StrBuffer StrBuffer;
130038 struct StrBuffer {
130039   char *z;                        /* Pointer to buffer containing string */
130040   int n;                          /* Length of z in bytes (excl. nul-term) */
130041   int nAlloc;                     /* Allocated size of buffer z in bytes */
130042 };
130043
130044
130045 /*
130046 ** This function is used to help iterate through a position-list. A position
130047 ** list is a list of unique integers, sorted from smallest to largest. Each
130048 ** element of the list is represented by an FTS3 varint that takes the value
130049 ** of the difference between the current element and the previous one plus
130050 ** two. For example, to store the position-list:
130051 **
130052 **     4 9 113
130053 **
130054 ** the three varints:
130055 **
130056 **     6 7 106
130057 **
130058 ** are encoded.
130059 **
130060 ** When this function is called, *pp points to the start of an element of
130061 ** the list. *piPos contains the value of the previous entry in the list.
130062 ** After it returns, *piPos contains the value of the next element of the
130063 ** list and *pp is advanced to the following varint.
130064 */
130065 static void fts3GetDeltaPosition(char **pp, int *piPos){
130066   int iVal;
130067   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
130068   *piPos += (iVal-2);
130069 }
130070
130071 /*
130072 ** Helper function for fts3ExprIterate() (see below).
130073 */
130074 static int fts3ExprIterate2(
130075   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
130076   int *piPhrase,                  /* Pointer to phrase counter */
130077   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
130078   void *pCtx                      /* Second argument to pass to callback */
130079 ){
130080   int rc;                         /* Return code */
130081   int eType = pExpr->eType;       /* Type of expression node pExpr */
130082
130083   if( eType!=FTSQUERY_PHRASE ){
130084     assert( pExpr->pLeft && pExpr->pRight );
130085     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
130086     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
130087       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
130088     }
130089   }else{
130090     rc = x(pExpr, *piPhrase, pCtx);
130091     (*piPhrase)++;
130092   }
130093   return rc;
130094 }
130095
130096 /*
130097 ** Iterate through all phrase nodes in an FTS3 query, except those that
130098 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
130099 ** For each phrase node found, the supplied callback function is invoked.
130100 **
130101 ** If the callback function returns anything other than SQLITE_OK, 
130102 ** the iteration is abandoned and the error code returned immediately.
130103 ** Otherwise, SQLITE_OK is returned after a callback has been made for
130104 ** all eligible phrase nodes.
130105 */
130106 static int fts3ExprIterate(
130107   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
130108   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
130109   void *pCtx                      /* Second argument to pass to callback */
130110 ){
130111   int iPhrase = 0;                /* Variable used as the phrase counter */
130112   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
130113 }
130114
130115 /*
130116 ** This is an fts3ExprIterate() callback used while loading the doclists
130117 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
130118 ** fts3ExprLoadDoclists().
130119 */
130120 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
130121   int rc = SQLITE_OK;
130122   Fts3Phrase *pPhrase = pExpr->pPhrase;
130123   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
130124
130125   UNUSED_PARAMETER(iPhrase);
130126
130127   p->nPhrase++;
130128   p->nToken += pPhrase->nToken;
130129
130130   return rc;
130131 }
130132
130133 /*
130134 ** Load the doclists for each phrase in the query associated with FTS3 cursor
130135 ** pCsr. 
130136 **
130137 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
130138 ** phrases in the expression (all phrases except those directly or 
130139 ** indirectly descended from the right-hand-side of a NOT operator). If 
130140 ** pnToken is not NULL, then it is set to the number of tokens in all
130141 ** matchable phrases of the expression.
130142 */
130143 static int fts3ExprLoadDoclists(
130144   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
130145   int *pnPhrase,                  /* OUT: Number of phrases in query */
130146   int *pnToken                    /* OUT: Number of tokens in query */
130147 ){
130148   int rc;                         /* Return Code */
130149   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
130150   sCtx.pCsr = pCsr;
130151   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
130152   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
130153   if( pnToken ) *pnToken = sCtx.nToken;
130154   return rc;
130155 }
130156
130157 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
130158   (*(int *)ctx)++;
130159   UNUSED_PARAMETER(pExpr);
130160   UNUSED_PARAMETER(iPhrase);
130161   return SQLITE_OK;
130162 }
130163 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
130164   int nPhrase = 0;
130165   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
130166   return nPhrase;
130167 }
130168
130169 /*
130170 ** Advance the position list iterator specified by the first two 
130171 ** arguments so that it points to the first element with a value greater
130172 ** than or equal to parameter iNext.
130173 */
130174 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
130175   char *pIter = *ppIter;
130176   if( pIter ){
130177     int iIter = *piIter;
130178
130179     while( iIter<iNext ){
130180       if( 0==(*pIter & 0xFE) ){
130181         iIter = -1;
130182         pIter = 0;
130183         break;
130184       }
130185       fts3GetDeltaPosition(&pIter, &iIter);
130186     }
130187
130188     *piIter = iIter;
130189     *ppIter = pIter;
130190   }
130191 }
130192
130193 /*
130194 ** Advance the snippet iterator to the next candidate snippet.
130195 */
130196 static int fts3SnippetNextCandidate(SnippetIter *pIter){
130197   int i;                          /* Loop counter */
130198
130199   if( pIter->iCurrent<0 ){
130200     /* The SnippetIter object has just been initialized. The first snippet
130201     ** candidate always starts at offset 0 (even if this candidate has a
130202     ** score of 0.0).
130203     */
130204     pIter->iCurrent = 0;
130205
130206     /* Advance the 'head' iterator of each phrase to the first offset that
130207     ** is greater than or equal to (iNext+nSnippet).
130208     */
130209     for(i=0; i<pIter->nPhrase; i++){
130210       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
130211       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
130212     }
130213   }else{
130214     int iStart;
130215     int iEnd = 0x7FFFFFFF;
130216
130217     for(i=0; i<pIter->nPhrase; i++){
130218       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
130219       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
130220         iEnd = pPhrase->iHead;
130221       }
130222     }
130223     if( iEnd==0x7FFFFFFF ){
130224       return 1;
130225     }
130226
130227     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
130228     for(i=0; i<pIter->nPhrase; i++){
130229       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
130230       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
130231       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
130232     }
130233   }
130234
130235   return 0;
130236 }
130237
130238 /*
130239 ** Retrieve information about the current candidate snippet of snippet 
130240 ** iterator pIter.
130241 */
130242 static void fts3SnippetDetails(
130243   SnippetIter *pIter,             /* Snippet iterator */
130244   u64 mCovered,                   /* Bitmask of phrases already covered */
130245   int *piToken,                   /* OUT: First token of proposed snippet */
130246   int *piScore,                   /* OUT: "Score" for this snippet */
130247   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
130248   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
130249 ){
130250   int iStart = pIter->iCurrent;   /* First token of snippet */
130251   int iScore = 0;                 /* Score of this snippet */
130252   int i;                          /* Loop counter */
130253   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
130254   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
130255
130256   for(i=0; i<pIter->nPhrase; i++){
130257     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
130258     if( pPhrase->pTail ){
130259       char *pCsr = pPhrase->pTail;
130260       int iCsr = pPhrase->iTail;
130261
130262       while( iCsr<(iStart+pIter->nSnippet) ){
130263         int j;
130264         u64 mPhrase = (u64)1 << i;
130265         u64 mPos = (u64)1 << (iCsr - iStart);
130266         assert( iCsr>=iStart );
130267         if( (mCover|mCovered)&mPhrase ){
130268           iScore++;
130269         }else{
130270           iScore += 1000;
130271         }
130272         mCover |= mPhrase;
130273
130274         for(j=0; j<pPhrase->nToken; j++){
130275           mHighlight |= (mPos>>j);
130276         }
130277
130278         if( 0==(*pCsr & 0x0FE) ) break;
130279         fts3GetDeltaPosition(&pCsr, &iCsr);
130280       }
130281     }
130282   }
130283
130284   /* Set the output variables before returning. */
130285   *piToken = iStart;
130286   *piScore = iScore;
130287   *pmCover = mCover;
130288   *pmHighlight = mHighlight;
130289 }
130290
130291 /*
130292 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
130293 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
130294 */
130295 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
130296   SnippetIter *p = (SnippetIter *)ctx;
130297   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
130298   char *pCsr;
130299   int rc;
130300
130301   pPhrase->nToken = pExpr->pPhrase->nToken;
130302   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
130303   assert( rc==SQLITE_OK || pCsr==0 );
130304   if( pCsr ){
130305     int iFirst = 0;
130306     pPhrase->pList = pCsr;
130307     fts3GetDeltaPosition(&pCsr, &iFirst);
130308     assert( iFirst>=0 );
130309     pPhrase->pHead = pCsr;
130310     pPhrase->pTail = pCsr;
130311     pPhrase->iHead = iFirst;
130312     pPhrase->iTail = iFirst;
130313   }else{
130314     assert( rc!=SQLITE_OK || (
130315        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
130316     ));
130317   }
130318
130319   return rc;
130320 }
130321
130322 /*
130323 ** Select the fragment of text consisting of nFragment contiguous tokens 
130324 ** from column iCol that represent the "best" snippet. The best snippet
130325 ** is the snippet with the highest score, where scores are calculated
130326 ** by adding:
130327 **
130328 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
130329 **
130330 **   (b) +1000 points for the first occurence of each matchable phrase in 
130331 **       the snippet for which the corresponding mCovered bit is not set.
130332 **
130333 ** The selected snippet parameters are stored in structure *pFragment before
130334 ** returning. The score of the selected snippet is stored in *piScore
130335 ** before returning.
130336 */
130337 static int fts3BestSnippet(
130338   int nSnippet,                   /* Desired snippet length */
130339   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
130340   int iCol,                       /* Index of column to create snippet from */
130341   u64 mCovered,                   /* Mask of phrases already covered */
130342   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
130343   SnippetFragment *pFragment,     /* OUT: Best snippet found */
130344   int *piScore                    /* OUT: Score of snippet pFragment */
130345 ){
130346   int rc;                         /* Return Code */
130347   int nList;                      /* Number of phrases in expression */
130348   SnippetIter sIter;              /* Iterates through snippet candidates */
130349   int nByte;                      /* Number of bytes of space to allocate */
130350   int iBestScore = -1;            /* Best snippet score found so far */
130351   int i;                          /* Loop counter */
130352
130353   memset(&sIter, 0, sizeof(sIter));
130354
130355   /* Iterate through the phrases in the expression to count them. The same
130356   ** callback makes sure the doclists are loaded for each phrase.
130357   */
130358   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
130359   if( rc!=SQLITE_OK ){
130360     return rc;
130361   }
130362
130363   /* Now that it is known how many phrases there are, allocate and zero
130364   ** the required space using malloc().
130365   */
130366   nByte = sizeof(SnippetPhrase) * nList;
130367   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
130368   if( !sIter.aPhrase ){
130369     return SQLITE_NOMEM;
130370   }
130371   memset(sIter.aPhrase, 0, nByte);
130372
130373   /* Initialize the contents of the SnippetIter object. Then iterate through
130374   ** the set of phrases in the expression to populate the aPhrase[] array.
130375   */
130376   sIter.pCsr = pCsr;
130377   sIter.iCol = iCol;
130378   sIter.nSnippet = nSnippet;
130379   sIter.nPhrase = nList;
130380   sIter.iCurrent = -1;
130381   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
130382
130383   /* Set the *pmSeen output variable. */
130384   for(i=0; i<nList; i++){
130385     if( sIter.aPhrase[i].pHead ){
130386       *pmSeen |= (u64)1 << i;
130387     }
130388   }
130389
130390   /* Loop through all candidate snippets. Store the best snippet in 
130391   ** *pFragment. Store its associated 'score' in iBestScore.
130392   */
130393   pFragment->iCol = iCol;
130394   while( !fts3SnippetNextCandidate(&sIter) ){
130395     int iPos;
130396     int iScore;
130397     u64 mCover;
130398     u64 mHighlight;
130399     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
130400     assert( iScore>=0 );
130401     if( iScore>iBestScore ){
130402       pFragment->iPos = iPos;
130403       pFragment->hlmask = mHighlight;
130404       pFragment->covered = mCover;
130405       iBestScore = iScore;
130406     }
130407   }
130408
130409   sqlite3_free(sIter.aPhrase);
130410   *piScore = iBestScore;
130411   return SQLITE_OK;
130412 }
130413
130414
130415 /*
130416 ** Append a string to the string-buffer passed as the first argument.
130417 **
130418 ** If nAppend is negative, then the length of the string zAppend is
130419 ** determined using strlen().
130420 */
130421 static int fts3StringAppend(
130422   StrBuffer *pStr,                /* Buffer to append to */
130423   const char *zAppend,            /* Pointer to data to append to buffer */
130424   int nAppend                     /* Size of zAppend in bytes (or -1) */
130425 ){
130426   if( nAppend<0 ){
130427     nAppend = (int)strlen(zAppend);
130428   }
130429
130430   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
130431   ** to grow the buffer until so that it is big enough to accomadate the
130432   ** appended data.
130433   */
130434   if( pStr->n+nAppend+1>=pStr->nAlloc ){
130435     int nAlloc = pStr->nAlloc+nAppend+100;
130436     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
130437     if( !zNew ){
130438       return SQLITE_NOMEM;
130439     }
130440     pStr->z = zNew;
130441     pStr->nAlloc = nAlloc;
130442   }
130443
130444   /* Append the data to the string buffer. */
130445   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
130446   pStr->n += nAppend;
130447   pStr->z[pStr->n] = '\0';
130448
130449   return SQLITE_OK;
130450 }
130451
130452 /*
130453 ** The fts3BestSnippet() function often selects snippets that end with a
130454 ** query term. That is, the final term of the snippet is always a term
130455 ** that requires highlighting. For example, if 'X' is a highlighted term
130456 ** and '.' is a non-highlighted term, BestSnippet() may select:
130457 **
130458 **     ........X.....X
130459 **
130460 ** This function "shifts" the beginning of the snippet forward in the 
130461 ** document so that there are approximately the same number of 
130462 ** non-highlighted terms to the right of the final highlighted term as there
130463 ** are to the left of the first highlighted term. For example, to this:
130464 **
130465 **     ....X.....X....
130466 **
130467 ** This is done as part of extracting the snippet text, not when selecting
130468 ** the snippet. Snippet selection is done based on doclists only, so there
130469 ** is no way for fts3BestSnippet() to know whether or not the document 
130470 ** actually contains terms that follow the final highlighted term. 
130471 */
130472 static int fts3SnippetShift(
130473   Fts3Table *pTab,                /* FTS3 table snippet comes from */
130474   int iLangid,                    /* Language id to use in tokenizing */
130475   int nSnippet,                   /* Number of tokens desired for snippet */
130476   const char *zDoc,               /* Document text to extract snippet from */
130477   int nDoc,                       /* Size of buffer zDoc in bytes */
130478   int *piPos,                     /* IN/OUT: First token of snippet */
130479   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
130480 ){
130481   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
130482
130483   if( hlmask ){
130484     int nLeft;                    /* Tokens to the left of first highlight */
130485     int nRight;                   /* Tokens to the right of last highlight */
130486     int nDesired;                 /* Ideal number of tokens to shift forward */
130487
130488     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
130489     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
130490     nDesired = (nLeft-nRight)/2;
130491
130492     /* Ideally, the start of the snippet should be pushed forward in the
130493     ** document nDesired tokens. This block checks if there are actually
130494     ** nDesired tokens to the right of the snippet. If so, *piPos and
130495     ** *pHlMask are updated to shift the snippet nDesired tokens to the
130496     ** right. Otherwise, the snippet is shifted by the number of tokens
130497     ** available.
130498     */
130499     if( nDesired>0 ){
130500       int nShift;                 /* Number of tokens to shift snippet by */
130501       int iCurrent = 0;           /* Token counter */
130502       int rc;                     /* Return Code */
130503       sqlite3_tokenizer_module *pMod;
130504       sqlite3_tokenizer_cursor *pC;
130505       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
130506
130507       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
130508       ** or more tokens in zDoc/nDoc.
130509       */
130510       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
130511       if( rc!=SQLITE_OK ){
130512         return rc;
130513       }
130514       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
130515         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
130516         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
130517       }
130518       pMod->xClose(pC);
130519       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
130520
130521       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
130522       assert( nShift<=nDesired );
130523       if( nShift>0 ){
130524         *piPos += nShift;
130525         *pHlmask = hlmask >> nShift;
130526       }
130527     }
130528   }
130529   return SQLITE_OK;
130530 }
130531
130532 /*
130533 ** Extract the snippet text for fragment pFragment from cursor pCsr and
130534 ** append it to string buffer pOut.
130535 */
130536 static int fts3SnippetText(
130537   Fts3Cursor *pCsr,               /* FTS3 Cursor */
130538   SnippetFragment *pFragment,     /* Snippet to extract */
130539   int iFragment,                  /* Fragment number */
130540   int isLast,                     /* True for final fragment in snippet */
130541   int nSnippet,                   /* Number of tokens in extracted snippet */
130542   const char *zOpen,              /* String inserted before highlighted term */
130543   const char *zClose,             /* String inserted after highlighted term */
130544   const char *zEllipsis,          /* String inserted between snippets */
130545   StrBuffer *pOut                 /* Write output here */
130546 ){
130547   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130548   int rc;                         /* Return code */
130549   const char *zDoc;               /* Document text to extract snippet from */
130550   int nDoc;                       /* Size of zDoc in bytes */
130551   int iCurrent = 0;               /* Current token number of document */
130552   int iEnd = 0;                   /* Byte offset of end of current token */
130553   int isShiftDone = 0;            /* True after snippet is shifted */
130554   int iPos = pFragment->iPos;     /* First token of snippet */
130555   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
130556   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
130557   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
130558   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
130559   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
130560   int DUMMY1;                     /* Dummy argument used with tokenizer */
130561   
130562   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
130563   if( zDoc==0 ){
130564     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
130565       return SQLITE_NOMEM;
130566     }
130567     return SQLITE_OK;
130568   }
130569   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
130570
130571   /* Open a token cursor on the document. */
130572   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
130573   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
130574   if( rc!=SQLITE_OK ){
130575     return rc;
130576   }
130577
130578   while( rc==SQLITE_OK ){
130579     int iBegin;                   /* Offset in zDoc of start of token */
130580     int iFin;                     /* Offset in zDoc of end of token */
130581     int isHighlight;              /* True for highlighted terms */
130582
130583     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
130584     if( rc!=SQLITE_OK ){
130585       if( rc==SQLITE_DONE ){
130586         /* Special case - the last token of the snippet is also the last token
130587         ** of the column. Append any punctuation that occurred between the end
130588         ** of the previous token and the end of the document to the output. 
130589         ** Then break out of the loop. */
130590         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
130591       }
130592       break;
130593     }
130594     if( iCurrent<iPos ){ continue; }
130595
130596     if( !isShiftDone ){
130597       int n = nDoc - iBegin;
130598       rc = fts3SnippetShift(
130599           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
130600       );
130601       isShiftDone = 1;
130602
130603       /* Now that the shift has been done, check if the initial "..." are
130604       ** required. They are required if (a) this is not the first fragment,
130605       ** or (b) this fragment does not begin at position 0 of its column. 
130606       */
130607       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
130608         rc = fts3StringAppend(pOut, zEllipsis, -1);
130609       }
130610       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
130611     }
130612
130613     if( iCurrent>=(iPos+nSnippet) ){
130614       if( isLast ){
130615         rc = fts3StringAppend(pOut, zEllipsis, -1);
130616       }
130617       break;
130618     }
130619
130620     /* Set isHighlight to true if this term should be highlighted. */
130621     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
130622
130623     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
130624     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
130625     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
130626     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
130627
130628     iEnd = iFin;
130629   }
130630
130631   pMod->xClose(pC);
130632   return rc;
130633 }
130634
130635
130636 /*
130637 ** This function is used to count the entries in a column-list (a 
130638 ** delta-encoded list of term offsets within a single column of a single 
130639 ** row). When this function is called, *ppCollist should point to the
130640 ** beginning of the first varint in the column-list (the varint that
130641 ** contains the position of the first matching term in the column data).
130642 ** Before returning, *ppCollist is set to point to the first byte after
130643 ** the last varint in the column-list (either the 0x00 signifying the end
130644 ** of the position-list, or the 0x01 that precedes the column number of
130645 ** the next column in the position-list).
130646 **
130647 ** The number of elements in the column-list is returned.
130648 */
130649 static int fts3ColumnlistCount(char **ppCollist){
130650   char *pEnd = *ppCollist;
130651   char c = 0;
130652   int nEntry = 0;
130653
130654   /* A column-list is terminated by either a 0x01 or 0x00. */
130655   while( 0xFE & (*pEnd | c) ){
130656     c = *pEnd++ & 0x80;
130657     if( !c ) nEntry++;
130658   }
130659
130660   *ppCollist = pEnd;
130661   return nEntry;
130662 }
130663
130664 /*
130665 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
130666 ** for a single query. 
130667 **
130668 ** fts3ExprIterate() callback to load the 'global' elements of a
130669 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
130670 ** of the matchinfo array that are constant for all rows returned by the 
130671 ** current query.
130672 **
130673 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
130674 ** function populates Matchinfo.aMatchinfo[] as follows:
130675 **
130676 **   for(iCol=0; iCol<nCol; iCol++){
130677 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
130678 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
130679 **   }
130680 **
130681 ** where X is the number of matches for phrase iPhrase is column iCol of all
130682 ** rows of the table. Y is the number of rows for which column iCol contains
130683 ** at least one instance of phrase iPhrase.
130684 **
130685 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
130686 ** Y values are set to nDoc, where nDoc is the number of documents in the 
130687 ** file system. This is done because the full-text index doclist is required
130688 ** to calculate these values properly, and the full-text index doclist is
130689 ** not available for deferred tokens.
130690 */
130691 static int fts3ExprGlobalHitsCb(
130692   Fts3Expr *pExpr,                /* Phrase expression node */
130693   int iPhrase,                    /* Phrase number (numbered from zero) */
130694   void *pCtx                      /* Pointer to MatchInfo structure */
130695 ){
130696   MatchInfo *p = (MatchInfo *)pCtx;
130697   return sqlite3Fts3EvalPhraseStats(
130698       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
130699   );
130700 }
130701
130702 /*
130703 ** fts3ExprIterate() callback used to collect the "local" part of the
130704 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
130705 ** array that are different for each row returned by the query.
130706 */
130707 static int fts3ExprLocalHitsCb(
130708   Fts3Expr *pExpr,                /* Phrase expression node */
130709   int iPhrase,                    /* Phrase number */
130710   void *pCtx                      /* Pointer to MatchInfo structure */
130711 ){
130712   int rc = SQLITE_OK;
130713   MatchInfo *p = (MatchInfo *)pCtx;
130714   int iStart = iPhrase * p->nCol * 3;
130715   int i;
130716
130717   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
130718     char *pCsr;
130719     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
130720     if( pCsr ){
130721       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
130722     }else{
130723       p->aMatchinfo[iStart+i*3] = 0;
130724     }
130725   }
130726
130727   return rc;
130728 }
130729
130730 static int fts3MatchinfoCheck(
130731   Fts3Table *pTab, 
130732   char cArg,
130733   char **pzErr
130734 ){
130735   if( (cArg==FTS3_MATCHINFO_NPHRASE)
130736    || (cArg==FTS3_MATCHINFO_NCOL)
130737    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
130738    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
130739    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
130740    || (cArg==FTS3_MATCHINFO_LCS)
130741    || (cArg==FTS3_MATCHINFO_HITS)
130742   ){
130743     return SQLITE_OK;
130744   }
130745   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
130746   return SQLITE_ERROR;
130747 }
130748
130749 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
130750   int nVal;                       /* Number of integers output by cArg */
130751
130752   switch( cArg ){
130753     case FTS3_MATCHINFO_NDOC:
130754     case FTS3_MATCHINFO_NPHRASE: 
130755     case FTS3_MATCHINFO_NCOL: 
130756       nVal = 1;
130757       break;
130758
130759     case FTS3_MATCHINFO_AVGLENGTH:
130760     case FTS3_MATCHINFO_LENGTH:
130761     case FTS3_MATCHINFO_LCS:
130762       nVal = pInfo->nCol;
130763       break;
130764
130765     default:
130766       assert( cArg==FTS3_MATCHINFO_HITS );
130767       nVal = pInfo->nCol * pInfo->nPhrase * 3;
130768       break;
130769   }
130770
130771   return nVal;
130772 }
130773
130774 static int fts3MatchinfoSelectDoctotal(
130775   Fts3Table *pTab,
130776   sqlite3_stmt **ppStmt,
130777   sqlite3_int64 *pnDoc,
130778   const char **paLen
130779 ){
130780   sqlite3_stmt *pStmt;
130781   const char *a;
130782   sqlite3_int64 nDoc;
130783
130784   if( !*ppStmt ){
130785     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
130786     if( rc!=SQLITE_OK ) return rc;
130787   }
130788   pStmt = *ppStmt;
130789   assert( sqlite3_data_count(pStmt)==1 );
130790
130791   a = sqlite3_column_blob(pStmt, 0);
130792   a += sqlite3Fts3GetVarint(a, &nDoc);
130793   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
130794   *pnDoc = (u32)nDoc;
130795
130796   if( paLen ) *paLen = a;
130797   return SQLITE_OK;
130798 }
130799
130800 /*
130801 ** An instance of the following structure is used to store state while 
130802 ** iterating through a multi-column position-list corresponding to the
130803 ** hits for a single phrase on a single row in order to calculate the
130804 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
130805 */
130806 typedef struct LcsIterator LcsIterator;
130807 struct LcsIterator {
130808   Fts3Expr *pExpr;                /* Pointer to phrase expression */
130809   int iPosOffset;                 /* Tokens count up to end of this phrase */
130810   char *pRead;                    /* Cursor used to iterate through aDoclist */
130811   int iPos;                       /* Current position */
130812 };
130813
130814 /* 
130815 ** If LcsIterator.iCol is set to the following value, the iterator has
130816 ** finished iterating through all offsets for all columns.
130817 */
130818 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
130819
130820 static int fts3MatchinfoLcsCb(
130821   Fts3Expr *pExpr,                /* Phrase expression node */
130822   int iPhrase,                    /* Phrase number (numbered from zero) */
130823   void *pCtx                      /* Pointer to MatchInfo structure */
130824 ){
130825   LcsIterator *aIter = (LcsIterator *)pCtx;
130826   aIter[iPhrase].pExpr = pExpr;
130827   return SQLITE_OK;
130828 }
130829
130830 /*
130831 ** Advance the iterator passed as an argument to the next position. Return
130832 ** 1 if the iterator is at EOF or if it now points to the start of the
130833 ** position list for the next column.
130834 */
130835 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
130836   char *pRead = pIter->pRead;
130837   sqlite3_int64 iRead;
130838   int rc = 0;
130839
130840   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
130841   if( iRead==0 || iRead==1 ){
130842     pRead = 0;
130843     rc = 1;
130844   }else{
130845     pIter->iPos += (int)(iRead-2);
130846   }
130847
130848   pIter->pRead = pRead;
130849   return rc;
130850 }
130851   
130852 /*
130853 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
130854 **
130855 ** If the call is successful, the longest-common-substring lengths for each
130856 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
130857 ** array before returning. SQLITE_OK is returned in this case.
130858 **
130859 ** Otherwise, if an error occurs, an SQLite error code is returned and the
130860 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
130861 ** undefined.
130862 */
130863 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
130864   LcsIterator *aIter;
130865   int i;
130866   int iCol;
130867   int nToken = 0;
130868
130869   /* Allocate and populate the array of LcsIterator objects. The array
130870   ** contains one element for each matchable phrase in the query.
130871   **/
130872   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
130873   if( !aIter ) return SQLITE_NOMEM;
130874   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
130875   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
130876
130877   for(i=0; i<pInfo->nPhrase; i++){
130878     LcsIterator *pIter = &aIter[i];
130879     nToken -= pIter->pExpr->pPhrase->nToken;
130880     pIter->iPosOffset = nToken;
130881   }
130882
130883   for(iCol=0; iCol<pInfo->nCol; iCol++){
130884     int nLcs = 0;                 /* LCS value for this column */
130885     int nLive = 0;                /* Number of iterators in aIter not at EOF */
130886
130887     for(i=0; i<pInfo->nPhrase; i++){
130888       int rc;
130889       LcsIterator *pIt = &aIter[i];
130890       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
130891       if( rc!=SQLITE_OK ) return rc;
130892       if( pIt->pRead ){
130893         pIt->iPos = pIt->iPosOffset;
130894         fts3LcsIteratorAdvance(&aIter[i]);
130895         nLive++;
130896       }
130897     }
130898
130899     while( nLive>0 ){
130900       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
130901       int nThisLcs = 0;           /* LCS for the current iterator positions */
130902
130903       for(i=0; i<pInfo->nPhrase; i++){
130904         LcsIterator *pIter = &aIter[i];
130905         if( pIter->pRead==0 ){
130906           /* This iterator is already at EOF for this column. */
130907           nThisLcs = 0;
130908         }else{
130909           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
130910             pAdv = pIter;
130911           }
130912           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
130913             nThisLcs++;
130914           }else{
130915             nThisLcs = 1;
130916           }
130917           if( nThisLcs>nLcs ) nLcs = nThisLcs;
130918         }
130919       }
130920       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
130921     }
130922
130923     pInfo->aMatchinfo[iCol] = nLcs;
130924   }
130925
130926   sqlite3_free(aIter);
130927   return SQLITE_OK;
130928 }
130929
130930 /*
130931 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
130932 ** be returned by the matchinfo() function. Argument zArg contains the 
130933 ** format string passed as the second argument to matchinfo (or the
130934 ** default value "pcx" if no second argument was specified). The format
130935 ** string has already been validated and the pInfo->aMatchinfo[] array
130936 ** is guaranteed to be large enough for the output.
130937 **
130938 ** If bGlobal is true, then populate all fields of the matchinfo() output.
130939 ** If it is false, then assume that those fields that do not change between
130940 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
130941 ** have already been populated.
130942 **
130943 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
130944 ** occurs. If a value other than SQLITE_OK is returned, the state the
130945 ** pInfo->aMatchinfo[] buffer is left in is undefined.
130946 */
130947 static int fts3MatchinfoValues(
130948   Fts3Cursor *pCsr,               /* FTS3 cursor object */
130949   int bGlobal,                    /* True to grab the global stats */
130950   MatchInfo *pInfo,               /* Matchinfo context object */
130951   const char *zArg                /* Matchinfo format string */
130952 ){
130953   int rc = SQLITE_OK;
130954   int i;
130955   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130956   sqlite3_stmt *pSelect = 0;
130957
130958   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
130959
130960     switch( zArg[i] ){
130961       case FTS3_MATCHINFO_NPHRASE:
130962         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
130963         break;
130964
130965       case FTS3_MATCHINFO_NCOL:
130966         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
130967         break;
130968         
130969       case FTS3_MATCHINFO_NDOC:
130970         if( bGlobal ){
130971           sqlite3_int64 nDoc = 0;
130972           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
130973           pInfo->aMatchinfo[0] = (u32)nDoc;
130974         }
130975         break;
130976
130977       case FTS3_MATCHINFO_AVGLENGTH: 
130978         if( bGlobal ){
130979           sqlite3_int64 nDoc;     /* Number of rows in table */
130980           const char *a;          /* Aggregate column length array */
130981
130982           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
130983           if( rc==SQLITE_OK ){
130984             int iCol;
130985             for(iCol=0; iCol<pInfo->nCol; iCol++){
130986               u32 iVal;
130987               sqlite3_int64 nToken;
130988               a += sqlite3Fts3GetVarint(a, &nToken);
130989               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
130990               pInfo->aMatchinfo[iCol] = iVal;
130991             }
130992           }
130993         }
130994         break;
130995
130996       case FTS3_MATCHINFO_LENGTH: {
130997         sqlite3_stmt *pSelectDocsize = 0;
130998         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
130999         if( rc==SQLITE_OK ){
131000           int iCol;
131001           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
131002           for(iCol=0; iCol<pInfo->nCol; iCol++){
131003             sqlite3_int64 nToken;
131004             a += sqlite3Fts3GetVarint(a, &nToken);
131005             pInfo->aMatchinfo[iCol] = (u32)nToken;
131006           }
131007         }
131008         sqlite3_reset(pSelectDocsize);
131009         break;
131010       }
131011
131012       case FTS3_MATCHINFO_LCS:
131013         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
131014         if( rc==SQLITE_OK ){
131015           rc = fts3MatchinfoLcs(pCsr, pInfo);
131016         }
131017         break;
131018
131019       default: {
131020         Fts3Expr *pExpr;
131021         assert( zArg[i]==FTS3_MATCHINFO_HITS );
131022         pExpr = pCsr->pExpr;
131023         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
131024         if( rc!=SQLITE_OK ) break;
131025         if( bGlobal ){
131026           if( pCsr->pDeferred ){
131027             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
131028             if( rc!=SQLITE_OK ) break;
131029           }
131030           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
131031           if( rc!=SQLITE_OK ) break;
131032         }
131033         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
131034         break;
131035       }
131036     }
131037
131038     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
131039   }
131040
131041   sqlite3_reset(pSelect);
131042   return rc;
131043 }
131044
131045
131046 /*
131047 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
131048 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
131049 */
131050 static int fts3GetMatchinfo(
131051   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
131052   const char *zArg                /* Second argument to matchinfo() function */
131053 ){
131054   MatchInfo sInfo;
131055   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131056   int rc = SQLITE_OK;
131057   int bGlobal = 0;                /* Collect 'global' stats as well as local */
131058
131059   memset(&sInfo, 0, sizeof(MatchInfo));
131060   sInfo.pCursor = pCsr;
131061   sInfo.nCol = pTab->nColumn;
131062
131063   /* If there is cached matchinfo() data, but the format string for the 
131064   ** cache does not match the format string for this request, discard 
131065   ** the cached data. */
131066   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
131067     assert( pCsr->aMatchinfo );
131068     sqlite3_free(pCsr->aMatchinfo);
131069     pCsr->zMatchinfo = 0;
131070     pCsr->aMatchinfo = 0;
131071   }
131072
131073   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
131074   ** matchinfo function has been called for this query. In this case 
131075   ** allocate the array used to accumulate the matchinfo data and
131076   ** initialize those elements that are constant for every row.
131077   */
131078   if( pCsr->aMatchinfo==0 ){
131079     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
131080     int nArg;                     /* Bytes in zArg */
131081     int i;                        /* Used to iterate through zArg */
131082
131083     /* Determine the number of phrases in the query */
131084     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
131085     sInfo.nPhrase = pCsr->nPhrase;
131086
131087     /* Determine the number of integers in the buffer returned by this call. */
131088     for(i=0; zArg[i]; i++){
131089       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
131090     }
131091
131092     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
131093     nArg = (int)strlen(zArg);
131094     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
131095     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
131096
131097     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
131098     pCsr->nMatchinfo = nMatchinfo;
131099     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
131100     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
131101     pCsr->isMatchinfoNeeded = 1;
131102     bGlobal = 1;
131103   }
131104
131105   sInfo.aMatchinfo = pCsr->aMatchinfo;
131106   sInfo.nPhrase = pCsr->nPhrase;
131107   if( pCsr->isMatchinfoNeeded ){
131108     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
131109     pCsr->isMatchinfoNeeded = 0;
131110   }
131111
131112   return rc;
131113 }
131114
131115 /*
131116 ** Implementation of snippet() function.
131117 */
131118 SQLITE_PRIVATE void sqlite3Fts3Snippet(
131119   sqlite3_context *pCtx,          /* SQLite function call context */
131120   Fts3Cursor *pCsr,               /* Cursor object */
131121   const char *zStart,             /* Snippet start text - "<b>" */
131122   const char *zEnd,               /* Snippet end text - "</b>" */
131123   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
131124   int iCol,                       /* Extract snippet from this column */
131125   int nToken                      /* Approximate number of tokens in snippet */
131126 ){
131127   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131128   int rc = SQLITE_OK;
131129   int i;
131130   StrBuffer res = {0, 0, 0};
131131
131132   /* The returned text includes up to four fragments of text extracted from
131133   ** the data in the current row. The first iteration of the for(...) loop
131134   ** below attempts to locate a single fragment of text nToken tokens in 
131135   ** size that contains at least one instance of all phrases in the query
131136   ** expression that appear in the current row. If such a fragment of text
131137   ** cannot be found, the second iteration of the loop attempts to locate
131138   ** a pair of fragments, and so on.
131139   */
131140   int nSnippet = 0;               /* Number of fragments in this snippet */
131141   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
131142   int nFToken = -1;               /* Number of tokens in each fragment */
131143
131144   if( !pCsr->pExpr ){
131145     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
131146     return;
131147   }
131148
131149   for(nSnippet=1; 1; nSnippet++){
131150
131151     int iSnip;                    /* Loop counter 0..nSnippet-1 */
131152     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
131153     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
131154
131155     if( nToken>=0 ){
131156       nFToken = (nToken+nSnippet-1) / nSnippet;
131157     }else{
131158       nFToken = -1 * nToken;
131159     }
131160
131161     for(iSnip=0; iSnip<nSnippet; iSnip++){
131162       int iBestScore = -1;        /* Best score of columns checked so far */
131163       int iRead;                  /* Used to iterate through columns */
131164       SnippetFragment *pFragment = &aSnippet[iSnip];
131165
131166       memset(pFragment, 0, sizeof(*pFragment));
131167
131168       /* Loop through all columns of the table being considered for snippets.
131169       ** If the iCol argument to this function was negative, this means all
131170       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
131171       */
131172       for(iRead=0; iRead<pTab->nColumn; iRead++){
131173         SnippetFragment sF = {0, 0, 0, 0};
131174         int iS;
131175         if( iCol>=0 && iRead!=iCol ) continue;
131176
131177         /* Find the best snippet of nFToken tokens in column iRead. */
131178         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
131179         if( rc!=SQLITE_OK ){
131180           goto snippet_out;
131181         }
131182         if( iS>iBestScore ){
131183           *pFragment = sF;
131184           iBestScore = iS;
131185         }
131186       }
131187
131188       mCovered |= pFragment->covered;
131189     }
131190
131191     /* If all query phrases seen by fts3BestSnippet() are present in at least
131192     ** one of the nSnippet snippet fragments, break out of the loop.
131193     */
131194     assert( (mCovered&mSeen)==mCovered );
131195     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
131196   }
131197
131198   assert( nFToken>0 );
131199
131200   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
131201     rc = fts3SnippetText(pCsr, &aSnippet[i], 
131202         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
131203     );
131204   }
131205
131206  snippet_out:
131207   sqlite3Fts3SegmentsClose(pTab);
131208   if( rc!=SQLITE_OK ){
131209     sqlite3_result_error_code(pCtx, rc);
131210     sqlite3_free(res.z);
131211   }else{
131212     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
131213   }
131214 }
131215
131216
131217 typedef struct TermOffset TermOffset;
131218 typedef struct TermOffsetCtx TermOffsetCtx;
131219
131220 struct TermOffset {
131221   char *pList;                    /* Position-list */
131222   int iPos;                       /* Position just read from pList */
131223   int iOff;                       /* Offset of this term from read positions */
131224 };
131225
131226 struct TermOffsetCtx {
131227   Fts3Cursor *pCsr;
131228   int iCol;                       /* Column of table to populate aTerm for */
131229   int iTerm;
131230   sqlite3_int64 iDocid;
131231   TermOffset *aTerm;
131232 };
131233
131234 /*
131235 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
131236 */
131237 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
131238   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
131239   int nTerm;                      /* Number of tokens in phrase */
131240   int iTerm;                      /* For looping through nTerm phrase terms */
131241   char *pList;                    /* Pointer to position list for phrase */
131242   int iPos = 0;                   /* First position in position-list */
131243   int rc;
131244
131245   UNUSED_PARAMETER(iPhrase);
131246   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
131247   nTerm = pExpr->pPhrase->nToken;
131248   if( pList ){
131249     fts3GetDeltaPosition(&pList, &iPos);
131250     assert( iPos>=0 );
131251   }
131252
131253   for(iTerm=0; iTerm<nTerm; iTerm++){
131254     TermOffset *pT = &p->aTerm[p->iTerm++];
131255     pT->iOff = nTerm-iTerm-1;
131256     pT->pList = pList;
131257     pT->iPos = iPos;
131258   }
131259
131260   return rc;
131261 }
131262
131263 /*
131264 ** Implementation of offsets() function.
131265 */
131266 SQLITE_PRIVATE void sqlite3Fts3Offsets(
131267   sqlite3_context *pCtx,          /* SQLite function call context */
131268   Fts3Cursor *pCsr                /* Cursor object */
131269 ){
131270   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131271   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
131272   const char *ZDUMMY;             /* Dummy argument used with xNext() */
131273   int NDUMMY;                     /* Dummy argument used with xNext() */
131274   int rc;                         /* Return Code */
131275   int nToken;                     /* Number of tokens in query */
131276   int iCol;                       /* Column currently being processed */
131277   StrBuffer res = {0, 0, 0};      /* Result string */
131278   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
131279
131280   if( !pCsr->pExpr ){
131281     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
131282     return;
131283   }
131284
131285   memset(&sCtx, 0, sizeof(sCtx));
131286   assert( pCsr->isRequireSeek==0 );
131287
131288   /* Count the number of terms in the query */
131289   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
131290   if( rc!=SQLITE_OK ) goto offsets_out;
131291
131292   /* Allocate the array of TermOffset iterators. */
131293   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
131294   if( 0==sCtx.aTerm ){
131295     rc = SQLITE_NOMEM;
131296     goto offsets_out;
131297   }
131298   sCtx.iDocid = pCsr->iPrevId;
131299   sCtx.pCsr = pCsr;
131300
131301   /* Loop through the table columns, appending offset information to 
131302   ** string-buffer res for each column.
131303   */
131304   for(iCol=0; iCol<pTab->nColumn; iCol++){
131305     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
131306     int iStart;
131307     int iEnd;
131308     int iCurrent;
131309     const char *zDoc;
131310     int nDoc;
131311
131312     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
131313     ** no way that this operation can fail, so the return code from
131314     ** fts3ExprIterate() can be discarded.
131315     */
131316     sCtx.iCol = iCol;
131317     sCtx.iTerm = 0;
131318     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
131319
131320     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
131321     ** in column iCol, jump immediately to the next iteration of the loop.
131322     ** If an OOM occurs while retrieving the data (this can happen if SQLite
131323     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
131324     ** to the caller. 
131325     */
131326     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
131327     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
131328     if( zDoc==0 ){
131329       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
131330         continue;
131331       }
131332       rc = SQLITE_NOMEM;
131333       goto offsets_out;
131334     }
131335
131336     /* Initialize a tokenizer iterator to iterate through column iCol. */
131337     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
131338         zDoc, nDoc, &pC
131339     );
131340     if( rc!=SQLITE_OK ) goto offsets_out;
131341
131342     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
131343     while( rc==SQLITE_OK ){
131344       int i;                      /* Used to loop through terms */
131345       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
131346       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
131347
131348       for(i=0; i<nToken; i++){
131349         TermOffset *pT = &sCtx.aTerm[i];
131350         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
131351           iMinPos = pT->iPos-pT->iOff;
131352           pTerm = pT;
131353         }
131354       }
131355
131356       if( !pTerm ){
131357         /* All offsets for this column have been gathered. */
131358         rc = SQLITE_DONE;
131359       }else{
131360         assert( iCurrent<=iMinPos );
131361         if( 0==(0xFE&*pTerm->pList) ){
131362           pTerm->pList = 0;
131363         }else{
131364           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
131365         }
131366         while( rc==SQLITE_OK && iCurrent<iMinPos ){
131367           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
131368         }
131369         if( rc==SQLITE_OK ){
131370           char aBuffer[64];
131371           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
131372               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
131373           );
131374           rc = fts3StringAppend(&res, aBuffer, -1);
131375         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
131376           rc = FTS_CORRUPT_VTAB;
131377         }
131378       }
131379     }
131380     if( rc==SQLITE_DONE ){
131381       rc = SQLITE_OK;
131382     }
131383
131384     pMod->xClose(pC);
131385     if( rc!=SQLITE_OK ) goto offsets_out;
131386   }
131387
131388  offsets_out:
131389   sqlite3_free(sCtx.aTerm);
131390   assert( rc!=SQLITE_DONE );
131391   sqlite3Fts3SegmentsClose(pTab);
131392   if( rc!=SQLITE_OK ){
131393     sqlite3_result_error_code(pCtx,  rc);
131394     sqlite3_free(res.z);
131395   }else{
131396     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
131397   }
131398   return;
131399 }
131400
131401 /*
131402 ** Implementation of matchinfo() function.
131403 */
131404 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
131405   sqlite3_context *pContext,      /* Function call context */
131406   Fts3Cursor *pCsr,               /* FTS3 table cursor */
131407   const char *zArg                /* Second arg to matchinfo() function */
131408 ){
131409   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131410   int rc;
131411   int i;
131412   const char *zFormat;
131413
131414   if( zArg ){
131415     for(i=0; zArg[i]; i++){
131416       char *zErr = 0;
131417       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
131418         sqlite3_result_error(pContext, zErr, -1);
131419         sqlite3_free(zErr);
131420         return;
131421       }
131422     }
131423     zFormat = zArg;
131424   }else{
131425     zFormat = FTS3_MATCHINFO_DEFAULT;
131426   }
131427
131428   if( !pCsr->pExpr ){
131429     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
131430     return;
131431   }
131432
131433   /* Retrieve matchinfo() data. */
131434   rc = fts3GetMatchinfo(pCsr, zFormat);
131435   sqlite3Fts3SegmentsClose(pTab);
131436
131437   if( rc!=SQLITE_OK ){
131438     sqlite3_result_error_code(pContext, rc);
131439   }else{
131440     int n = pCsr->nMatchinfo * sizeof(u32);
131441     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
131442   }
131443 }
131444
131445 #endif
131446
131447 /************** End of fts3_snippet.c ****************************************/
131448 /************** Begin file fts3_unicode.c ************************************/
131449 /*
131450 ** 2012 May 24
131451 **
131452 ** The author disclaims copyright to this source code.  In place of
131453 ** a legal notice, here is a blessing:
131454 **
131455 **    May you do good and not evil.
131456 **    May you find forgiveness for yourself and forgive others.
131457 **    May you share freely, never taking more than you give.
131458 **
131459 ******************************************************************************
131460 **
131461 ** Implementation of the "unicode" full-text-search tokenizer.
131462 */
131463
131464 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
131465
131466 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131467
131468 /* #include <assert.h> */
131469 /* #include <stdlib.h> */
131470 /* #include <stdio.h> */
131471 /* #include <string.h> */
131472
131473
131474 /*
131475 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
131476 ** from the sqlite3 source file utf.c. If this file is compiled as part
131477 ** of the amalgamation, they are not required.
131478 */
131479 #ifndef SQLITE_AMALGAMATION
131480
131481 static const unsigned char sqlite3Utf8Trans1[] = {
131482   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
131483   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
131484   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
131485   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
131486   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
131487   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
131488   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
131489   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
131490 };
131491
131492 #define READ_UTF8(zIn, zTerm, c)                           \
131493   c = *(zIn++);                                            \
131494   if( c>=0xc0 ){                                           \
131495     c = sqlite3Utf8Trans1[c-0xc0];                         \
131496     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
131497       c = (c<<6) + (0x3f & *(zIn++));                      \
131498     }                                                      \
131499     if( c<0x80                                             \
131500         || (c&0xFFFFF800)==0xD800                          \
131501         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
131502   }
131503
131504 #define WRITE_UTF8(zOut, c) {                          \
131505   if( c<0x00080 ){                                     \
131506     *zOut++ = (u8)(c&0xFF);                            \
131507   }                                                    \
131508   else if( c<0x00800 ){                                \
131509     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
131510     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
131511   }                                                    \
131512   else if( c<0x10000 ){                                \
131513     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
131514     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
131515     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
131516   }else{                                               \
131517     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
131518     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
131519     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
131520     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
131521   }                                                    \
131522 }
131523
131524 #endif /* ifndef SQLITE_AMALGAMATION */
131525
131526 typedef struct unicode_tokenizer unicode_tokenizer;
131527 typedef struct unicode_cursor unicode_cursor;
131528
131529 struct unicode_tokenizer {
131530   sqlite3_tokenizer base;
131531   int bRemoveDiacritic;
131532   int nException;
131533   int *aiException;
131534 };
131535
131536 struct unicode_cursor {
131537   sqlite3_tokenizer_cursor base;
131538   const unsigned char *aInput;    /* Input text being tokenized */
131539   int nInput;                     /* Size of aInput[] in bytes */
131540   int iOff;                       /* Current offset within aInput[] */
131541   int iToken;                     /* Index of next token to be returned */
131542   char *zToken;                   /* storage for current token */
131543   int nAlloc;                     /* space allocated at zToken */
131544 };
131545
131546
131547 /*
131548 ** Destroy a tokenizer allocated by unicodeCreate().
131549 */
131550 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
131551   if( pTokenizer ){
131552     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
131553     sqlite3_free(p->aiException);
131554     sqlite3_free(p);
131555   }
131556   return SQLITE_OK;
131557 }
131558
131559 /*
131560 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
131561 ** statement has specified that the tokenizer for this table shall consider
131562 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
131563 ** token characters (if bAlnum==1).
131564 **
131565 ** For each codepoint in the zIn/nIn string, this function checks if the
131566 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
131567 ** If so, no action is taken. Otherwise, the codepoint is added to the 
131568 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
131569 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
131570 ** codepoints in the aiException[] array.
131571 **
131572 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
131573 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
131574 ** It is not possible to change the behaviour of the tokenizer with respect
131575 ** to these codepoints.
131576 */
131577 static int unicodeAddExceptions(
131578   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
131579   int bAlnum,                     /* Replace Isalnum() return value with this */
131580   const char *zIn,                /* Array of characters to make exceptions */
131581   int nIn                         /* Length of z in bytes */
131582 ){
131583   const unsigned char *z = (const unsigned char *)zIn;
131584   const unsigned char *zTerm = &z[nIn];
131585   int iCode;
131586   int nEntry = 0;
131587
131588   assert( bAlnum==0 || bAlnum==1 );
131589
131590   while( z<zTerm ){
131591     READ_UTF8(z, zTerm, iCode);
131592     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
131593     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
131594      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
131595     ){
131596       nEntry++;
131597     }
131598   }
131599
131600   if( nEntry ){
131601     int *aNew;                    /* New aiException[] array */
131602     int nNew;                     /* Number of valid entries in array aNew[] */
131603
131604     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
131605     if( aNew==0 ) return SQLITE_NOMEM;
131606     nNew = p->nException;
131607
131608     z = (const unsigned char *)zIn;
131609     while( z<zTerm ){
131610       READ_UTF8(z, zTerm, iCode);
131611       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
131612        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
131613       ){
131614         int i, j;
131615         for(i=0; i<nNew && aNew[i]<iCode; i++);
131616         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
131617         aNew[i] = iCode;
131618         nNew++;
131619       }
131620     }
131621     p->aiException = aNew;
131622     p->nException = nNew;
131623   }
131624
131625   return SQLITE_OK;
131626 }
131627
131628 /*
131629 ** Return true if the p->aiException[] array contains the value iCode.
131630 */
131631 static int unicodeIsException(unicode_tokenizer *p, int iCode){
131632   if( p->nException>0 ){
131633     int *a = p->aiException;
131634     int iLo = 0;
131635     int iHi = p->nException-1;
131636
131637     while( iHi>=iLo ){
131638       int iTest = (iHi + iLo) / 2;
131639       if( iCode==a[iTest] ){
131640         return 1;
131641       }else if( iCode>a[iTest] ){
131642         iLo = iTest+1;
131643       }else{
131644         iHi = iTest-1;
131645       }
131646     }
131647   }
131648
131649   return 0;
131650 }
131651
131652 /*
131653 ** Return true if, for the purposes of tokenization, codepoint iCode is
131654 ** considered a token character (not a separator).
131655 */
131656 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
131657   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
131658   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
131659 }
131660
131661 /*
131662 ** Create a new tokenizer instance.
131663 */
131664 static int unicodeCreate(
131665   int nArg,                       /* Size of array argv[] */
131666   const char * const *azArg,      /* Tokenizer creation arguments */
131667   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
131668 ){
131669   unicode_tokenizer *pNew;        /* New tokenizer object */
131670   int i;
131671   int rc = SQLITE_OK;
131672
131673   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
131674   if( pNew==NULL ) return SQLITE_NOMEM;
131675   memset(pNew, 0, sizeof(unicode_tokenizer));
131676   pNew->bRemoveDiacritic = 1;
131677
131678   for(i=0; rc==SQLITE_OK && i<nArg; i++){
131679     const char *z = azArg[i];
131680     int n = strlen(z);
131681
131682     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
131683       pNew->bRemoveDiacritic = 1;
131684     }
131685     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
131686       pNew->bRemoveDiacritic = 0;
131687     }
131688     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
131689       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
131690     }
131691     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
131692       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
131693     }
131694     else{
131695       /* Unrecognized argument */
131696       rc  = SQLITE_ERROR;
131697     }
131698   }
131699
131700   if( rc!=SQLITE_OK ){
131701     unicodeDestroy((sqlite3_tokenizer *)pNew);
131702     pNew = 0;
131703   }
131704   *pp = (sqlite3_tokenizer *)pNew;
131705   return rc;
131706 }
131707
131708 /*
131709 ** Prepare to begin tokenizing a particular string.  The input
131710 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
131711 ** used to incrementally tokenize this string is returned in 
131712 ** *ppCursor.
131713 */
131714 static int unicodeOpen(
131715   sqlite3_tokenizer *p,           /* The tokenizer */
131716   const char *aInput,             /* Input string */
131717   int nInput,                     /* Size of string aInput in bytes */
131718   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
131719 ){
131720   unicode_cursor *pCsr;
131721
131722   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
131723   if( pCsr==0 ){
131724     return SQLITE_NOMEM;
131725   }
131726   memset(pCsr, 0, sizeof(unicode_cursor));
131727
131728   pCsr->aInput = (const unsigned char *)aInput;
131729   if( aInput==0 ){
131730     pCsr->nInput = 0;
131731   }else if( nInput<0 ){
131732     pCsr->nInput = (int)strlen(aInput);
131733   }else{
131734     pCsr->nInput = nInput;
131735   }
131736
131737   *pp = &pCsr->base;
131738   UNUSED_PARAMETER(p);
131739   return SQLITE_OK;
131740 }
131741
131742 /*
131743 ** Close a tokenization cursor previously opened by a call to
131744 ** simpleOpen() above.
131745 */
131746 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
131747   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
131748   sqlite3_free(pCsr->zToken);
131749   sqlite3_free(pCsr);
131750   return SQLITE_OK;
131751 }
131752
131753 /*
131754 ** Extract the next token from a tokenization cursor.  The cursor must
131755 ** have been opened by a prior call to simpleOpen().
131756 */
131757 static int unicodeNext(
131758   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
131759   const char **paToken,           /* OUT: Token text */
131760   int *pnToken,                   /* OUT: Number of bytes at *paToken */
131761   int *piStart,                   /* OUT: Starting offset of token */
131762   int *piEnd,                     /* OUT: Ending offset of token */
131763   int *piPos                      /* OUT: Position integer of token */
131764 ){
131765   unicode_cursor *pCsr = (unicode_cursor *)pC;
131766   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
131767   int iCode;
131768   char *zOut;
131769   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
131770   const unsigned char *zStart = z;
131771   const unsigned char *zEnd;
131772   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
131773
131774   /* Scan past any delimiter characters before the start of the next token.
131775   ** Return SQLITE_DONE early if this takes us all the way to the end of 
131776   ** the input.  */
131777   while( z<zTerm ){
131778     READ_UTF8(z, zTerm, iCode);
131779     if( unicodeIsAlnum(p, iCode) ) break;
131780     zStart = z;
131781   }
131782   if( zStart>=zTerm ) return SQLITE_DONE;
131783
131784   zOut = pCsr->zToken;
131785   do {
131786     int iOut;
131787
131788     /* Grow the output buffer if required. */
131789     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
131790       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
131791       if( !zNew ) return SQLITE_NOMEM;
131792       zOut = &zNew[zOut - pCsr->zToken];
131793       pCsr->zToken = zNew;
131794       pCsr->nAlloc += 64;
131795     }
131796
131797     /* Write the folded case of the last character read to the output */
131798     zEnd = z;
131799     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
131800     if( iOut ){
131801       WRITE_UTF8(zOut, iOut);
131802     }
131803
131804     /* If the cursor is not at EOF, read the next character */
131805     if( z>=zTerm ) break;
131806     READ_UTF8(z, zTerm, iCode);
131807   }while( unicodeIsAlnum(p, iCode) 
131808        || sqlite3FtsUnicodeIsdiacritic(iCode)
131809   );
131810
131811   /* Set the output variables and return. */
131812   pCsr->iOff = (z - pCsr->aInput);
131813   *paToken = pCsr->zToken;
131814   *pnToken = zOut - pCsr->zToken;
131815   *piStart = (zStart - pCsr->aInput);
131816   *piEnd = (zEnd - pCsr->aInput);
131817   *piPos = pCsr->iToken++;
131818   return SQLITE_OK;
131819 }
131820
131821 /*
131822 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
131823 ** structure for the unicode tokenizer.
131824 */
131825 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
131826   static const sqlite3_tokenizer_module module = {
131827     0,
131828     unicodeCreate,
131829     unicodeDestroy,
131830     unicodeOpen,
131831     unicodeClose,
131832     unicodeNext,
131833     0,
131834   };
131835   *ppModule = &module;
131836 }
131837
131838 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
131839 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
131840
131841 /************** End of fts3_unicode.c ****************************************/
131842 /************** Begin file fts3_unicode2.c ***********************************/
131843 /*
131844 ** 2012 May 25
131845 **
131846 ** The author disclaims copyright to this source code.  In place of
131847 ** a legal notice, here is a blessing:
131848 **
131849 **    May you do good and not evil.
131850 **    May you find forgiveness for yourself and forgive others.
131851 **    May you share freely, never taking more than you give.
131852 **
131853 ******************************************************************************
131854 */
131855
131856 /*
131857 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
131858 */
131859
131860 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
131861 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
131862
131863 /* #include <assert.h> */
131864
131865 /*
131866 ** Return true if the argument corresponds to a unicode codepoint
131867 ** classified as either a letter or a number. Otherwise false.
131868 **
131869 ** The results are undefined if the value passed to this function
131870 ** is less than zero.
131871 */
131872 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
131873   /* Each unsigned integer in the following array corresponds to a contiguous
131874   ** range of unicode codepoints that are not either letters or numbers (i.e.
131875   ** codepoints for which this function should return 0).
131876   **
131877   ** The most significant 22 bits in each 32-bit value contain the first 
131878   ** codepoint in the range. The least significant 10 bits are used to store
131879   ** the size of the range (always at least 1). In other words, the value 
131880   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
131881   ** C. It is not possible to represent a range larger than 1023 codepoints 
131882   ** using this format.
131883   */
131884   const static unsigned int aEntry[] = {
131885     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
131886     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
131887     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
131888     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
131889     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
131890     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
131891     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
131892     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
131893     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
131894     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
131895     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
131896     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
131897     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
131898     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
131899     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
131900     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
131901     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
131902     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
131903     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
131904     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
131905     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
131906     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
131907     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
131908     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
131909     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
131910     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
131911     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
131912     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
131913     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
131914     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
131915     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
131916     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
131917     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
131918     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
131919     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
131920     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
131921     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
131922     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
131923     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
131924     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
131925     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
131926     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
131927     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
131928     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
131929     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
131930     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
131931     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
131932     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
131933     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
131934     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
131935     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
131936     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
131937     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
131938     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
131939     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
131940     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
131941     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
131942     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
131943     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
131944     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
131945     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
131946     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
131947     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
131948     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
131949     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
131950     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
131951     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
131952     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
131953     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
131954     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
131955     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
131956     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
131957     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
131958     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
131959     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
131960     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
131961     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
131962     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
131963     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
131964     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
131965     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
131966     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
131967     0x43FFF401,
131968   };
131969   static const unsigned int aAscii[4] = {
131970     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
131971   };
131972
131973   if( c<128 ){
131974     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
131975   }else if( c<(1<<22) ){
131976     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
131977     int iRes;
131978     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
131979     int iLo = 0;
131980     while( iHi>=iLo ){
131981       int iTest = (iHi + iLo) / 2;
131982       if( key >= aEntry[iTest] ){
131983         iRes = iTest;
131984         iLo = iTest+1;
131985       }else{
131986         iHi = iTest-1;
131987       }
131988     }
131989     assert( aEntry[0]<key );
131990     assert( key>=aEntry[iRes] );
131991     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
131992   }
131993   return 1;
131994 }
131995
131996
131997 /*
131998 ** If the argument is a codepoint corresponding to a lowercase letter
131999 ** in the ASCII range with a diacritic added, return the codepoint
132000 ** of the ASCII letter only. For example, if passed 235 - "LATIN
132001 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
132002 ** E"). The resuls of passing a codepoint that corresponds to an
132003 ** uppercase letter are undefined.
132004 */
132005 static int remove_diacritic(int c){
132006   unsigned short aDia[] = {
132007         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
132008      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
132009      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
132010      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
132011      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
132012      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
132013      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
132014      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
132015     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
132016     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
132017     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
132018     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
132019     62924, 63050, 63082, 63274, 63390, 
132020   };
132021   char aChar[] = {
132022     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
132023     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
132024     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
132025     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
132026     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
132027     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
132028     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
132029     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
132030     'e',  'i',  'o',  'u',  'y',  
132031   };
132032
132033   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
132034   int iRes = 0;
132035   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
132036   int iLo = 0;
132037   while( iHi>=iLo ){
132038     int iTest = (iHi + iLo) / 2;
132039     if( key >= aDia[iTest] ){
132040       iRes = iTest;
132041       iLo = iTest+1;
132042     }else{
132043       iHi = iTest-1;
132044     }
132045   }
132046   assert( key>=aDia[iRes] );
132047   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
132048 };
132049
132050
132051 /*
132052 ** Return true if the argument interpreted as a unicode codepoint
132053 ** is a diacritical modifier character.
132054 */
132055 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
132056   unsigned int mask0 = 0x08029FDF;
132057   unsigned int mask1 = 0x000361F8;
132058   if( c<768 || c>817 ) return 0;
132059   return (c < 768+32) ?
132060       (mask0 & (1 << (c-768))) :
132061       (mask1 & (1 << (c-768-32)));
132062 }
132063
132064
132065 /*
132066 ** Interpret the argument as a unicode codepoint. If the codepoint
132067 ** is an upper case character that has a lower case equivalent,
132068 ** return the codepoint corresponding to the lower case version.
132069 ** Otherwise, return a copy of the argument.
132070 **
132071 ** The results are undefined if the value passed to this function
132072 ** is less than zero.
132073 */
132074 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
132075   /* Each entry in the following array defines a rule for folding a range
132076   ** of codepoints to lower case. The rule applies to a range of nRange
132077   ** codepoints starting at codepoint iCode.
132078   **
132079   ** If the least significant bit in flags is clear, then the rule applies
132080   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
132081   ** need to be folded). Or, if it is set, then the rule only applies to
132082   ** every second codepoint in the range, starting with codepoint C.
132083   **
132084   ** The 7 most significant bits in flags are an index into the aiOff[]
132085   ** array. If a specific codepoint C does require folding, then its lower
132086   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
132087   **
132088   ** The contents of this array are generated by parsing the CaseFolding.txt
132089   ** file distributed as part of the "Unicode Character Database". See
132090   ** http://www.unicode.org for details.
132091   */
132092   static const struct TableEntry {
132093     unsigned short iCode;
132094     unsigned char flags;
132095     unsigned char nRange;
132096   } aEntry[] = {
132097     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
132098     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
132099     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
132100     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
132101     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
132102     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
132103     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
132104     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
132105     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
132106     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
132107     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
132108     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
132109     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
132110     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
132111     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
132112     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
132113     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
132114     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
132115     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
132116     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
132117     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
132118     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
132119     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
132120     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
132121     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
132122     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
132123     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
132124     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
132125     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
132126     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
132127     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
132128     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
132129     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
132130     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
132131     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
132132     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
132133     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
132134     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
132135     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
132136     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
132137     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
132138     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
132139     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
132140     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
132141     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
132142     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
132143     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
132144     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
132145     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
132146     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
132147     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
132148     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
132149     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
132150     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
132151     {65313, 14, 26},       
132152   };
132153   static const unsigned short aiOff[] = {
132154    1,     2,     8,     15,    16,    26,    28,    32,    
132155    37,    38,    40,    48,    63,    64,    69,    71,    
132156    79,    80,    116,   202,   203,   205,   206,   207,   
132157    209,   210,   211,   213,   214,   217,   218,   219,   
132158    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
132159    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
132160    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
132161    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
132162    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
132163    65514, 65521, 65527, 65528, 65529, 
132164   };
132165
132166   int ret = c;
132167
132168   assert( c>=0 );
132169   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
132170
132171   if( c<128 ){
132172     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
132173   }else if( c<65536 ){
132174     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
132175     int iLo = 0;
132176     int iRes = -1;
132177
132178     while( iHi>=iLo ){
132179       int iTest = (iHi + iLo) / 2;
132180       int cmp = (c - aEntry[iTest].iCode);
132181       if( cmp>=0 ){
132182         iRes = iTest;
132183         iLo = iTest+1;
132184       }else{
132185         iHi = iTest-1;
132186       }
132187     }
132188     assert( iRes<0 || c>=aEntry[iRes].iCode );
132189
132190     if( iRes>=0 ){
132191       const struct TableEntry *p = &aEntry[iRes];
132192       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
132193         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
132194         assert( ret>0 );
132195       }
132196     }
132197
132198     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
132199   }
132200   
132201   else if( c>=66560 && c<66600 ){
132202     ret = c + 40;
132203   }
132204
132205   return ret;
132206 }
132207 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
132208 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
132209
132210 /************** End of fts3_unicode2.c ***************************************/
132211 /************** Begin file rtree.c *******************************************/
132212 /*
132213 ** 2001 September 15
132214 **
132215 ** The author disclaims copyright to this source code.  In place of
132216 ** a legal notice, here is a blessing:
132217 **
132218 **    May you do good and not evil.
132219 **    May you find forgiveness for yourself and forgive others.
132220 **    May you share freely, never taking more than you give.
132221 **
132222 *************************************************************************
132223 ** This file contains code for implementations of the r-tree and r*-tree
132224 ** algorithms packaged as an SQLite virtual table module.
132225 */
132226
132227 /*
132228 ** Database Format of R-Tree Tables
132229 ** --------------------------------
132230 **
132231 ** The data structure for a single virtual r-tree table is stored in three 
132232 ** native SQLite tables declared as follows. In each case, the '%' character
132233 ** in the table name is replaced with the user-supplied name of the r-tree
132234 ** table.
132235 **
132236 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
132237 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
132238 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
132239 **
132240 ** The data for each node of the r-tree structure is stored in the %_node
132241 ** table. For each node that is not the root node of the r-tree, there is
132242 ** an entry in the %_parent table associating the node with its parent.
132243 ** And for each row of data in the table, there is an entry in the %_rowid
132244 ** table that maps from the entries rowid to the id of the node that it
132245 ** is stored on.
132246 **
132247 ** The root node of an r-tree always exists, even if the r-tree table is
132248 ** empty. The nodeno of the root node is always 1. All other nodes in the
132249 ** table must be the same size as the root node. The content of each node
132250 ** is formatted as follows:
132251 **
132252 **   1. If the node is the root node (node 1), then the first 2 bytes
132253 **      of the node contain the tree depth as a big-endian integer.
132254 **      For non-root nodes, the first 2 bytes are left unused.
132255 **
132256 **   2. The next 2 bytes contain the number of entries currently 
132257 **      stored in the node.
132258 **
132259 **   3. The remainder of the node contains the node entries. Each entry
132260 **      consists of a single 8-byte integer followed by an even number
132261 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
132262 **      of a record. For internal nodes it is the node number of a
132263 **      child page.
132264 */
132265
132266 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
132267
132268 /*
132269 ** This file contains an implementation of a couple of different variants
132270 ** of the r-tree algorithm. See the README file for further details. The 
132271 ** same data-structure is used for all, but the algorithms for insert and
132272 ** delete operations vary. The variants used are selected at compile time 
132273 ** by defining the following symbols:
132274 */
132275
132276 /* Either, both or none of the following may be set to activate 
132277 ** r*tree variant algorithms.
132278 */
132279 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
132280 #define VARIANT_RSTARTREE_REINSERT      1
132281
132282 /* 
132283 ** Exactly one of the following must be set to 1.
132284 */
132285 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
132286 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
132287 #define VARIANT_RSTARTREE_SPLIT         1
132288
132289 #define VARIANT_GUTTMAN_SPLIT \
132290         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
132291
132292 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
132293   #define PickNext QuadraticPickNext
132294   #define PickSeeds QuadraticPickSeeds
132295   #define AssignCells splitNodeGuttman
132296 #endif
132297 #if VARIANT_GUTTMAN_LINEAR_SPLIT
132298   #define PickNext LinearPickNext
132299   #define PickSeeds LinearPickSeeds
132300   #define AssignCells splitNodeGuttman
132301 #endif
132302 #if VARIANT_RSTARTREE_SPLIT
132303   #define AssignCells splitNodeStartree
132304 #endif
132305
132306 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
132307 # define NDEBUG 1
132308 #endif
132309
132310 #ifndef SQLITE_CORE
132311   SQLITE_EXTENSION_INIT1
132312 #else
132313 #endif
132314
132315 /* #include <string.h> */
132316 /* #include <assert.h> */
132317
132318 #ifndef SQLITE_AMALGAMATION
132319 #include "sqlite3rtree.h"
132320 typedef sqlite3_int64 i64;
132321 typedef unsigned char u8;
132322 typedef unsigned int u32;
132323 #endif
132324
132325 /*  The following macro is used to suppress compiler warnings.
132326 */
132327 #ifndef UNUSED_PARAMETER
132328 # define UNUSED_PARAMETER(x) (void)(x)
132329 #endif
132330
132331 typedef struct Rtree Rtree;
132332 typedef struct RtreeCursor RtreeCursor;
132333 typedef struct RtreeNode RtreeNode;
132334 typedef struct RtreeCell RtreeCell;
132335 typedef struct RtreeConstraint RtreeConstraint;
132336 typedef struct RtreeMatchArg RtreeMatchArg;
132337 typedef struct RtreeGeomCallback RtreeGeomCallback;
132338 typedef union RtreeCoord RtreeCoord;
132339
132340 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
132341 #define RTREE_MAX_DIMENSIONS 5
132342
132343 /* Size of hash table Rtree.aHash. This hash table is not expected to
132344 ** ever contain very many entries, so a fixed number of buckets is 
132345 ** used.
132346 */
132347 #define HASHSIZE 128
132348
132349 /* 
132350 ** An rtree virtual-table object.
132351 */
132352 struct Rtree {
132353   sqlite3_vtab base;
132354   sqlite3 *db;                /* Host database connection */
132355   int iNodeSize;              /* Size in bytes of each node in the node table */
132356   int nDim;                   /* Number of dimensions */
132357   int nBytesPerCell;          /* Bytes consumed per cell */
132358   int iDepth;                 /* Current depth of the r-tree structure */
132359   char *zDb;                  /* Name of database containing r-tree table */
132360   char *zName;                /* Name of r-tree table */ 
132361   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
132362   int nBusy;                  /* Current number of users of this structure */
132363
132364   /* List of nodes removed during a CondenseTree operation. List is
132365   ** linked together via the pointer normally used for hash chains -
132366   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
132367   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
132368   */
132369   RtreeNode *pDeleted;
132370   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
132371
132372   /* Statements to read/write/delete a record from xxx_node */
132373   sqlite3_stmt *pReadNode;
132374   sqlite3_stmt *pWriteNode;
132375   sqlite3_stmt *pDeleteNode;
132376
132377   /* Statements to read/write/delete a record from xxx_rowid */
132378   sqlite3_stmt *pReadRowid;
132379   sqlite3_stmt *pWriteRowid;
132380   sqlite3_stmt *pDeleteRowid;
132381
132382   /* Statements to read/write/delete a record from xxx_parent */
132383   sqlite3_stmt *pReadParent;
132384   sqlite3_stmt *pWriteParent;
132385   sqlite3_stmt *pDeleteParent;
132386
132387   int eCoordType;
132388 };
132389
132390 /* Possible values for eCoordType: */
132391 #define RTREE_COORD_REAL32 0
132392 #define RTREE_COORD_INT32  1
132393
132394 /*
132395 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
132396 ** only deal with integer coordinates.  No floating point operations
132397 ** will be done.
132398 */
132399 #ifdef SQLITE_RTREE_INT_ONLY
132400   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
132401   typedef int RtreeValue;                  /* Low accuracy coordinate */
132402 #else
132403   typedef double RtreeDValue;              /* High accuracy coordinate */
132404   typedef float RtreeValue;                /* Low accuracy coordinate */
132405 #endif
132406
132407 /*
132408 ** The minimum number of cells allowed for a node is a third of the 
132409 ** maximum. In Gutman's notation:
132410 **
132411 **     m = M/3
132412 **
132413 ** If an R*-tree "Reinsert" operation is required, the same number of
132414 ** cells are removed from the overfull node and reinserted into the tree.
132415 */
132416 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
132417 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
132418 #define RTREE_MAXCELLS 51
132419
132420 /*
132421 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
132422 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
132423 ** Therefore all non-root nodes must contain at least 3 entries. Since 
132424 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
132425 ** 40 or less.
132426 */
132427 #define RTREE_MAX_DEPTH 40
132428
132429 /* 
132430 ** An rtree cursor object.
132431 */
132432 struct RtreeCursor {
132433   sqlite3_vtab_cursor base;
132434   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
132435   int iCell;                        /* Index of current cell in pNode */
132436   int iStrategy;                    /* Copy of idxNum search parameter */
132437   int nConstraint;                  /* Number of entries in aConstraint */
132438   RtreeConstraint *aConstraint;     /* Search constraints. */
132439 };
132440
132441 union RtreeCoord {
132442   RtreeValue f;
132443   int i;
132444 };
132445
132446 /*
132447 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
132448 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
132449 ** variable pRtree points to the Rtree structure associated with the
132450 ** RtreeCoord.
132451 */
132452 #ifdef SQLITE_RTREE_INT_ONLY
132453 # define DCOORD(coord) ((RtreeDValue)coord.i)
132454 #else
132455 # define DCOORD(coord) (                           \
132456     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
132457       ((double)coord.f) :                           \
132458       ((double)coord.i)                             \
132459   )
132460 #endif
132461
132462 /*
132463 ** A search constraint.
132464 */
132465 struct RtreeConstraint {
132466   int iCoord;                     /* Index of constrained coordinate */
132467   int op;                         /* Constraining operation */
132468   RtreeDValue rValue;             /* Constraint value. */
132469   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
132470   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
132471 };
132472
132473 /* Possible values for RtreeConstraint.op */
132474 #define RTREE_EQ    0x41
132475 #define RTREE_LE    0x42
132476 #define RTREE_LT    0x43
132477 #define RTREE_GE    0x44
132478 #define RTREE_GT    0x45
132479 #define RTREE_MATCH 0x46
132480
132481 /* 
132482 ** An rtree structure node.
132483 */
132484 struct RtreeNode {
132485   RtreeNode *pParent;               /* Parent node */
132486   i64 iNode;
132487   int nRef;
132488   int isDirty;
132489   u8 *zData;
132490   RtreeNode *pNext;                 /* Next node in this hash chain */
132491 };
132492 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
132493
132494 /* 
132495 ** Structure to store a deserialized rtree record.
132496 */
132497 struct RtreeCell {
132498   i64 iRowid;
132499   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
132500 };
132501
132502
132503 /*
132504 ** Value for the first field of every RtreeMatchArg object. The MATCH
132505 ** operator tests that the first field of a blob operand matches this
132506 ** value to avoid operating on invalid blobs (which could cause a segfault).
132507 */
132508 #define RTREE_GEOMETRY_MAGIC 0x891245AB
132509
132510 /*
132511 ** An instance of this structure must be supplied as a blob argument to
132512 ** the right-hand-side of an SQL MATCH operator used to constrain an
132513 ** r-tree query.
132514 */
132515 struct RtreeMatchArg {
132516   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
132517   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
132518   void *pContext;
132519   int nParam;
132520   RtreeDValue aParam[1];
132521 };
132522
132523 /*
132524 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
132525 ** a single instance of the following structure is allocated. It is used
132526 ** as the context for the user-function created by by s_r_g_c(). The object
132527 ** is eventually deleted by the destructor mechanism provided by
132528 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
132529 ** the geometry callback function).
132530 */
132531 struct RtreeGeomCallback {
132532   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
132533   void *pContext;
132534 };
132535
132536 #ifndef MAX
132537 # define MAX(x,y) ((x) < (y) ? (y) : (x))
132538 #endif
132539 #ifndef MIN
132540 # define MIN(x,y) ((x) > (y) ? (y) : (x))
132541 #endif
132542
132543 /*
132544 ** Functions to deserialize a 16 bit integer, 32 bit real number and
132545 ** 64 bit integer. The deserialized value is returned.
132546 */
132547 static int readInt16(u8 *p){
132548   return (p[0]<<8) + p[1];
132549 }
132550 static void readCoord(u8 *p, RtreeCoord *pCoord){
132551   u32 i = (
132552     (((u32)p[0]) << 24) + 
132553     (((u32)p[1]) << 16) + 
132554     (((u32)p[2]) <<  8) + 
132555     (((u32)p[3]) <<  0)
132556   );
132557   *(u32 *)pCoord = i;
132558 }
132559 static i64 readInt64(u8 *p){
132560   return (
132561     (((i64)p[0]) << 56) + 
132562     (((i64)p[1]) << 48) + 
132563     (((i64)p[2]) << 40) + 
132564     (((i64)p[3]) << 32) + 
132565     (((i64)p[4]) << 24) + 
132566     (((i64)p[5]) << 16) + 
132567     (((i64)p[6]) <<  8) + 
132568     (((i64)p[7]) <<  0)
132569   );
132570 }
132571
132572 /*
132573 ** Functions to serialize a 16 bit integer, 32 bit real number and
132574 ** 64 bit integer. The value returned is the number of bytes written
132575 ** to the argument buffer (always 2, 4 and 8 respectively).
132576 */
132577 static int writeInt16(u8 *p, int i){
132578   p[0] = (i>> 8)&0xFF;
132579   p[1] = (i>> 0)&0xFF;
132580   return 2;
132581 }
132582 static int writeCoord(u8 *p, RtreeCoord *pCoord){
132583   u32 i;
132584   assert( sizeof(RtreeCoord)==4 );
132585   assert( sizeof(u32)==4 );
132586   i = *(u32 *)pCoord;
132587   p[0] = (i>>24)&0xFF;
132588   p[1] = (i>>16)&0xFF;
132589   p[2] = (i>> 8)&0xFF;
132590   p[3] = (i>> 0)&0xFF;
132591   return 4;
132592 }
132593 static int writeInt64(u8 *p, i64 i){
132594   p[0] = (i>>56)&0xFF;
132595   p[1] = (i>>48)&0xFF;
132596   p[2] = (i>>40)&0xFF;
132597   p[3] = (i>>32)&0xFF;
132598   p[4] = (i>>24)&0xFF;
132599   p[5] = (i>>16)&0xFF;
132600   p[6] = (i>> 8)&0xFF;
132601   p[7] = (i>> 0)&0xFF;
132602   return 8;
132603 }
132604
132605 /*
132606 ** Increment the reference count of node p.
132607 */
132608 static void nodeReference(RtreeNode *p){
132609   if( p ){
132610     p->nRef++;
132611   }
132612 }
132613
132614 /*
132615 ** Clear the content of node p (set all bytes to 0x00).
132616 */
132617 static void nodeZero(Rtree *pRtree, RtreeNode *p){
132618   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
132619   p->isDirty = 1;
132620 }
132621
132622 /*
132623 ** Given a node number iNode, return the corresponding key to use
132624 ** in the Rtree.aHash table.
132625 */
132626 static int nodeHash(i64 iNode){
132627   return (
132628     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
132629     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
132630   ) % HASHSIZE;
132631 }
132632
132633 /*
132634 ** Search the node hash table for node iNode. If found, return a pointer
132635 ** to it. Otherwise, return 0.
132636 */
132637 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
132638   RtreeNode *p;
132639   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
132640   return p;
132641 }
132642
132643 /*
132644 ** Add node pNode to the node hash table.
132645 */
132646 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
132647   int iHash;
132648   assert( pNode->pNext==0 );
132649   iHash = nodeHash(pNode->iNode);
132650   pNode->pNext = pRtree->aHash[iHash];
132651   pRtree->aHash[iHash] = pNode;
132652 }
132653
132654 /*
132655 ** Remove node pNode from the node hash table.
132656 */
132657 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
132658   RtreeNode **pp;
132659   if( pNode->iNode!=0 ){
132660     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
132661     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
132662     *pp = pNode->pNext;
132663     pNode->pNext = 0;
132664   }
132665 }
132666
132667 /*
132668 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
132669 ** indicating that node has not yet been assigned a node number. It is
132670 ** assigned a node number when nodeWrite() is called to write the
132671 ** node contents out to the database.
132672 */
132673 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
132674   RtreeNode *pNode;
132675   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
132676   if( pNode ){
132677     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
132678     pNode->zData = (u8 *)&pNode[1];
132679     pNode->nRef = 1;
132680     pNode->pParent = pParent;
132681     pNode->isDirty = 1;
132682     nodeReference(pParent);
132683   }
132684   return pNode;
132685 }
132686
132687 /*
132688 ** Obtain a reference to an r-tree node.
132689 */
132690 static int
132691 nodeAcquire(
132692   Rtree *pRtree,             /* R-tree structure */
132693   i64 iNode,                 /* Node number to load */
132694   RtreeNode *pParent,        /* Either the parent node or NULL */
132695   RtreeNode **ppNode         /* OUT: Acquired node */
132696 ){
132697   int rc;
132698   int rc2 = SQLITE_OK;
132699   RtreeNode *pNode;
132700
132701   /* Check if the requested node is already in the hash table. If so,
132702   ** increase its reference count and return it.
132703   */
132704   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
132705     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
132706     if( pParent && !pNode->pParent ){
132707       nodeReference(pParent);
132708       pNode->pParent = pParent;
132709     }
132710     pNode->nRef++;
132711     *ppNode = pNode;
132712     return SQLITE_OK;
132713   }
132714
132715   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
132716   rc = sqlite3_step(pRtree->pReadNode);
132717   if( rc==SQLITE_ROW ){
132718     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
132719     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
132720       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
132721       if( !pNode ){
132722         rc2 = SQLITE_NOMEM;
132723       }else{
132724         pNode->pParent = pParent;
132725         pNode->zData = (u8 *)&pNode[1];
132726         pNode->nRef = 1;
132727         pNode->iNode = iNode;
132728         pNode->isDirty = 0;
132729         pNode->pNext = 0;
132730         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
132731         nodeReference(pParent);
132732       }
132733     }
132734   }
132735   rc = sqlite3_reset(pRtree->pReadNode);
132736   if( rc==SQLITE_OK ) rc = rc2;
132737
132738   /* If the root node was just loaded, set pRtree->iDepth to the height
132739   ** of the r-tree structure. A height of zero means all data is stored on
132740   ** the root node. A height of one means the children of the root node
132741   ** are the leaves, and so on. If the depth as specified on the root node
132742   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
132743   */
132744   if( pNode && iNode==1 ){
132745     pRtree->iDepth = readInt16(pNode->zData);
132746     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
132747       rc = SQLITE_CORRUPT_VTAB;
132748     }
132749   }
132750
132751   /* If no error has occurred so far, check if the "number of entries"
132752   ** field on the node is too large. If so, set the return code to 
132753   ** SQLITE_CORRUPT_VTAB.
132754   */
132755   if( pNode && rc==SQLITE_OK ){
132756     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
132757       rc = SQLITE_CORRUPT_VTAB;
132758     }
132759   }
132760
132761   if( rc==SQLITE_OK ){
132762     if( pNode!=0 ){
132763       nodeHashInsert(pRtree, pNode);
132764     }else{
132765       rc = SQLITE_CORRUPT_VTAB;
132766     }
132767     *ppNode = pNode;
132768   }else{
132769     sqlite3_free(pNode);
132770     *ppNode = 0;
132771   }
132772
132773   return rc;
132774 }
132775
132776 /*
132777 ** Overwrite cell iCell of node pNode with the contents of pCell.
132778 */
132779 static void nodeOverwriteCell(
132780   Rtree *pRtree, 
132781   RtreeNode *pNode,  
132782   RtreeCell *pCell, 
132783   int iCell
132784 ){
132785   int ii;
132786   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
132787   p += writeInt64(p, pCell->iRowid);
132788   for(ii=0; ii<(pRtree->nDim*2); ii++){
132789     p += writeCoord(p, &pCell->aCoord[ii]);
132790   }
132791   pNode->isDirty = 1;
132792 }
132793
132794 /*
132795 ** Remove cell the cell with index iCell from node pNode.
132796 */
132797 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
132798   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
132799   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
132800   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
132801   memmove(pDst, pSrc, nByte);
132802   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
132803   pNode->isDirty = 1;
132804 }
132805
132806 /*
132807 ** Insert the contents of cell pCell into node pNode. If the insert
132808 ** is successful, return SQLITE_OK.
132809 **
132810 ** If there is not enough free space in pNode, return SQLITE_FULL.
132811 */
132812 static int
132813 nodeInsertCell(
132814   Rtree *pRtree, 
132815   RtreeNode *pNode, 
132816   RtreeCell *pCell 
132817 ){
132818   int nCell;                    /* Current number of cells in pNode */
132819   int nMaxCell;                 /* Maximum number of cells for pNode */
132820
132821   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
132822   nCell = NCELL(pNode);
132823
132824   assert( nCell<=nMaxCell );
132825   if( nCell<nMaxCell ){
132826     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
132827     writeInt16(&pNode->zData[2], nCell+1);
132828     pNode->isDirty = 1;
132829   }
132830
132831   return (nCell==nMaxCell);
132832 }
132833
132834 /*
132835 ** If the node is dirty, write it out to the database.
132836 */
132837 static int
132838 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
132839   int rc = SQLITE_OK;
132840   if( pNode->isDirty ){
132841     sqlite3_stmt *p = pRtree->pWriteNode;
132842     if( pNode->iNode ){
132843       sqlite3_bind_int64(p, 1, pNode->iNode);
132844     }else{
132845       sqlite3_bind_null(p, 1);
132846     }
132847     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
132848     sqlite3_step(p);
132849     pNode->isDirty = 0;
132850     rc = sqlite3_reset(p);
132851     if( pNode->iNode==0 && rc==SQLITE_OK ){
132852       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
132853       nodeHashInsert(pRtree, pNode);
132854     }
132855   }
132856   return rc;
132857 }
132858
132859 /*
132860 ** Release a reference to a node. If the node is dirty and the reference
132861 ** count drops to zero, the node data is written to the database.
132862 */
132863 static int
132864 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
132865   int rc = SQLITE_OK;
132866   if( pNode ){
132867     assert( pNode->nRef>0 );
132868     pNode->nRef--;
132869     if( pNode->nRef==0 ){
132870       if( pNode->iNode==1 ){
132871         pRtree->iDepth = -1;
132872       }
132873       if( pNode->pParent ){
132874         rc = nodeRelease(pRtree, pNode->pParent);
132875       }
132876       if( rc==SQLITE_OK ){
132877         rc = nodeWrite(pRtree, pNode);
132878       }
132879       nodeHashDelete(pRtree, pNode);
132880       sqlite3_free(pNode);
132881     }
132882   }
132883   return rc;
132884 }
132885
132886 /*
132887 ** Return the 64-bit integer value associated with cell iCell of
132888 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
132889 ** an internal node, then the 64-bit integer is a child page number.
132890 */
132891 static i64 nodeGetRowid(
132892   Rtree *pRtree, 
132893   RtreeNode *pNode, 
132894   int iCell
132895 ){
132896   assert( iCell<NCELL(pNode) );
132897   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
132898 }
132899
132900 /*
132901 ** Return coordinate iCoord from cell iCell in node pNode.
132902 */
132903 static void nodeGetCoord(
132904   Rtree *pRtree, 
132905   RtreeNode *pNode, 
132906   int iCell,
132907   int iCoord,
132908   RtreeCoord *pCoord           /* Space to write result to */
132909 ){
132910   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
132911 }
132912
132913 /*
132914 ** Deserialize cell iCell of node pNode. Populate the structure pointed
132915 ** to by pCell with the results.
132916 */
132917 static void nodeGetCell(
132918   Rtree *pRtree, 
132919   RtreeNode *pNode, 
132920   int iCell,
132921   RtreeCell *pCell
132922 ){
132923   int ii;
132924   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
132925   for(ii=0; ii<pRtree->nDim*2; ii++){
132926     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
132927   }
132928 }
132929
132930
132931 /* Forward declaration for the function that does the work of
132932 ** the virtual table module xCreate() and xConnect() methods.
132933 */
132934 static int rtreeInit(
132935   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
132936 );
132937
132938 /* 
132939 ** Rtree virtual table module xCreate method.
132940 */
132941 static int rtreeCreate(
132942   sqlite3 *db,
132943   void *pAux,
132944   int argc, const char *const*argv,
132945   sqlite3_vtab **ppVtab,
132946   char **pzErr
132947 ){
132948   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
132949 }
132950
132951 /* 
132952 ** Rtree virtual table module xConnect method.
132953 */
132954 static int rtreeConnect(
132955   sqlite3 *db,
132956   void *pAux,
132957   int argc, const char *const*argv,
132958   sqlite3_vtab **ppVtab,
132959   char **pzErr
132960 ){
132961   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
132962 }
132963
132964 /*
132965 ** Increment the r-tree reference count.
132966 */
132967 static void rtreeReference(Rtree *pRtree){
132968   pRtree->nBusy++;
132969 }
132970
132971 /*
132972 ** Decrement the r-tree reference count. When the reference count reaches
132973 ** zero the structure is deleted.
132974 */
132975 static void rtreeRelease(Rtree *pRtree){
132976   pRtree->nBusy--;
132977   if( pRtree->nBusy==0 ){
132978     sqlite3_finalize(pRtree->pReadNode);
132979     sqlite3_finalize(pRtree->pWriteNode);
132980     sqlite3_finalize(pRtree->pDeleteNode);
132981     sqlite3_finalize(pRtree->pReadRowid);
132982     sqlite3_finalize(pRtree->pWriteRowid);
132983     sqlite3_finalize(pRtree->pDeleteRowid);
132984     sqlite3_finalize(pRtree->pReadParent);
132985     sqlite3_finalize(pRtree->pWriteParent);
132986     sqlite3_finalize(pRtree->pDeleteParent);
132987     sqlite3_free(pRtree);
132988   }
132989 }
132990
132991 /* 
132992 ** Rtree virtual table module xDisconnect method.
132993 */
132994 static int rtreeDisconnect(sqlite3_vtab *pVtab){
132995   rtreeRelease((Rtree *)pVtab);
132996   return SQLITE_OK;
132997 }
132998
132999 /* 
133000 ** Rtree virtual table module xDestroy method.
133001 */
133002 static int rtreeDestroy(sqlite3_vtab *pVtab){
133003   Rtree *pRtree = (Rtree *)pVtab;
133004   int rc;
133005   char *zCreate = sqlite3_mprintf(
133006     "DROP TABLE '%q'.'%q_node';"
133007     "DROP TABLE '%q'.'%q_rowid';"
133008     "DROP TABLE '%q'.'%q_parent';",
133009     pRtree->zDb, pRtree->zName, 
133010     pRtree->zDb, pRtree->zName,
133011     pRtree->zDb, pRtree->zName
133012   );
133013   if( !zCreate ){
133014     rc = SQLITE_NOMEM;
133015   }else{
133016     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
133017     sqlite3_free(zCreate);
133018   }
133019   if( rc==SQLITE_OK ){
133020     rtreeRelease(pRtree);
133021   }
133022
133023   return rc;
133024 }
133025
133026 /* 
133027 ** Rtree virtual table module xOpen method.
133028 */
133029 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
133030   int rc = SQLITE_NOMEM;
133031   RtreeCursor *pCsr;
133032
133033   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
133034   if( pCsr ){
133035     memset(pCsr, 0, sizeof(RtreeCursor));
133036     pCsr->base.pVtab = pVTab;
133037     rc = SQLITE_OK;
133038   }
133039   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
133040
133041   return rc;
133042 }
133043
133044
133045 /*
133046 ** Free the RtreeCursor.aConstraint[] array and its contents.
133047 */
133048 static void freeCursorConstraints(RtreeCursor *pCsr){
133049   if( pCsr->aConstraint ){
133050     int i;                        /* Used to iterate through constraint array */
133051     for(i=0; i<pCsr->nConstraint; i++){
133052       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
133053       if( pGeom ){
133054         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
133055         sqlite3_free(pGeom);
133056       }
133057     }
133058     sqlite3_free(pCsr->aConstraint);
133059     pCsr->aConstraint = 0;
133060   }
133061 }
133062
133063 /* 
133064 ** Rtree virtual table module xClose method.
133065 */
133066 static int rtreeClose(sqlite3_vtab_cursor *cur){
133067   Rtree *pRtree = (Rtree *)(cur->pVtab);
133068   int rc;
133069   RtreeCursor *pCsr = (RtreeCursor *)cur;
133070   freeCursorConstraints(pCsr);
133071   rc = nodeRelease(pRtree, pCsr->pNode);
133072   sqlite3_free(pCsr);
133073   return rc;
133074 }
133075
133076 /*
133077 ** Rtree virtual table module xEof method.
133078 **
133079 ** Return non-zero if the cursor does not currently point to a valid 
133080 ** record (i.e if the scan has finished), or zero otherwise.
133081 */
133082 static int rtreeEof(sqlite3_vtab_cursor *cur){
133083   RtreeCursor *pCsr = (RtreeCursor *)cur;
133084   return (pCsr->pNode==0);
133085 }
133086
133087 /*
133088 ** The r-tree constraint passed as the second argument to this function is
133089 ** guaranteed to be a MATCH constraint.
133090 */
133091 static int testRtreeGeom(
133092   Rtree *pRtree,                  /* R-Tree object */
133093   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
133094   RtreeCell *pCell,               /* Cell to test */
133095   int *pbRes                      /* OUT: Test result */
133096 ){
133097   int i;
133098   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
133099   int nCoord = pRtree->nDim*2;
133100
133101   assert( pConstraint->op==RTREE_MATCH );
133102   assert( pConstraint->pGeom );
133103
133104   for(i=0; i<nCoord; i++){
133105     aCoord[i] = DCOORD(pCell->aCoord[i]);
133106   }
133107   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
133108 }
133109
133110 /* 
133111 ** Cursor pCursor currently points to a cell in a non-leaf page.
133112 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
133113 ** (excluded) by the constraints in the pCursor->aConstraint[] 
133114 ** array, or false otherwise.
133115 **
133116 ** Return SQLITE_OK if successful or an SQLite error code if an error
133117 ** occurs within a geometry callback.
133118 */
133119 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
133120   RtreeCell cell;
133121   int ii;
133122   int bRes = 0;
133123   int rc = SQLITE_OK;
133124
133125   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
133126   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
133127     RtreeConstraint *p = &pCursor->aConstraint[ii];
133128     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
133129     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
133130
133131     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
133132         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
133133     );
133134
133135     switch( p->op ){
133136       case RTREE_LE: case RTREE_LT: 
133137         bRes = p->rValue<cell_min; 
133138         break;
133139
133140       case RTREE_GE: case RTREE_GT: 
133141         bRes = p->rValue>cell_max; 
133142         break;
133143
133144       case RTREE_EQ:
133145         bRes = (p->rValue>cell_max || p->rValue<cell_min);
133146         break;
133147
133148       default: {
133149         assert( p->op==RTREE_MATCH );
133150         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
133151         bRes = !bRes;
133152         break;
133153       }
133154     }
133155   }
133156
133157   *pbEof = bRes;
133158   return rc;
133159 }
133160
133161 /* 
133162 ** Test if the cell that cursor pCursor currently points to
133163 ** would be filtered (excluded) by the constraints in the 
133164 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
133165 ** returning. If the cell is not filtered (excluded) by the constraints,
133166 ** set pbEof to zero.
133167 **
133168 ** Return SQLITE_OK if successful or an SQLite error code if an error
133169 ** occurs within a geometry callback.
133170 **
133171 ** This function assumes that the cell is part of a leaf node.
133172 */
133173 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
133174   RtreeCell cell;
133175   int ii;
133176   *pbEof = 0;
133177
133178   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
133179   for(ii=0; ii<pCursor->nConstraint; ii++){
133180     RtreeConstraint *p = &pCursor->aConstraint[ii];
133181     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
133182     int res;
133183     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
133184         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
133185     );
133186     switch( p->op ){
133187       case RTREE_LE: res = (coord<=p->rValue); break;
133188       case RTREE_LT: res = (coord<p->rValue);  break;
133189       case RTREE_GE: res = (coord>=p->rValue); break;
133190       case RTREE_GT: res = (coord>p->rValue);  break;
133191       case RTREE_EQ: res = (coord==p->rValue); break;
133192       default: {
133193         int rc;
133194         assert( p->op==RTREE_MATCH );
133195         rc = testRtreeGeom(pRtree, p, &cell, &res);
133196         if( rc!=SQLITE_OK ){
133197           return rc;
133198         }
133199         break;
133200       }
133201     }
133202
133203     if( !res ){
133204       *pbEof = 1;
133205       return SQLITE_OK;
133206     }
133207   }
133208
133209   return SQLITE_OK;
133210 }
133211
133212 /*
133213 ** Cursor pCursor currently points at a node that heads a sub-tree of
133214 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
133215 ** to point to the left-most cell of the sub-tree that matches the 
133216 ** configured constraints.
133217 */
133218 static int descendToCell(
133219   Rtree *pRtree, 
133220   RtreeCursor *pCursor, 
133221   int iHeight,
133222   int *pEof                 /* OUT: Set to true if cannot descend */
133223 ){
133224   int isEof;
133225   int rc;
133226   int ii;
133227   RtreeNode *pChild;
133228   sqlite3_int64 iRowid;
133229
133230   RtreeNode *pSavedNode = pCursor->pNode;
133231   int iSavedCell = pCursor->iCell;
133232
133233   assert( iHeight>=0 );
133234
133235   if( iHeight==0 ){
133236     rc = testRtreeEntry(pRtree, pCursor, &isEof);
133237   }else{
133238     rc = testRtreeCell(pRtree, pCursor, &isEof);
133239   }
133240   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
133241     goto descend_to_cell_out;
133242   }
133243
133244   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
133245   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
133246   if( rc!=SQLITE_OK ){
133247     goto descend_to_cell_out;
133248   }
133249
133250   nodeRelease(pRtree, pCursor->pNode);
133251   pCursor->pNode = pChild;
133252   isEof = 1;
133253   for(ii=0; isEof && ii<NCELL(pChild); ii++){
133254     pCursor->iCell = ii;
133255     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
133256     if( rc!=SQLITE_OK ){
133257       goto descend_to_cell_out;
133258     }
133259   }
133260
133261   if( isEof ){
133262     assert( pCursor->pNode==pChild );
133263     nodeReference(pSavedNode);
133264     nodeRelease(pRtree, pChild);
133265     pCursor->pNode = pSavedNode;
133266     pCursor->iCell = iSavedCell;
133267   }
133268
133269 descend_to_cell_out:
133270   *pEof = isEof;
133271   return rc;
133272 }
133273
133274 /*
133275 ** One of the cells in node pNode is guaranteed to have a 64-bit 
133276 ** integer value equal to iRowid. Return the index of this cell.
133277 */
133278 static int nodeRowidIndex(
133279   Rtree *pRtree, 
133280   RtreeNode *pNode, 
133281   i64 iRowid,
133282   int *piIndex
133283 ){
133284   int ii;
133285   int nCell = NCELL(pNode);
133286   for(ii=0; ii<nCell; ii++){
133287     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
133288       *piIndex = ii;
133289       return SQLITE_OK;
133290     }
133291   }
133292   return SQLITE_CORRUPT_VTAB;
133293 }
133294
133295 /*
133296 ** Return the index of the cell containing a pointer to node pNode
133297 ** in its parent. If pNode is the root node, return -1.
133298 */
133299 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
133300   RtreeNode *pParent = pNode->pParent;
133301   if( pParent ){
133302     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
133303   }
133304   *piIndex = -1;
133305   return SQLITE_OK;
133306 }
133307
133308 /* 
133309 ** Rtree virtual table module xNext method.
133310 */
133311 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
133312   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
133313   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
133314   int rc = SQLITE_OK;
133315
133316   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
133317   ** already at EOF. It is against the rules to call the xNext() method of
133318   ** a cursor that has already reached EOF.
133319   */
133320   assert( pCsr->pNode );
133321
133322   if( pCsr->iStrategy==1 ){
133323     /* This "scan" is a direct lookup by rowid. There is no next entry. */
133324     nodeRelease(pRtree, pCsr->pNode);
133325     pCsr->pNode = 0;
133326   }else{
133327     /* Move to the next entry that matches the configured constraints. */
133328     int iHeight = 0;
133329     while( pCsr->pNode ){
133330       RtreeNode *pNode = pCsr->pNode;
133331       int nCell = NCELL(pNode);
133332       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
133333         int isEof;
133334         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
133335         if( rc!=SQLITE_OK || !isEof ){
133336           return rc;
133337         }
133338       }
133339       pCsr->pNode = pNode->pParent;
133340       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
133341       if( rc!=SQLITE_OK ){
133342         return rc;
133343       }
133344       nodeReference(pCsr->pNode);
133345       nodeRelease(pRtree, pNode);
133346       iHeight++;
133347     }
133348   }
133349
133350   return rc;
133351 }
133352
133353 /* 
133354 ** Rtree virtual table module xRowid method.
133355 */
133356 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
133357   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
133358   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
133359
133360   assert(pCsr->pNode);
133361   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
133362
133363   return SQLITE_OK;
133364 }
133365
133366 /* 
133367 ** Rtree virtual table module xColumn method.
133368 */
133369 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
133370   Rtree *pRtree = (Rtree *)cur->pVtab;
133371   RtreeCursor *pCsr = (RtreeCursor *)cur;
133372
133373   if( i==0 ){
133374     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
133375     sqlite3_result_int64(ctx, iRowid);
133376   }else{
133377     RtreeCoord c;
133378     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
133379 #ifndef SQLITE_RTREE_INT_ONLY
133380     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
133381       sqlite3_result_double(ctx, c.f);
133382     }else
133383 #endif
133384     {
133385       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
133386       sqlite3_result_int(ctx, c.i);
133387     }
133388   }
133389
133390   return SQLITE_OK;
133391 }
133392
133393 /* 
133394 ** Use nodeAcquire() to obtain the leaf node containing the record with 
133395 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
133396 ** return SQLITE_OK. If there is no such record in the table, set
133397 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
133398 ** to zero and return an SQLite error code.
133399 */
133400 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
133401   int rc;
133402   *ppLeaf = 0;
133403   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
133404   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
133405     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
133406     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
133407     sqlite3_reset(pRtree->pReadRowid);
133408   }else{
133409     rc = sqlite3_reset(pRtree->pReadRowid);
133410   }
133411   return rc;
133412 }
133413
133414 /*
133415 ** This function is called to configure the RtreeConstraint object passed
133416 ** as the second argument for a MATCH constraint. The value passed as the
133417 ** first argument to this function is the right-hand operand to the MATCH
133418 ** operator.
133419 */
133420 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
133421   RtreeMatchArg *p;
133422   sqlite3_rtree_geometry *pGeom;
133423   int nBlob;
133424
133425   /* Check that value is actually a blob. */
133426   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
133427
133428   /* Check that the blob is roughly the right size. */
133429   nBlob = sqlite3_value_bytes(pValue);
133430   if( nBlob<(int)sizeof(RtreeMatchArg) 
133431    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
133432   ){
133433     return SQLITE_ERROR;
133434   }
133435
133436   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
133437       sizeof(sqlite3_rtree_geometry) + nBlob
133438   );
133439   if( !pGeom ) return SQLITE_NOMEM;
133440   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
133441   p = (RtreeMatchArg *)&pGeom[1];
133442
133443   memcpy(p, sqlite3_value_blob(pValue), nBlob);
133444   if( p->magic!=RTREE_GEOMETRY_MAGIC 
133445    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
133446   ){
133447     sqlite3_free(pGeom);
133448     return SQLITE_ERROR;
133449   }
133450
133451   pGeom->pContext = p->pContext;
133452   pGeom->nParam = p->nParam;
133453   pGeom->aParam = p->aParam;
133454
133455   pCons->xGeom = p->xGeom;
133456   pCons->pGeom = pGeom;
133457   return SQLITE_OK;
133458 }
133459
133460 /* 
133461 ** Rtree virtual table module xFilter method.
133462 */
133463 static int rtreeFilter(
133464   sqlite3_vtab_cursor *pVtabCursor, 
133465   int idxNum, const char *idxStr,
133466   int argc, sqlite3_value **argv
133467 ){
133468   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
133469   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
133470
133471   RtreeNode *pRoot = 0;
133472   int ii;
133473   int rc = SQLITE_OK;
133474
133475   rtreeReference(pRtree);
133476
133477   freeCursorConstraints(pCsr);
133478   pCsr->iStrategy = idxNum;
133479
133480   if( idxNum==1 ){
133481     /* Special case - lookup by rowid. */
133482     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
133483     i64 iRowid = sqlite3_value_int64(argv[0]);
133484     rc = findLeafNode(pRtree, iRowid, &pLeaf);
133485     pCsr->pNode = pLeaf; 
133486     if( pLeaf ){
133487       assert( rc==SQLITE_OK );
133488       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
133489     }
133490   }else{
133491     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
133492     ** with the configured constraints. 
133493     */
133494     if( argc>0 ){
133495       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
133496       pCsr->nConstraint = argc;
133497       if( !pCsr->aConstraint ){
133498         rc = SQLITE_NOMEM;
133499       }else{
133500         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
133501         assert( (idxStr==0 && argc==0)
133502                 || (idxStr && (int)strlen(idxStr)==argc*2) );
133503         for(ii=0; ii<argc; ii++){
133504           RtreeConstraint *p = &pCsr->aConstraint[ii];
133505           p->op = idxStr[ii*2];
133506           p->iCoord = idxStr[ii*2+1]-'a';
133507           if( p->op==RTREE_MATCH ){
133508             /* A MATCH operator. The right-hand-side must be a blob that
133509             ** can be cast into an RtreeMatchArg object. One created using
133510             ** an sqlite3_rtree_geometry_callback() SQL user function.
133511             */
133512             rc = deserializeGeometry(argv[ii], p);
133513             if( rc!=SQLITE_OK ){
133514               break;
133515             }
133516           }else{
133517 #ifdef SQLITE_RTREE_INT_ONLY
133518             p->rValue = sqlite3_value_int64(argv[ii]);
133519 #else
133520             p->rValue = sqlite3_value_double(argv[ii]);
133521 #endif
133522           }
133523         }
133524       }
133525     }
133526   
133527     if( rc==SQLITE_OK ){
133528       pCsr->pNode = 0;
133529       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
133530     }
133531     if( rc==SQLITE_OK ){
133532       int isEof = 1;
133533       int nCell = NCELL(pRoot);
133534       pCsr->pNode = pRoot;
133535       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
133536         assert( pCsr->pNode==pRoot );
133537         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
133538         if( !isEof ){
133539           break;
133540         }
133541       }
133542       if( rc==SQLITE_OK && isEof ){
133543         assert( pCsr->pNode==pRoot );
133544         nodeRelease(pRtree, pRoot);
133545         pCsr->pNode = 0;
133546       }
133547       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
133548     }
133549   }
133550
133551   rtreeRelease(pRtree);
133552   return rc;
133553 }
133554
133555 /*
133556 ** Rtree virtual table module xBestIndex method. There are three
133557 ** table scan strategies to choose from (in order from most to 
133558 ** least desirable):
133559 **
133560 **   idxNum     idxStr        Strategy
133561 **   ------------------------------------------------
133562 **     1        Unused        Direct lookup by rowid.
133563 **     2        See below     R-tree query or full-table scan.
133564 **   ------------------------------------------------
133565 **
133566 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
133567 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
133568 ** constraint used. The first two bytes of idxStr correspond to 
133569 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
133570 ** (argvIndex==1) etc.
133571 **
133572 ** The first of each pair of bytes in idxStr identifies the constraint
133573 ** operator as follows:
133574 **
133575 **   Operator    Byte Value
133576 **   ----------------------
133577 **      =        0x41 ('A')
133578 **     <=        0x42 ('B')
133579 **      <        0x43 ('C')
133580 **     >=        0x44 ('D')
133581 **      >        0x45 ('E')
133582 **   MATCH       0x46 ('F')
133583 **   ----------------------
133584 **
133585 ** The second of each pair of bytes identifies the coordinate column
133586 ** to which the constraint applies. The leftmost coordinate column
133587 ** is 'a', the second from the left 'b' etc.
133588 */
133589 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
133590   int rc = SQLITE_OK;
133591   int ii;
133592
133593   int iIdx = 0;
133594   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
133595   memset(zIdxStr, 0, sizeof(zIdxStr));
133596   UNUSED_PARAMETER(tab);
133597
133598   assert( pIdxInfo->idxStr==0 );
133599   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
133600     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
133601
133602     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
133603       /* We have an equality constraint on the rowid. Use strategy 1. */
133604       int jj;
133605       for(jj=0; jj<ii; jj++){
133606         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
133607         pIdxInfo->aConstraintUsage[jj].omit = 0;
133608       }
133609       pIdxInfo->idxNum = 1;
133610       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
133611       pIdxInfo->aConstraintUsage[jj].omit = 1;
133612
133613       /* This strategy involves a two rowid lookups on an B-Tree structures
133614       ** and then a linear search of an R-Tree node. This should be 
133615       ** considered almost as quick as a direct rowid lookup (for which 
133616       ** sqlite uses an internal cost of 0.0).
133617       */ 
133618       pIdxInfo->estimatedCost = 10.0;
133619       return SQLITE_OK;
133620     }
133621
133622     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
133623       u8 op;
133624       switch( p->op ){
133625         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
133626         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
133627         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
133628         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
133629         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
133630         default:
133631           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
133632           op = RTREE_MATCH; 
133633           break;
133634       }
133635       zIdxStr[iIdx++] = op;
133636       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
133637       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
133638       pIdxInfo->aConstraintUsage[ii].omit = 1;
133639     }
133640   }
133641
133642   pIdxInfo->idxNum = 2;
133643   pIdxInfo->needToFreeIdxStr = 1;
133644   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
133645     return SQLITE_NOMEM;
133646   }
133647   assert( iIdx>=0 );
133648   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
133649   return rc;
133650 }
133651
133652 /*
133653 ** Return the N-dimensional volumn of the cell stored in *p.
133654 */
133655 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
133656   RtreeDValue area = (RtreeDValue)1;
133657   int ii;
133658   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
133659     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
133660   }
133661   return area;
133662 }
133663
133664 /*
133665 ** Return the margin length of cell p. The margin length is the sum
133666 ** of the objects size in each dimension.
133667 */
133668 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
133669   RtreeDValue margin = (RtreeDValue)0;
133670   int ii;
133671   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
133672     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
133673   }
133674   return margin;
133675 }
133676
133677 /*
133678 ** Store the union of cells p1 and p2 in p1.
133679 */
133680 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
133681   int ii;
133682   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
133683     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
133684       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
133685       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
133686     }
133687   }else{
133688     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
133689       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
133690       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
133691     }
133692   }
133693 }
133694
133695 /*
133696 ** Return true if the area covered by p2 is a subset of the area covered
133697 ** by p1. False otherwise.
133698 */
133699 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
133700   int ii;
133701   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
133702   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
133703     RtreeCoord *a1 = &p1->aCoord[ii];
133704     RtreeCoord *a2 = &p2->aCoord[ii];
133705     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
133706      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
133707     ){
133708       return 0;
133709     }
133710   }
133711   return 1;
133712 }
133713
133714 /*
133715 ** Return the amount cell p would grow by if it were unioned with pCell.
133716 */
133717 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
133718   RtreeDValue area;
133719   RtreeCell cell;
133720   memcpy(&cell, p, sizeof(RtreeCell));
133721   area = cellArea(pRtree, &cell);
133722   cellUnion(pRtree, &cell, pCell);
133723   return (cellArea(pRtree, &cell)-area);
133724 }
133725
133726 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
133727 static RtreeDValue cellOverlap(
133728   Rtree *pRtree, 
133729   RtreeCell *p, 
133730   RtreeCell *aCell, 
133731   int nCell, 
133732   int iExclude
133733 ){
133734   int ii;
133735   RtreeDValue overlap = 0.0;
133736   for(ii=0; ii<nCell; ii++){
133737 #if VARIANT_RSTARTREE_CHOOSESUBTREE
133738     if( ii!=iExclude )
133739 #else
133740     assert( iExclude==-1 );
133741     UNUSED_PARAMETER(iExclude);
133742 #endif
133743     {
133744       int jj;
133745       RtreeDValue o = (RtreeDValue)1;
133746       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
133747         RtreeDValue x1, x2;
133748
133749         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
133750         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
133751
133752         if( x2<x1 ){
133753           o = 0.0;
133754           break;
133755         }else{
133756           o = o * (x2-x1);
133757         }
133758       }
133759       overlap += o;
133760     }
133761   }
133762   return overlap;
133763 }
133764 #endif
133765
133766 #if VARIANT_RSTARTREE_CHOOSESUBTREE
133767 static RtreeDValue cellOverlapEnlargement(
133768   Rtree *pRtree, 
133769   RtreeCell *p, 
133770   RtreeCell *pInsert, 
133771   RtreeCell *aCell, 
133772   int nCell, 
133773   int iExclude
133774 ){
133775   RtreeDValue before, after;
133776   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
133777   cellUnion(pRtree, p, pInsert);
133778   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
133779   return (after-before);
133780 }
133781 #endif
133782
133783
133784 /*
133785 ** This function implements the ChooseLeaf algorithm from Gutman[84].
133786 ** ChooseSubTree in r*tree terminology.
133787 */
133788 static int ChooseLeaf(
133789   Rtree *pRtree,               /* Rtree table */
133790   RtreeCell *pCell,            /* Cell to insert into rtree */
133791   int iHeight,                 /* Height of sub-tree rooted at pCell */
133792   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
133793 ){
133794   int rc;
133795   int ii;
133796   RtreeNode *pNode;
133797   rc = nodeAcquire(pRtree, 1, 0, &pNode);
133798
133799   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
133800     int iCell;
133801     sqlite3_int64 iBest = 0;
133802
133803     RtreeDValue fMinGrowth = 0.0;
133804     RtreeDValue fMinArea = 0.0;
133805 #if VARIANT_RSTARTREE_CHOOSESUBTREE
133806     RtreeDValue fMinOverlap = 0.0;
133807     RtreeDValue overlap;
133808 #endif
133809
133810     int nCell = NCELL(pNode);
133811     RtreeCell cell;
133812     RtreeNode *pChild;
133813
133814     RtreeCell *aCell = 0;
133815
133816 #if VARIANT_RSTARTREE_CHOOSESUBTREE
133817     if( ii==(pRtree->iDepth-1) ){
133818       int jj;
133819       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
133820       if( !aCell ){
133821         rc = SQLITE_NOMEM;
133822         nodeRelease(pRtree, pNode);
133823         pNode = 0;
133824         continue;
133825       }
133826       for(jj=0; jj<nCell; jj++){
133827         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
133828       }
133829     }
133830 #endif
133831
133832     /* Select the child node which will be enlarged the least if pCell
133833     ** is inserted into it. Resolve ties by choosing the entry with
133834     ** the smallest area.
133835     */
133836     for(iCell=0; iCell<nCell; iCell++){
133837       int bBest = 0;
133838       RtreeDValue growth;
133839       RtreeDValue area;
133840       nodeGetCell(pRtree, pNode, iCell, &cell);
133841       growth = cellGrowth(pRtree, &cell, pCell);
133842       area = cellArea(pRtree, &cell);
133843
133844 #if VARIANT_RSTARTREE_CHOOSESUBTREE
133845       if( ii==(pRtree->iDepth-1) ){
133846         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
133847       }else{
133848         overlap = 0.0;
133849       }
133850       if( (iCell==0) 
133851        || (overlap<fMinOverlap) 
133852        || (overlap==fMinOverlap && growth<fMinGrowth)
133853        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
133854       ){
133855         bBest = 1;
133856         fMinOverlap = overlap;
133857       }
133858 #else
133859       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
133860         bBest = 1;
133861       }
133862 #endif
133863       if( bBest ){
133864         fMinGrowth = growth;
133865         fMinArea = area;
133866         iBest = cell.iRowid;
133867       }
133868     }
133869
133870     sqlite3_free(aCell);
133871     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
133872     nodeRelease(pRtree, pNode);
133873     pNode = pChild;
133874   }
133875
133876   *ppLeaf = pNode;
133877   return rc;
133878 }
133879
133880 /*
133881 ** A cell with the same content as pCell has just been inserted into
133882 ** the node pNode. This function updates the bounding box cells in
133883 ** all ancestor elements.
133884 */
133885 static int AdjustTree(
133886   Rtree *pRtree,                    /* Rtree table */
133887   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
133888   RtreeCell *pCell                  /* This cell was just inserted */
133889 ){
133890   RtreeNode *p = pNode;
133891   while( p->pParent ){
133892     RtreeNode *pParent = p->pParent;
133893     RtreeCell cell;
133894     int iCell;
133895
133896     if( nodeParentIndex(pRtree, p, &iCell) ){
133897       return SQLITE_CORRUPT_VTAB;
133898     }
133899
133900     nodeGetCell(pRtree, pParent, iCell, &cell);
133901     if( !cellContains(pRtree, &cell, pCell) ){
133902       cellUnion(pRtree, &cell, pCell);
133903       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
133904     }
133905  
133906     p = pParent;
133907   }
133908   return SQLITE_OK;
133909 }
133910
133911 /*
133912 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
133913 */
133914 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
133915   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
133916   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
133917   sqlite3_step(pRtree->pWriteRowid);
133918   return sqlite3_reset(pRtree->pWriteRowid);
133919 }
133920
133921 /*
133922 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
133923 */
133924 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
133925   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
133926   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
133927   sqlite3_step(pRtree->pWriteParent);
133928   return sqlite3_reset(pRtree->pWriteParent);
133929 }
133930
133931 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
133932
133933 #if VARIANT_GUTTMAN_LINEAR_SPLIT
133934 /*
133935 ** Implementation of the linear variant of the PickNext() function from
133936 ** Guttman[84].
133937 */
133938 static RtreeCell *LinearPickNext(
133939   Rtree *pRtree,
133940   RtreeCell *aCell, 
133941   int nCell, 
133942   RtreeCell *pLeftBox, 
133943   RtreeCell *pRightBox,
133944   int *aiUsed
133945 ){
133946   int ii;
133947   for(ii=0; aiUsed[ii]; ii++);
133948   aiUsed[ii] = 1;
133949   return &aCell[ii];
133950 }
133951
133952 /*
133953 ** Implementation of the linear variant of the PickSeeds() function from
133954 ** Guttman[84].
133955 */
133956 static void LinearPickSeeds(
133957   Rtree *pRtree,
133958   RtreeCell *aCell, 
133959   int nCell, 
133960   int *piLeftSeed, 
133961   int *piRightSeed
133962 ){
133963   int i;
133964   int iLeftSeed = 0;
133965   int iRightSeed = 1;
133966   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
133967
133968   /* Pick two "seed" cells from the array of cells. The algorithm used
133969   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
133970   ** indices of the two seed cells in the array are stored in local
133971   ** variables iLeftSeek and iRightSeed.
133972   */
133973   for(i=0; i<pRtree->nDim; i++){
133974     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
133975     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
133976     RtreeDValue x3 = x1;
133977     RtreeDValue x4 = x2;
133978     int jj;
133979
133980     int iCellLeft = 0;
133981     int iCellRight = 0;
133982
133983     for(jj=1; jj<nCell; jj++){
133984       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
133985       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
133986
133987       if( left<x1 ) x1 = left;
133988       if( right>x4 ) x4 = right;
133989       if( left>x3 ){
133990         x3 = left;
133991         iCellRight = jj;
133992       }
133993       if( right<x2 ){
133994         x2 = right;
133995         iCellLeft = jj;
133996       }
133997     }
133998
133999     if( x4!=x1 ){
134000       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
134001       if( normalwidth>maxNormalInnerWidth ){
134002         iLeftSeed = iCellLeft;
134003         iRightSeed = iCellRight;
134004       }
134005     }
134006   }
134007
134008   *piLeftSeed = iLeftSeed;
134009   *piRightSeed = iRightSeed;
134010 }
134011 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
134012
134013 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
134014 /*
134015 ** Implementation of the quadratic variant of the PickNext() function from
134016 ** Guttman[84].
134017 */
134018 static RtreeCell *QuadraticPickNext(
134019   Rtree *pRtree,
134020   RtreeCell *aCell, 
134021   int nCell, 
134022   RtreeCell *pLeftBox, 
134023   RtreeCell *pRightBox,
134024   int *aiUsed
134025 ){
134026   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
134027
134028   int iSelect = -1;
134029   RtreeDValue fDiff;
134030   int ii;
134031   for(ii=0; ii<nCell; ii++){
134032     if( aiUsed[ii]==0 ){
134033       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
134034       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
134035       RtreeDValue diff = FABS(right-left);
134036       if( iSelect<0 || diff>fDiff ){
134037         fDiff = diff;
134038         iSelect = ii;
134039       }
134040     }
134041   }
134042   aiUsed[iSelect] = 1;
134043   return &aCell[iSelect];
134044 }
134045
134046 /*
134047 ** Implementation of the quadratic variant of the PickSeeds() function from
134048 ** Guttman[84].
134049 */
134050 static void QuadraticPickSeeds(
134051   Rtree *pRtree,
134052   RtreeCell *aCell, 
134053   int nCell, 
134054   int *piLeftSeed, 
134055   int *piRightSeed
134056 ){
134057   int ii;
134058   int jj;
134059
134060   int iLeftSeed = 0;
134061   int iRightSeed = 1;
134062   RtreeDValue fWaste = 0.0;
134063
134064   for(ii=0; ii<nCell; ii++){
134065     for(jj=ii+1; jj<nCell; jj++){
134066       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
134067       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
134068       RtreeDValue waste = growth - right;
134069
134070       if( waste>fWaste ){
134071         iLeftSeed = ii;
134072         iRightSeed = jj;
134073         fWaste = waste;
134074       }
134075     }
134076   }
134077
134078   *piLeftSeed = iLeftSeed;
134079   *piRightSeed = iRightSeed;
134080 }
134081 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
134082
134083 /*
134084 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
134085 ** nIdx. The aIdx array contains the set of integers from 0 to 
134086 ** (nIdx-1) in no particular order. This function sorts the values
134087 ** in aIdx according to the indexed values in aDistance. For
134088 ** example, assuming the inputs:
134089 **
134090 **   aIdx      = { 0,   1,   2,   3 }
134091 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
134092 **
134093 ** this function sets the aIdx array to contain:
134094 **
134095 **   aIdx      = { 0,   1,   2,   3 }
134096 **
134097 ** The aSpare array is used as temporary working space by the
134098 ** sorting algorithm.
134099 */
134100 static void SortByDistance(
134101   int *aIdx, 
134102   int nIdx, 
134103   RtreeDValue *aDistance, 
134104   int *aSpare
134105 ){
134106   if( nIdx>1 ){
134107     int iLeft = 0;
134108     int iRight = 0;
134109
134110     int nLeft = nIdx/2;
134111     int nRight = nIdx-nLeft;
134112     int *aLeft = aIdx;
134113     int *aRight = &aIdx[nLeft];
134114
134115     SortByDistance(aLeft, nLeft, aDistance, aSpare);
134116     SortByDistance(aRight, nRight, aDistance, aSpare);
134117
134118     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
134119     aLeft = aSpare;
134120
134121     while( iLeft<nLeft || iRight<nRight ){
134122       if( iLeft==nLeft ){
134123         aIdx[iLeft+iRight] = aRight[iRight];
134124         iRight++;
134125       }else if( iRight==nRight ){
134126         aIdx[iLeft+iRight] = aLeft[iLeft];
134127         iLeft++;
134128       }else{
134129         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
134130         RtreeDValue fRight = aDistance[aRight[iRight]];
134131         if( fLeft<fRight ){
134132           aIdx[iLeft+iRight] = aLeft[iLeft];
134133           iLeft++;
134134         }else{
134135           aIdx[iLeft+iRight] = aRight[iRight];
134136           iRight++;
134137         }
134138       }
134139     }
134140
134141 #if 0
134142     /* Check that the sort worked */
134143     {
134144       int jj;
134145       for(jj=1; jj<nIdx; jj++){
134146         RtreeDValue left = aDistance[aIdx[jj-1]];
134147         RtreeDValue right = aDistance[aIdx[jj]];
134148         assert( left<=right );
134149       }
134150     }
134151 #endif
134152   }
134153 }
134154
134155 /*
134156 ** Arguments aIdx, aCell and aSpare all point to arrays of size
134157 ** nIdx. The aIdx array contains the set of integers from 0 to 
134158 ** (nIdx-1) in no particular order. This function sorts the values
134159 ** in aIdx according to dimension iDim of the cells in aCell. The
134160 ** minimum value of dimension iDim is considered first, the
134161 ** maximum used to break ties.
134162 **
134163 ** The aSpare array is used as temporary working space by the
134164 ** sorting algorithm.
134165 */
134166 static void SortByDimension(
134167   Rtree *pRtree,
134168   int *aIdx, 
134169   int nIdx, 
134170   int iDim, 
134171   RtreeCell *aCell, 
134172   int *aSpare
134173 ){
134174   if( nIdx>1 ){
134175
134176     int iLeft = 0;
134177     int iRight = 0;
134178
134179     int nLeft = nIdx/2;
134180     int nRight = nIdx-nLeft;
134181     int *aLeft = aIdx;
134182     int *aRight = &aIdx[nLeft];
134183
134184     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
134185     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
134186
134187     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
134188     aLeft = aSpare;
134189     while( iLeft<nLeft || iRight<nRight ){
134190       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
134191       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
134192       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
134193       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
134194       if( (iLeft!=nLeft) && ((iRight==nRight)
134195        || (xleft1<xright1)
134196        || (xleft1==xright1 && xleft2<xright2)
134197       )){
134198         aIdx[iLeft+iRight] = aLeft[iLeft];
134199         iLeft++;
134200       }else{
134201         aIdx[iLeft+iRight] = aRight[iRight];
134202         iRight++;
134203       }
134204     }
134205
134206 #if 0
134207     /* Check that the sort worked */
134208     {
134209       int jj;
134210       for(jj=1; jj<nIdx; jj++){
134211         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
134212         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
134213         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
134214         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
134215         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
134216       }
134217     }
134218 #endif
134219   }
134220 }
134221
134222 #if VARIANT_RSTARTREE_SPLIT
134223 /*
134224 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
134225 */
134226 static int splitNodeStartree(
134227   Rtree *pRtree,
134228   RtreeCell *aCell,
134229   int nCell,
134230   RtreeNode *pLeft,
134231   RtreeNode *pRight,
134232   RtreeCell *pBboxLeft,
134233   RtreeCell *pBboxRight
134234 ){
134235   int **aaSorted;
134236   int *aSpare;
134237   int ii;
134238
134239   int iBestDim = 0;
134240   int iBestSplit = 0;
134241   RtreeDValue fBestMargin = 0.0;
134242
134243   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
134244
134245   aaSorted = (int **)sqlite3_malloc(nByte);
134246   if( !aaSorted ){
134247     return SQLITE_NOMEM;
134248   }
134249
134250   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
134251   memset(aaSorted, 0, nByte);
134252   for(ii=0; ii<pRtree->nDim; ii++){
134253     int jj;
134254     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
134255     for(jj=0; jj<nCell; jj++){
134256       aaSorted[ii][jj] = jj;
134257     }
134258     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
134259   }
134260
134261   for(ii=0; ii<pRtree->nDim; ii++){
134262     RtreeDValue margin = 0.0;
134263     RtreeDValue fBestOverlap = 0.0;
134264     RtreeDValue fBestArea = 0.0;
134265     int iBestLeft = 0;
134266     int nLeft;
134267
134268     for(
134269       nLeft=RTREE_MINCELLS(pRtree); 
134270       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
134271       nLeft++
134272     ){
134273       RtreeCell left;
134274       RtreeCell right;
134275       int kk;
134276       RtreeDValue overlap;
134277       RtreeDValue area;
134278
134279       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
134280       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
134281       for(kk=1; kk<(nCell-1); kk++){
134282         if( kk<nLeft ){
134283           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
134284         }else{
134285           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
134286         }
134287       }
134288       margin += cellMargin(pRtree, &left);
134289       margin += cellMargin(pRtree, &right);
134290       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
134291       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
134292       if( (nLeft==RTREE_MINCELLS(pRtree))
134293        || (overlap<fBestOverlap)
134294        || (overlap==fBestOverlap && area<fBestArea)
134295       ){
134296         iBestLeft = nLeft;
134297         fBestOverlap = overlap;
134298         fBestArea = area;
134299       }
134300     }
134301
134302     if( ii==0 || margin<fBestMargin ){
134303       iBestDim = ii;
134304       fBestMargin = margin;
134305       iBestSplit = iBestLeft;
134306     }
134307   }
134308
134309   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
134310   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
134311   for(ii=0; ii<nCell; ii++){
134312     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
134313     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
134314     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
134315     nodeInsertCell(pRtree, pTarget, pCell);
134316     cellUnion(pRtree, pBbox, pCell);
134317   }
134318
134319   sqlite3_free(aaSorted);
134320   return SQLITE_OK;
134321 }
134322 #endif
134323
134324 #if VARIANT_GUTTMAN_SPLIT
134325 /*
134326 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
134327 */
134328 static int splitNodeGuttman(
134329   Rtree *pRtree,
134330   RtreeCell *aCell,
134331   int nCell,
134332   RtreeNode *pLeft,
134333   RtreeNode *pRight,
134334   RtreeCell *pBboxLeft,
134335   RtreeCell *pBboxRight
134336 ){
134337   int iLeftSeed = 0;
134338   int iRightSeed = 1;
134339   int *aiUsed;
134340   int i;
134341
134342   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
134343   if( !aiUsed ){
134344     return SQLITE_NOMEM;
134345   }
134346   memset(aiUsed, 0, sizeof(int)*nCell);
134347
134348   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
134349
134350   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
134351   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
134352   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
134353   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
134354   aiUsed[iLeftSeed] = 1;
134355   aiUsed[iRightSeed] = 1;
134356
134357   for(i=nCell-2; i>0; i--){
134358     RtreeCell *pNext;
134359     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
134360     RtreeDValue diff =  
134361       cellGrowth(pRtree, pBboxLeft, pNext) - 
134362       cellGrowth(pRtree, pBboxRight, pNext)
134363     ;
134364     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
134365      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
134366     ){
134367       nodeInsertCell(pRtree, pRight, pNext);
134368       cellUnion(pRtree, pBboxRight, pNext);
134369     }else{
134370       nodeInsertCell(pRtree, pLeft, pNext);
134371       cellUnion(pRtree, pBboxLeft, pNext);
134372     }
134373   }
134374
134375   sqlite3_free(aiUsed);
134376   return SQLITE_OK;
134377 }
134378 #endif
134379
134380 static int updateMapping(
134381   Rtree *pRtree, 
134382   i64 iRowid, 
134383   RtreeNode *pNode, 
134384   int iHeight
134385 ){
134386   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
134387   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
134388   if( iHeight>0 ){
134389     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
134390     if( pChild ){
134391       nodeRelease(pRtree, pChild->pParent);
134392       nodeReference(pNode);
134393       pChild->pParent = pNode;
134394     }
134395   }
134396   return xSetMapping(pRtree, iRowid, pNode->iNode);
134397 }
134398
134399 static int SplitNode(
134400   Rtree *pRtree,
134401   RtreeNode *pNode,
134402   RtreeCell *pCell,
134403   int iHeight
134404 ){
134405   int i;
134406   int newCellIsRight = 0;
134407
134408   int rc = SQLITE_OK;
134409   int nCell = NCELL(pNode);
134410   RtreeCell *aCell;
134411   int *aiUsed;
134412
134413   RtreeNode *pLeft = 0;
134414   RtreeNode *pRight = 0;
134415
134416   RtreeCell leftbbox;
134417   RtreeCell rightbbox;
134418
134419   /* Allocate an array and populate it with a copy of pCell and 
134420   ** all cells from node pLeft. Then zero the original node.
134421   */
134422   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
134423   if( !aCell ){
134424     rc = SQLITE_NOMEM;
134425     goto splitnode_out;
134426   }
134427   aiUsed = (int *)&aCell[nCell+1];
134428   memset(aiUsed, 0, sizeof(int)*(nCell+1));
134429   for(i=0; i<nCell; i++){
134430     nodeGetCell(pRtree, pNode, i, &aCell[i]);
134431   }
134432   nodeZero(pRtree, pNode);
134433   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
134434   nCell++;
134435
134436   if( pNode->iNode==1 ){
134437     pRight = nodeNew(pRtree, pNode);
134438     pLeft = nodeNew(pRtree, pNode);
134439     pRtree->iDepth++;
134440     pNode->isDirty = 1;
134441     writeInt16(pNode->zData, pRtree->iDepth);
134442   }else{
134443     pLeft = pNode;
134444     pRight = nodeNew(pRtree, pLeft->pParent);
134445     nodeReference(pLeft);
134446   }
134447
134448   if( !pLeft || !pRight ){
134449     rc = SQLITE_NOMEM;
134450     goto splitnode_out;
134451   }
134452
134453   memset(pLeft->zData, 0, pRtree->iNodeSize);
134454   memset(pRight->zData, 0, pRtree->iNodeSize);
134455
134456   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
134457   if( rc!=SQLITE_OK ){
134458     goto splitnode_out;
134459   }
134460
134461   /* Ensure both child nodes have node numbers assigned to them by calling
134462   ** nodeWrite(). Node pRight always needs a node number, as it was created
134463   ** by nodeNew() above. But node pLeft sometimes already has a node number.
134464   ** In this case avoid the all to nodeWrite().
134465   */
134466   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
134467    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
134468   ){
134469     goto splitnode_out;
134470   }
134471
134472   rightbbox.iRowid = pRight->iNode;
134473   leftbbox.iRowid = pLeft->iNode;
134474
134475   if( pNode->iNode==1 ){
134476     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
134477     if( rc!=SQLITE_OK ){
134478       goto splitnode_out;
134479     }
134480   }else{
134481     RtreeNode *pParent = pLeft->pParent;
134482     int iCell;
134483     rc = nodeParentIndex(pRtree, pLeft, &iCell);
134484     if( rc==SQLITE_OK ){
134485       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
134486       rc = AdjustTree(pRtree, pParent, &leftbbox);
134487     }
134488     if( rc!=SQLITE_OK ){
134489       goto splitnode_out;
134490     }
134491   }
134492   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
134493     goto splitnode_out;
134494   }
134495
134496   for(i=0; i<NCELL(pRight); i++){
134497     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
134498     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
134499     if( iRowid==pCell->iRowid ){
134500       newCellIsRight = 1;
134501     }
134502     if( rc!=SQLITE_OK ){
134503       goto splitnode_out;
134504     }
134505   }
134506   if( pNode->iNode==1 ){
134507     for(i=0; i<NCELL(pLeft); i++){
134508       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
134509       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
134510       if( rc!=SQLITE_OK ){
134511         goto splitnode_out;
134512       }
134513     }
134514   }else if( newCellIsRight==0 ){
134515     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
134516   }
134517
134518   if( rc==SQLITE_OK ){
134519     rc = nodeRelease(pRtree, pRight);
134520     pRight = 0;
134521   }
134522   if( rc==SQLITE_OK ){
134523     rc = nodeRelease(pRtree, pLeft);
134524     pLeft = 0;
134525   }
134526
134527 splitnode_out:
134528   nodeRelease(pRtree, pRight);
134529   nodeRelease(pRtree, pLeft);
134530   sqlite3_free(aCell);
134531   return rc;
134532 }
134533
134534 /*
134535 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
134536 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
134537 ** the pLeaf->pParent chain all the way up to the root node.
134538 **
134539 ** This operation is required when a row is deleted (or updated - an update
134540 ** is implemented as a delete followed by an insert). SQLite provides the
134541 ** rowid of the row to delete, which can be used to find the leaf on which
134542 ** the entry resides (argument pLeaf). Once the leaf is located, this 
134543 ** function is called to determine its ancestry.
134544 */
134545 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
134546   int rc = SQLITE_OK;
134547   RtreeNode *pChild = pLeaf;
134548   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
134549     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
134550     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
134551     rc = sqlite3_step(pRtree->pReadParent);
134552     if( rc==SQLITE_ROW ){
134553       RtreeNode *pTest;           /* Used to test for reference loops */
134554       i64 iNode;                  /* Node number of parent node */
134555
134556       /* Before setting pChild->pParent, test that we are not creating a
134557       ** loop of references (as we would if, say, pChild==pParent). We don't
134558       ** want to do this as it leads to a memory leak when trying to delete
134559       ** the referenced counted node structures.
134560       */
134561       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
134562       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
134563       if( !pTest ){
134564         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
134565       }
134566     }
134567     rc = sqlite3_reset(pRtree->pReadParent);
134568     if( rc==SQLITE_OK ) rc = rc2;
134569     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
134570     pChild = pChild->pParent;
134571   }
134572   return rc;
134573 }
134574
134575 static int deleteCell(Rtree *, RtreeNode *, int, int);
134576
134577 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
134578   int rc;
134579   int rc2;
134580   RtreeNode *pParent = 0;
134581   int iCell;
134582
134583   assert( pNode->nRef==1 );
134584
134585   /* Remove the entry in the parent cell. */
134586   rc = nodeParentIndex(pRtree, pNode, &iCell);
134587   if( rc==SQLITE_OK ){
134588     pParent = pNode->pParent;
134589     pNode->pParent = 0;
134590     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
134591   }
134592   rc2 = nodeRelease(pRtree, pParent);
134593   if( rc==SQLITE_OK ){
134594     rc = rc2;
134595   }
134596   if( rc!=SQLITE_OK ){
134597     return rc;
134598   }
134599
134600   /* Remove the xxx_node entry. */
134601   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
134602   sqlite3_step(pRtree->pDeleteNode);
134603   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
134604     return rc;
134605   }
134606
134607   /* Remove the xxx_parent entry. */
134608   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
134609   sqlite3_step(pRtree->pDeleteParent);
134610   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
134611     return rc;
134612   }
134613   
134614   /* Remove the node from the in-memory hash table and link it into
134615   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
134616   */
134617   nodeHashDelete(pRtree, pNode);
134618   pNode->iNode = iHeight;
134619   pNode->pNext = pRtree->pDeleted;
134620   pNode->nRef++;
134621   pRtree->pDeleted = pNode;
134622
134623   return SQLITE_OK;
134624 }
134625
134626 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
134627   RtreeNode *pParent = pNode->pParent;
134628   int rc = SQLITE_OK; 
134629   if( pParent ){
134630     int ii; 
134631     int nCell = NCELL(pNode);
134632     RtreeCell box;                            /* Bounding box for pNode */
134633     nodeGetCell(pRtree, pNode, 0, &box);
134634     for(ii=1; ii<nCell; ii++){
134635       RtreeCell cell;
134636       nodeGetCell(pRtree, pNode, ii, &cell);
134637       cellUnion(pRtree, &box, &cell);
134638     }
134639     box.iRowid = pNode->iNode;
134640     rc = nodeParentIndex(pRtree, pNode, &ii);
134641     if( rc==SQLITE_OK ){
134642       nodeOverwriteCell(pRtree, pParent, &box, ii);
134643       rc = fixBoundingBox(pRtree, pParent);
134644     }
134645   }
134646   return rc;
134647 }
134648
134649 /*
134650 ** Delete the cell at index iCell of node pNode. After removing the
134651 ** cell, adjust the r-tree data structure if required.
134652 */
134653 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
134654   RtreeNode *pParent;
134655   int rc;
134656
134657   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
134658     return rc;
134659   }
134660
134661   /* Remove the cell from the node. This call just moves bytes around
134662   ** the in-memory node image, so it cannot fail.
134663   */
134664   nodeDeleteCell(pRtree, pNode, iCell);
134665
134666   /* If the node is not the tree root and now has less than the minimum
134667   ** number of cells, remove it from the tree. Otherwise, update the
134668   ** cell in the parent node so that it tightly contains the updated
134669   ** node.
134670   */
134671   pParent = pNode->pParent;
134672   assert( pParent || pNode->iNode==1 );
134673   if( pParent ){
134674     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
134675       rc = removeNode(pRtree, pNode, iHeight);
134676     }else{
134677       rc = fixBoundingBox(pRtree, pNode);
134678     }
134679   }
134680
134681   return rc;
134682 }
134683
134684 static int Reinsert(
134685   Rtree *pRtree, 
134686   RtreeNode *pNode, 
134687   RtreeCell *pCell, 
134688   int iHeight
134689 ){
134690   int *aOrder;
134691   int *aSpare;
134692   RtreeCell *aCell;
134693   RtreeDValue *aDistance;
134694   int nCell;
134695   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
134696   int iDim;
134697   int ii;
134698   int rc = SQLITE_OK;
134699   int n;
134700
134701   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
134702
134703   nCell = NCELL(pNode)+1;
134704   n = (nCell+1)&(~1);
134705
134706   /* Allocate the buffers used by this operation. The allocation is
134707   ** relinquished before this function returns.
134708   */
134709   aCell = (RtreeCell *)sqlite3_malloc(n * (
134710     sizeof(RtreeCell)     +         /* aCell array */
134711     sizeof(int)           +         /* aOrder array */
134712     sizeof(int)           +         /* aSpare array */
134713     sizeof(RtreeDValue)             /* aDistance array */
134714   ));
134715   if( !aCell ){
134716     return SQLITE_NOMEM;
134717   }
134718   aOrder    = (int *)&aCell[n];
134719   aSpare    = (int *)&aOrder[n];
134720   aDistance = (RtreeDValue *)&aSpare[n];
134721
134722   for(ii=0; ii<nCell; ii++){
134723     if( ii==(nCell-1) ){
134724       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
134725     }else{
134726       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
134727     }
134728     aOrder[ii] = ii;
134729     for(iDim=0; iDim<pRtree->nDim; iDim++){
134730       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
134731       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
134732     }
134733   }
134734   for(iDim=0; iDim<pRtree->nDim; iDim++){
134735     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
134736   }
134737
134738   for(ii=0; ii<nCell; ii++){
134739     aDistance[ii] = 0.0;
134740     for(iDim=0; iDim<pRtree->nDim; iDim++){
134741       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
134742                                DCOORD(aCell[ii].aCoord[iDim*2]));
134743       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
134744     }
134745   }
134746
134747   SortByDistance(aOrder, nCell, aDistance, aSpare);
134748   nodeZero(pRtree, pNode);
134749
134750   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
134751     RtreeCell *p = &aCell[aOrder[ii]];
134752     nodeInsertCell(pRtree, pNode, p);
134753     if( p->iRowid==pCell->iRowid ){
134754       if( iHeight==0 ){
134755         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
134756       }else{
134757         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
134758       }
134759     }
134760   }
134761   if( rc==SQLITE_OK ){
134762     rc = fixBoundingBox(pRtree, pNode);
134763   }
134764   for(; rc==SQLITE_OK && ii<nCell; ii++){
134765     /* Find a node to store this cell in. pNode->iNode currently contains
134766     ** the height of the sub-tree headed by the cell.
134767     */
134768     RtreeNode *pInsert;
134769     RtreeCell *p = &aCell[aOrder[ii]];
134770     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
134771     if( rc==SQLITE_OK ){
134772       int rc2;
134773       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
134774       rc2 = nodeRelease(pRtree, pInsert);
134775       if( rc==SQLITE_OK ){
134776         rc = rc2;
134777       }
134778     }
134779   }
134780
134781   sqlite3_free(aCell);
134782   return rc;
134783 }
134784
134785 /*
134786 ** Insert cell pCell into node pNode. Node pNode is the head of a 
134787 ** subtree iHeight high (leaf nodes have iHeight==0).
134788 */
134789 static int rtreeInsertCell(
134790   Rtree *pRtree,
134791   RtreeNode *pNode,
134792   RtreeCell *pCell,
134793   int iHeight
134794 ){
134795   int rc = SQLITE_OK;
134796   if( iHeight>0 ){
134797     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
134798     if( pChild ){
134799       nodeRelease(pRtree, pChild->pParent);
134800       nodeReference(pNode);
134801       pChild->pParent = pNode;
134802     }
134803   }
134804   if( nodeInsertCell(pRtree, pNode, pCell) ){
134805 #if VARIANT_RSTARTREE_REINSERT
134806     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
134807       rc = SplitNode(pRtree, pNode, pCell, iHeight);
134808     }else{
134809       pRtree->iReinsertHeight = iHeight;
134810       rc = Reinsert(pRtree, pNode, pCell, iHeight);
134811     }
134812 #else
134813     rc = SplitNode(pRtree, pNode, pCell, iHeight);
134814 #endif
134815   }else{
134816     rc = AdjustTree(pRtree, pNode, pCell);
134817     if( rc==SQLITE_OK ){
134818       if( iHeight==0 ){
134819         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
134820       }else{
134821         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
134822       }
134823     }
134824   }
134825   return rc;
134826 }
134827
134828 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
134829   int ii;
134830   int rc = SQLITE_OK;
134831   int nCell = NCELL(pNode);
134832
134833   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
134834     RtreeNode *pInsert;
134835     RtreeCell cell;
134836     nodeGetCell(pRtree, pNode, ii, &cell);
134837
134838     /* Find a node to store this cell in. pNode->iNode currently contains
134839     ** the height of the sub-tree headed by the cell.
134840     */
134841     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
134842     if( rc==SQLITE_OK ){
134843       int rc2;
134844       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
134845       rc2 = nodeRelease(pRtree, pInsert);
134846       if( rc==SQLITE_OK ){
134847         rc = rc2;
134848       }
134849     }
134850   }
134851   return rc;
134852 }
134853
134854 /*
134855 ** Select a currently unused rowid for a new r-tree record.
134856 */
134857 static int newRowid(Rtree *pRtree, i64 *piRowid){
134858   int rc;
134859   sqlite3_bind_null(pRtree->pWriteRowid, 1);
134860   sqlite3_bind_null(pRtree->pWriteRowid, 2);
134861   sqlite3_step(pRtree->pWriteRowid);
134862   rc = sqlite3_reset(pRtree->pWriteRowid);
134863   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
134864   return rc;
134865 }
134866
134867 /*
134868 ** Remove the entry with rowid=iDelete from the r-tree structure.
134869 */
134870 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
134871   int rc;                         /* Return code */
134872   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
134873   int iCell;                      /* Index of iDelete cell in pLeaf */
134874   RtreeNode *pRoot;               /* Root node of rtree structure */
134875
134876
134877   /* Obtain a reference to the root node to initialise Rtree.iDepth */
134878   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
134879
134880   /* Obtain a reference to the leaf node that contains the entry 
134881   ** about to be deleted. 
134882   */
134883   if( rc==SQLITE_OK ){
134884     rc = findLeafNode(pRtree, iDelete, &pLeaf);
134885   }
134886
134887   /* Delete the cell in question from the leaf node. */
134888   if( rc==SQLITE_OK ){
134889     int rc2;
134890     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
134891     if( rc==SQLITE_OK ){
134892       rc = deleteCell(pRtree, pLeaf, iCell, 0);
134893     }
134894     rc2 = nodeRelease(pRtree, pLeaf);
134895     if( rc==SQLITE_OK ){
134896       rc = rc2;
134897     }
134898   }
134899
134900   /* Delete the corresponding entry in the <rtree>_rowid table. */
134901   if( rc==SQLITE_OK ){
134902     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
134903     sqlite3_step(pRtree->pDeleteRowid);
134904     rc = sqlite3_reset(pRtree->pDeleteRowid);
134905   }
134906
134907   /* Check if the root node now has exactly one child. If so, remove
134908   ** it, schedule the contents of the child for reinsertion and 
134909   ** reduce the tree height by one.
134910   **
134911   ** This is equivalent to copying the contents of the child into
134912   ** the root node (the operation that Gutman's paper says to perform 
134913   ** in this scenario).
134914   */
134915   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
134916     int rc2;
134917     RtreeNode *pChild;
134918     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
134919     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
134920     if( rc==SQLITE_OK ){
134921       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
134922     }
134923     rc2 = nodeRelease(pRtree, pChild);
134924     if( rc==SQLITE_OK ) rc = rc2;
134925     if( rc==SQLITE_OK ){
134926       pRtree->iDepth--;
134927       writeInt16(pRoot->zData, pRtree->iDepth);
134928       pRoot->isDirty = 1;
134929     }
134930   }
134931
134932   /* Re-insert the contents of any underfull nodes removed from the tree. */
134933   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
134934     if( rc==SQLITE_OK ){
134935       rc = reinsertNodeContent(pRtree, pLeaf);
134936     }
134937     pRtree->pDeleted = pLeaf->pNext;
134938     sqlite3_free(pLeaf);
134939   }
134940
134941   /* Release the reference to the root node. */
134942   if( rc==SQLITE_OK ){
134943     rc = nodeRelease(pRtree, pRoot);
134944   }else{
134945     nodeRelease(pRtree, pRoot);
134946   }
134947
134948   return rc;
134949 }
134950
134951 /*
134952 ** Rounding constants for float->double conversion.
134953 */
134954 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
134955 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
134956
134957 #if !defined(SQLITE_RTREE_INT_ONLY)
134958 /*
134959 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
134960 ** while taking care to round toward negative or positive, respectively.
134961 */
134962 static RtreeValue rtreeValueDown(sqlite3_value *v){
134963   double d = sqlite3_value_double(v);
134964   float f = (float)d;
134965   if( f>d ){
134966     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
134967   }
134968   return f;
134969 }
134970 static RtreeValue rtreeValueUp(sqlite3_value *v){
134971   double d = sqlite3_value_double(v);
134972   float f = (float)d;
134973   if( f<d ){
134974     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
134975   }
134976   return f;
134977 }
134978 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
134979
134980
134981 /*
134982 ** The xUpdate method for rtree module virtual tables.
134983 */
134984 static int rtreeUpdate(
134985   sqlite3_vtab *pVtab, 
134986   int nData, 
134987   sqlite3_value **azData, 
134988   sqlite_int64 *pRowid
134989 ){
134990   Rtree *pRtree = (Rtree *)pVtab;
134991   int rc = SQLITE_OK;
134992   RtreeCell cell;                 /* New cell to insert if nData>1 */
134993   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
134994
134995   rtreeReference(pRtree);
134996   assert(nData>=1);
134997
134998   /* Constraint handling. A write operation on an r-tree table may return
134999   ** SQLITE_CONSTRAINT for two reasons:
135000   **
135001   **   1. A duplicate rowid value, or
135002   **   2. The supplied data violates the "x2>=x1" constraint.
135003   **
135004   ** In the first case, if the conflict-handling mode is REPLACE, then
135005   ** the conflicting row can be removed before proceeding. In the second
135006   ** case, SQLITE_CONSTRAINT must be returned regardless of the
135007   ** conflict-handling mode specified by the user.
135008   */
135009   if( nData>1 ){
135010     int ii;
135011
135012     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
135013     assert( nData==(pRtree->nDim*2 + 3) );
135014 #ifndef SQLITE_RTREE_INT_ONLY
135015     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135016       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135017         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
135018         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
135019         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
135020           rc = SQLITE_CONSTRAINT;
135021           goto constraint;
135022         }
135023       }
135024     }else
135025 #endif
135026     {
135027       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135028         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
135029         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
135030         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
135031           rc = SQLITE_CONSTRAINT;
135032           goto constraint;
135033         }
135034       }
135035     }
135036
135037     /* If a rowid value was supplied, check if it is already present in 
135038     ** the table. If so, the constraint has failed. */
135039     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
135040       cell.iRowid = sqlite3_value_int64(azData[2]);
135041       if( sqlite3_value_type(azData[0])==SQLITE_NULL
135042        || sqlite3_value_int64(azData[0])!=cell.iRowid
135043       ){
135044         int steprc;
135045         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
135046         steprc = sqlite3_step(pRtree->pReadRowid);
135047         rc = sqlite3_reset(pRtree->pReadRowid);
135048         if( SQLITE_ROW==steprc ){
135049           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
135050             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
135051           }else{
135052             rc = SQLITE_CONSTRAINT;
135053             goto constraint;
135054           }
135055         }
135056       }
135057       bHaveRowid = 1;
135058     }
135059   }
135060
135061   /* If azData[0] is not an SQL NULL value, it is the rowid of a
135062   ** record to delete from the r-tree table. The following block does
135063   ** just that.
135064   */
135065   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
135066     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
135067   }
135068
135069   /* If the azData[] array contains more than one element, elements
135070   ** (azData[2]..azData[argc-1]) contain a new record to insert into
135071   ** the r-tree structure.
135072   */
135073   if( rc==SQLITE_OK && nData>1 ){
135074     /* Insert the new record into the r-tree */
135075     RtreeNode *pLeaf;
135076
135077     /* Figure out the rowid of the new row. */
135078     if( bHaveRowid==0 ){
135079       rc = newRowid(pRtree, &cell.iRowid);
135080     }
135081     *pRowid = cell.iRowid;
135082
135083     if( rc==SQLITE_OK ){
135084       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
135085     }
135086     if( rc==SQLITE_OK ){
135087       int rc2;
135088       pRtree->iReinsertHeight = -1;
135089       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
135090       rc2 = nodeRelease(pRtree, pLeaf);
135091       if( rc==SQLITE_OK ){
135092         rc = rc2;
135093       }
135094     }
135095   }
135096
135097 constraint:
135098   rtreeRelease(pRtree);
135099   return rc;
135100 }
135101
135102 /*
135103 ** The xRename method for rtree module virtual tables.
135104 */
135105 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
135106   Rtree *pRtree = (Rtree *)pVtab;
135107   int rc = SQLITE_NOMEM;
135108   char *zSql = sqlite3_mprintf(
135109     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
135110     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
135111     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
135112     , pRtree->zDb, pRtree->zName, zNewName 
135113     , pRtree->zDb, pRtree->zName, zNewName 
135114     , pRtree->zDb, pRtree->zName, zNewName
135115   );
135116   if( zSql ){
135117     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
135118     sqlite3_free(zSql);
135119   }
135120   return rc;
135121 }
135122
135123 static sqlite3_module rtreeModule = {
135124   0,                          /* iVersion */
135125   rtreeCreate,                /* xCreate - create a table */
135126   rtreeConnect,               /* xConnect - connect to an existing table */
135127   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
135128   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
135129   rtreeDestroy,               /* xDestroy - Drop a table */
135130   rtreeOpen,                  /* xOpen - open a cursor */
135131   rtreeClose,                 /* xClose - close a cursor */
135132   rtreeFilter,                /* xFilter - configure scan constraints */
135133   rtreeNext,                  /* xNext - advance a cursor */
135134   rtreeEof,                   /* xEof */
135135   rtreeColumn,                /* xColumn - read data */
135136   rtreeRowid,                 /* xRowid - read data */
135137   rtreeUpdate,                /* xUpdate - write data */
135138   0,                          /* xBegin - begin transaction */
135139   0,                          /* xSync - sync transaction */
135140   0,                          /* xCommit - commit transaction */
135141   0,                          /* xRollback - rollback transaction */
135142   0,                          /* xFindFunction - function overloading */
135143   rtreeRename,                /* xRename - rename the table */
135144   0,                          /* xSavepoint */
135145   0,                          /* xRelease */
135146   0                           /* xRollbackTo */
135147 };
135148
135149 static int rtreeSqlInit(
135150   Rtree *pRtree, 
135151   sqlite3 *db, 
135152   const char *zDb, 
135153   const char *zPrefix, 
135154   int isCreate
135155 ){
135156   int rc = SQLITE_OK;
135157
135158   #define N_STATEMENT 9
135159   static const char *azSql[N_STATEMENT] = {
135160     /* Read and write the xxx_node table */
135161     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
135162     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
135163     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
135164
135165     /* Read and write the xxx_rowid table */
135166     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
135167     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
135168     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
135169
135170     /* Read and write the xxx_parent table */
135171     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
135172     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
135173     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
135174   };
135175   sqlite3_stmt **appStmt[N_STATEMENT];
135176   int i;
135177
135178   pRtree->db = db;
135179
135180   if( isCreate ){
135181     char *zCreate = sqlite3_mprintf(
135182 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
135183 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
135184 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
135185 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
135186       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
135187     );
135188     if( !zCreate ){
135189       return SQLITE_NOMEM;
135190     }
135191     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
135192     sqlite3_free(zCreate);
135193     if( rc!=SQLITE_OK ){
135194       return rc;
135195     }
135196   }
135197
135198   appStmt[0] = &pRtree->pReadNode;
135199   appStmt[1] = &pRtree->pWriteNode;
135200   appStmt[2] = &pRtree->pDeleteNode;
135201   appStmt[3] = &pRtree->pReadRowid;
135202   appStmt[4] = &pRtree->pWriteRowid;
135203   appStmt[5] = &pRtree->pDeleteRowid;
135204   appStmt[6] = &pRtree->pReadParent;
135205   appStmt[7] = &pRtree->pWriteParent;
135206   appStmt[8] = &pRtree->pDeleteParent;
135207
135208   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
135209     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
135210     if( zSql ){
135211       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
135212     }else{
135213       rc = SQLITE_NOMEM;
135214     }
135215     sqlite3_free(zSql);
135216   }
135217
135218   return rc;
135219 }
135220
135221 /*
135222 ** The second argument to this function contains the text of an SQL statement
135223 ** that returns a single integer value. The statement is compiled and executed
135224 ** using database connection db. If successful, the integer value returned
135225 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
135226 ** code is returned and the value of *piVal after returning is not defined.
135227 */
135228 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
135229   int rc = SQLITE_NOMEM;
135230   if( zSql ){
135231     sqlite3_stmt *pStmt = 0;
135232     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
135233     if( rc==SQLITE_OK ){
135234       if( SQLITE_ROW==sqlite3_step(pStmt) ){
135235         *piVal = sqlite3_column_int(pStmt, 0);
135236       }
135237       rc = sqlite3_finalize(pStmt);
135238     }
135239   }
135240   return rc;
135241 }
135242
135243 /*
135244 ** This function is called from within the xConnect() or xCreate() method to
135245 ** determine the node-size used by the rtree table being created or connected
135246 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
135247 ** Otherwise, an SQLite error code is returned.
135248 **
135249 ** If this function is being called as part of an xConnect(), then the rtree
135250 ** table already exists. In this case the node-size is determined by inspecting
135251 ** the root node of the tree.
135252 **
135253 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
135254 ** This ensures that each node is stored on a single database page. If the 
135255 ** database page-size is so large that more than RTREE_MAXCELLS entries 
135256 ** would fit in a single node, use a smaller node-size.
135257 */
135258 static int getNodeSize(
135259   sqlite3 *db,                    /* Database handle */
135260   Rtree *pRtree,                  /* Rtree handle */
135261   int isCreate                    /* True for xCreate, false for xConnect */
135262 ){
135263   int rc;
135264   char *zSql;
135265   if( isCreate ){
135266     int iPageSize = 0;
135267     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
135268     rc = getIntFromStmt(db, zSql, &iPageSize);
135269     if( rc==SQLITE_OK ){
135270       pRtree->iNodeSize = iPageSize-64;
135271       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
135272         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
135273       }
135274     }
135275   }else{
135276     zSql = sqlite3_mprintf(
135277         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
135278         pRtree->zDb, pRtree->zName
135279     );
135280     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
135281   }
135282
135283   sqlite3_free(zSql);
135284   return rc;
135285 }
135286
135287 /* 
135288 ** This function is the implementation of both the xConnect and xCreate
135289 ** methods of the r-tree virtual table.
135290 **
135291 **   argv[0]   -> module name
135292 **   argv[1]   -> database name
135293 **   argv[2]   -> table name
135294 **   argv[...] -> column names...
135295 */
135296 static int rtreeInit(
135297   sqlite3 *db,                        /* Database connection */
135298   void *pAux,                         /* One of the RTREE_COORD_* constants */
135299   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
135300   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
135301   char **pzErr,                       /* OUT: Error message, if any */
135302   int isCreate                        /* True for xCreate, false for xConnect */
135303 ){
135304   int rc = SQLITE_OK;
135305   Rtree *pRtree;
135306   int nDb;              /* Length of string argv[1] */
135307   int nName;            /* Length of string argv[2] */
135308   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
135309
135310   const char *aErrMsg[] = {
135311     0,                                                    /* 0 */
135312     "Wrong number of columns for an rtree table",         /* 1 */
135313     "Too few columns for an rtree table",                 /* 2 */
135314     "Too many columns for an rtree table"                 /* 3 */
135315   };
135316
135317   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
135318   if( aErrMsg[iErr] ){
135319     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
135320     return SQLITE_ERROR;
135321   }
135322
135323   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
135324
135325   /* Allocate the sqlite3_vtab structure */
135326   nDb = (int)strlen(argv[1]);
135327   nName = (int)strlen(argv[2]);
135328   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
135329   if( !pRtree ){
135330     return SQLITE_NOMEM;
135331   }
135332   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
135333   pRtree->nBusy = 1;
135334   pRtree->base.pModule = &rtreeModule;
135335   pRtree->zDb = (char *)&pRtree[1];
135336   pRtree->zName = &pRtree->zDb[nDb+1];
135337   pRtree->nDim = (argc-4)/2;
135338   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
135339   pRtree->eCoordType = eCoordType;
135340   memcpy(pRtree->zDb, argv[1], nDb);
135341   memcpy(pRtree->zName, argv[2], nName);
135342
135343   /* Figure out the node size to use. */
135344   rc = getNodeSize(db, pRtree, isCreate);
135345
135346   /* Create/Connect to the underlying relational database schema. If
135347   ** that is successful, call sqlite3_declare_vtab() to configure
135348   ** the r-tree table schema.
135349   */
135350   if( rc==SQLITE_OK ){
135351     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
135352       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
135353     }else{
135354       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
135355       char *zTmp;
135356       int ii;
135357       for(ii=4; zSql && ii<argc; ii++){
135358         zTmp = zSql;
135359         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
135360         sqlite3_free(zTmp);
135361       }
135362       if( zSql ){
135363         zTmp = zSql;
135364         zSql = sqlite3_mprintf("%s);", zTmp);
135365         sqlite3_free(zTmp);
135366       }
135367       if( !zSql ){
135368         rc = SQLITE_NOMEM;
135369       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
135370         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
135371       }
135372       sqlite3_free(zSql);
135373     }
135374   }
135375
135376   if( rc==SQLITE_OK ){
135377     *ppVtab = (sqlite3_vtab *)pRtree;
135378   }else{
135379     rtreeRelease(pRtree);
135380   }
135381   return rc;
135382 }
135383
135384
135385 /*
135386 ** Implementation of a scalar function that decodes r-tree nodes to
135387 ** human readable strings. This can be used for debugging and analysis.
135388 **
135389 ** The scalar function takes two arguments, a blob of data containing
135390 ** an r-tree node, and the number of dimensions the r-tree indexes.
135391 ** For a two-dimensional r-tree structure called "rt", to deserialize
135392 ** all nodes, a statement like:
135393 **
135394 **   SELECT rtreenode(2, data) FROM rt_node;
135395 **
135396 ** The human readable string takes the form of a Tcl list with one
135397 ** entry for each cell in the r-tree node. Each entry is itself a
135398 ** list, containing the 8-byte rowid/pageno followed by the 
135399 ** <num-dimension>*2 coordinates.
135400 */
135401 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
135402   char *zText = 0;
135403   RtreeNode node;
135404   Rtree tree;
135405   int ii;
135406
135407   UNUSED_PARAMETER(nArg);
135408   memset(&node, 0, sizeof(RtreeNode));
135409   memset(&tree, 0, sizeof(Rtree));
135410   tree.nDim = sqlite3_value_int(apArg[0]);
135411   tree.nBytesPerCell = 8 + 8 * tree.nDim;
135412   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
135413
135414   for(ii=0; ii<NCELL(&node); ii++){
135415     char zCell[512];
135416     int nCell = 0;
135417     RtreeCell cell;
135418     int jj;
135419
135420     nodeGetCell(&tree, &node, ii, &cell);
135421     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
135422     nCell = (int)strlen(zCell);
135423     for(jj=0; jj<tree.nDim*2; jj++){
135424 #ifndef SQLITE_RTREE_INT_ONLY
135425       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
135426                        (double)cell.aCoord[jj].f);
135427 #else
135428       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
135429                        cell.aCoord[jj].i);
135430 #endif
135431       nCell = (int)strlen(zCell);
135432     }
135433
135434     if( zText ){
135435       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
135436       sqlite3_free(zText);
135437       zText = zTextNew;
135438     }else{
135439       zText = sqlite3_mprintf("{%s}", zCell);
135440     }
135441   }
135442   
135443   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
135444 }
135445
135446 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
135447   UNUSED_PARAMETER(nArg);
135448   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
135449    || sqlite3_value_bytes(apArg[0])<2
135450   ){
135451     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
135452   }else{
135453     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
135454     sqlite3_result_int(ctx, readInt16(zBlob));
135455   }
135456 }
135457
135458 /*
135459 ** Register the r-tree module with database handle db. This creates the
135460 ** virtual table module "rtree" and the debugging/analysis scalar 
135461 ** function "rtreenode".
135462 */
135463 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
135464   const int utf8 = SQLITE_UTF8;
135465   int rc;
135466
135467   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
135468   if( rc==SQLITE_OK ){
135469     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
135470   }
135471   if( rc==SQLITE_OK ){
135472 #ifdef SQLITE_RTREE_INT_ONLY
135473     void *c = (void *)RTREE_COORD_INT32;
135474 #else
135475     void *c = (void *)RTREE_COORD_REAL32;
135476 #endif
135477     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
135478   }
135479   if( rc==SQLITE_OK ){
135480     void *c = (void *)RTREE_COORD_INT32;
135481     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
135482   }
135483
135484   return rc;
135485 }
135486
135487 /*
135488 ** A version of sqlite3_free() that can be used as a callback. This is used
135489 ** in two places - as the destructor for the blob value returned by the
135490 ** invocation of a geometry function, and as the destructor for the geometry
135491 ** functions themselves.
135492 */
135493 static void doSqlite3Free(void *p){
135494   sqlite3_free(p);
135495 }
135496
135497 /*
135498 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
135499 ** scalar user function. This C function is the callback used for all such
135500 ** registered SQL functions.
135501 **
135502 ** The scalar user functions return a blob that is interpreted by r-tree
135503 ** table MATCH operators.
135504 */
135505 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
135506   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
135507   RtreeMatchArg *pBlob;
135508   int nBlob;
135509
135510   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
135511   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
135512   if( !pBlob ){
135513     sqlite3_result_error_nomem(ctx);
135514   }else{
135515     int i;
135516     pBlob->magic = RTREE_GEOMETRY_MAGIC;
135517     pBlob->xGeom = pGeomCtx->xGeom;
135518     pBlob->pContext = pGeomCtx->pContext;
135519     pBlob->nParam = nArg;
135520     for(i=0; i<nArg; i++){
135521 #ifdef SQLITE_RTREE_INT_ONLY
135522       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
135523 #else
135524       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
135525 #endif
135526     }
135527     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
135528   }
135529 }
135530
135531 /*
135532 ** Register a new geometry function for use with the r-tree MATCH operator.
135533 */
135534 SQLITE_API int sqlite3_rtree_geometry_callback(
135535   sqlite3 *db,
135536   const char *zGeom,
135537   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
135538   void *pContext
135539 ){
135540   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
135541
135542   /* Allocate and populate the context object. */
135543   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
135544   if( !pGeomCtx ) return SQLITE_NOMEM;
135545   pGeomCtx->xGeom = xGeom;
135546   pGeomCtx->pContext = pContext;
135547
135548   /* Create the new user-function. Register a destructor function to delete
135549   ** the context object when it is no longer required.  */
135550   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
135551       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
135552   );
135553 }
135554
135555 #if !SQLITE_CORE
135556 SQLITE_API int sqlite3_extension_init(
135557   sqlite3 *db,
135558   char **pzErrMsg,
135559   const sqlite3_api_routines *pApi
135560 ){
135561   SQLITE_EXTENSION_INIT2(pApi)
135562   return sqlite3RtreeInit(db);
135563 }
135564 #endif
135565
135566 #endif
135567
135568 /************** End of rtree.c ***********************************************/
135569 /************** Begin file icu.c *********************************************/
135570 /*
135571 ** 2007 May 6
135572 **
135573 ** The author disclaims copyright to this source code.  In place of
135574 ** a legal notice, here is a blessing:
135575 **
135576 **    May you do good and not evil.
135577 **    May you find forgiveness for yourself and forgive others.
135578 **    May you share freely, never taking more than you give.
135579 **
135580 *************************************************************************
135581 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
135582 **
135583 ** This file implements an integration between the ICU library 
135584 ** ("International Components for Unicode", an open-source library 
135585 ** for handling unicode data) and SQLite. The integration uses 
135586 ** ICU to provide the following to SQLite:
135587 **
135588 **   * An implementation of the SQL regexp() function (and hence REGEXP
135589 **     operator) using the ICU uregex_XX() APIs.
135590 **
135591 **   * Implementations of the SQL scalar upper() and lower() functions
135592 **     for case mapping.
135593 **
135594 **   * Integration of ICU and SQLite collation seqences.
135595 **
135596 **   * An implementation of the LIKE operator that uses ICU to 
135597 **     provide case-independent matching.
135598 */
135599
135600 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
135601
135602 /* Include ICU headers */
135603 #include <unicode/utypes.h>
135604 #include <unicode/uregex.h>
135605 #include <unicode/ustring.h>
135606 #include <unicode/ucol.h>
135607
135608 /* #include <assert.h> */
135609
135610 #ifndef SQLITE_CORE
135611   SQLITE_EXTENSION_INIT1
135612 #else
135613 #endif
135614
135615 /*
135616 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
135617 ** operator.
135618 */
135619 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
135620 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
135621 #endif
135622
135623 /*
135624 ** Version of sqlite3_free() that is always a function, never a macro.
135625 */
135626 static void xFree(void *p){
135627   sqlite3_free(p);
135628 }
135629
135630 /*
135631 ** Compare two UTF-8 strings for equality where the first string is
135632 ** a "LIKE" expression. Return true (1) if they are the same and 
135633 ** false (0) if they are different.
135634 */
135635 static int icuLikeCompare(
135636   const uint8_t *zPattern,   /* LIKE pattern */
135637   const uint8_t *zString,    /* The UTF-8 string to compare against */
135638   const UChar32 uEsc         /* The escape character */
135639 ){
135640   static const int MATCH_ONE = (UChar32)'_';
135641   static const int MATCH_ALL = (UChar32)'%';
135642
135643   int iPattern = 0;       /* Current byte index in zPattern */
135644   int iString = 0;        /* Current byte index in zString */
135645
135646   int prevEscape = 0;     /* True if the previous character was uEsc */
135647
135648   while( zPattern[iPattern]!=0 ){
135649
135650     /* Read (and consume) the next character from the input pattern. */
135651     UChar32 uPattern;
135652     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
135653     assert(uPattern!=0);
135654
135655     /* There are now 4 possibilities:
135656     **
135657     **     1. uPattern is an unescaped match-all character "%",
135658     **     2. uPattern is an unescaped match-one character "_",
135659     **     3. uPattern is an unescaped escape character, or
135660     **     4. uPattern is to be handled as an ordinary character
135661     */
135662     if( !prevEscape && uPattern==MATCH_ALL ){
135663       /* Case 1. */
135664       uint8_t c;
135665
135666       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
135667       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
135668       ** test string.
135669       */
135670       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
135671         if( c==MATCH_ONE ){
135672           if( zString[iString]==0 ) return 0;
135673           U8_FWD_1_UNSAFE(zString, iString);
135674         }
135675         iPattern++;
135676       }
135677
135678       if( zPattern[iPattern]==0 ) return 1;
135679
135680       while( zString[iString] ){
135681         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
135682           return 1;
135683         }
135684         U8_FWD_1_UNSAFE(zString, iString);
135685       }
135686       return 0;
135687
135688     }else if( !prevEscape && uPattern==MATCH_ONE ){
135689       /* Case 2. */
135690       if( zString[iString]==0 ) return 0;
135691       U8_FWD_1_UNSAFE(zString, iString);
135692
135693     }else if( !prevEscape && uPattern==uEsc){
135694       /* Case 3. */
135695       prevEscape = 1;
135696
135697     }else{
135698       /* Case 4. */
135699       UChar32 uString;
135700       U8_NEXT_UNSAFE(zString, iString, uString);
135701       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
135702       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
135703       if( uString!=uPattern ){
135704         return 0;
135705       }
135706       prevEscape = 0;
135707     }
135708   }
135709
135710   return zString[iString]==0;
135711 }
135712
135713 /*
135714 ** Implementation of the like() SQL function.  This function implements
135715 ** the build-in LIKE operator.  The first argument to the function is the
135716 ** pattern and the second argument is the string.  So, the SQL statements:
135717 **
135718 **       A LIKE B
135719 **
135720 ** is implemented as like(B, A). If there is an escape character E, 
135721 **
135722 **       A LIKE B ESCAPE E
135723 **
135724 ** is mapped to like(B, A, E).
135725 */
135726 static void icuLikeFunc(
135727   sqlite3_context *context, 
135728   int argc, 
135729   sqlite3_value **argv
135730 ){
135731   const unsigned char *zA = sqlite3_value_text(argv[0]);
135732   const unsigned char *zB = sqlite3_value_text(argv[1]);
135733   UChar32 uEsc = 0;
135734
135735   /* Limit the length of the LIKE or GLOB pattern to avoid problems
135736   ** of deep recursion and N*N behavior in patternCompare().
135737   */
135738   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
135739     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
135740     return;
135741   }
135742
135743
135744   if( argc==3 ){
135745     /* The escape character string must consist of a single UTF-8 character.
135746     ** Otherwise, return an error.
135747     */
135748     int nE= sqlite3_value_bytes(argv[2]);
135749     const unsigned char *zE = sqlite3_value_text(argv[2]);
135750     int i = 0;
135751     if( zE==0 ) return;
135752     U8_NEXT(zE, i, nE, uEsc);
135753     if( i!=nE){
135754       sqlite3_result_error(context, 
135755           "ESCAPE expression must be a single character", -1);
135756       return;
135757     }
135758   }
135759
135760   if( zA && zB ){
135761     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
135762   }
135763 }
135764
135765 /*
135766 ** This function is called when an ICU function called from within
135767 ** the implementation of an SQL scalar function returns an error.
135768 **
135769 ** The scalar function context passed as the first argument is 
135770 ** loaded with an error message based on the following two args.
135771 */
135772 static void icuFunctionError(
135773   sqlite3_context *pCtx,       /* SQLite scalar function context */
135774   const char *zName,           /* Name of ICU function that failed */
135775   UErrorCode e                 /* Error code returned by ICU function */
135776 ){
135777   char zBuf[128];
135778   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
135779   zBuf[127] = '\0';
135780   sqlite3_result_error(pCtx, zBuf, -1);
135781 }
135782
135783 /*
135784 ** Function to delete compiled regexp objects. Registered as
135785 ** a destructor function with sqlite3_set_auxdata().
135786 */
135787 static void icuRegexpDelete(void *p){
135788   URegularExpression *pExpr = (URegularExpression *)p;
135789   uregex_close(pExpr);
135790 }
135791
135792 /*
135793 ** Implementation of SQLite REGEXP operator. This scalar function takes
135794 ** two arguments. The first is a regular expression pattern to compile
135795 ** the second is a string to match against that pattern. If either 
135796 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
135797 ** is 1 if the string matches the pattern, or 0 otherwise.
135798 **
135799 ** SQLite maps the regexp() function to the regexp() operator such
135800 ** that the following two are equivalent:
135801 **
135802 **     zString REGEXP zPattern
135803 **     regexp(zPattern, zString)
135804 **
135805 ** Uses the following ICU regexp APIs:
135806 **
135807 **     uregex_open()
135808 **     uregex_matches()
135809 **     uregex_close()
135810 */
135811 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
135812   UErrorCode status = U_ZERO_ERROR;
135813   URegularExpression *pExpr;
135814   UBool res;
135815   const UChar *zString = sqlite3_value_text16(apArg[1]);
135816
135817   (void)nArg;  /* Unused parameter */
135818
135819   /* If the left hand side of the regexp operator is NULL, 
135820   ** then the result is also NULL. 
135821   */
135822   if( !zString ){
135823     return;
135824   }
135825
135826   pExpr = sqlite3_get_auxdata(p, 0);
135827   if( !pExpr ){
135828     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
135829     if( !zPattern ){
135830       return;
135831     }
135832     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
135833
135834     if( U_SUCCESS(status) ){
135835       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
135836     }else{
135837       assert(!pExpr);
135838       icuFunctionError(p, "uregex_open", status);
135839       return;
135840     }
135841   }
135842
135843   /* Configure the text that the regular expression operates on. */
135844   uregex_setText(pExpr, zString, -1, &status);
135845   if( !U_SUCCESS(status) ){
135846     icuFunctionError(p, "uregex_setText", status);
135847     return;
135848   }
135849
135850   /* Attempt the match */
135851   res = uregex_matches(pExpr, 0, &status);
135852   if( !U_SUCCESS(status) ){
135853     icuFunctionError(p, "uregex_matches", status);
135854     return;
135855   }
135856
135857   /* Set the text that the regular expression operates on to a NULL
135858   ** pointer. This is not really necessary, but it is tidier than 
135859   ** leaving the regular expression object configured with an invalid
135860   ** pointer after this function returns.
135861   */
135862   uregex_setText(pExpr, 0, 0, &status);
135863
135864   /* Return 1 or 0. */
135865   sqlite3_result_int(p, res ? 1 : 0);
135866 }
135867
135868 /*
135869 ** Implementations of scalar functions for case mapping - upper() and 
135870 ** lower(). Function upper() converts its input to upper-case (ABC).
135871 ** Function lower() converts to lower-case (abc).
135872 **
135873 ** ICU provides two types of case mapping, "general" case mapping and
135874 ** "language specific". Refer to ICU documentation for the differences
135875 ** between the two.
135876 **
135877 ** To utilise "general" case mapping, the upper() or lower() scalar 
135878 ** functions are invoked with one argument:
135879 **
135880 **     upper('ABC') -> 'abc'
135881 **     lower('abc') -> 'ABC'
135882 **
135883 ** To access ICU "language specific" case mapping, upper() or lower()
135884 ** should be invoked with two arguments. The second argument is the name
135885 ** of the locale to use. Passing an empty string ("") or SQL NULL value
135886 ** as the second argument is the same as invoking the 1 argument version
135887 ** of upper() or lower().
135888 **
135889 **     lower('I', 'en_us') -> 'i'
135890 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
135891 **
135892 ** http://www.icu-project.org/userguide/posix.html#case_mappings
135893 */
135894 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
135895   const UChar *zInput;
135896   UChar *zOutput;
135897   int nInput;
135898   int nOutput;
135899
135900   UErrorCode status = U_ZERO_ERROR;
135901   const char *zLocale = 0;
135902
135903   assert(nArg==1 || nArg==2);
135904   if( nArg==2 ){
135905     zLocale = (const char *)sqlite3_value_text(apArg[1]);
135906   }
135907
135908   zInput = sqlite3_value_text16(apArg[0]);
135909   if( !zInput ){
135910     return;
135911   }
135912   nInput = sqlite3_value_bytes16(apArg[0]);
135913
135914   nOutput = nInput * 2 + 2;
135915   zOutput = sqlite3_malloc(nOutput);
135916   if( !zOutput ){
135917     return;
135918   }
135919
135920   if( sqlite3_user_data(p) ){
135921     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
135922   }else{
135923     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
135924   }
135925
135926   if( !U_SUCCESS(status) ){
135927     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
135928     return;
135929   }
135930
135931   sqlite3_result_text16(p, zOutput, -1, xFree);
135932 }
135933
135934 /*
135935 ** Collation sequence destructor function. The pCtx argument points to
135936 ** a UCollator structure previously allocated using ucol_open().
135937 */
135938 static void icuCollationDel(void *pCtx){
135939   UCollator *p = (UCollator *)pCtx;
135940   ucol_close(p);
135941 }
135942
135943 /*
135944 ** Collation sequence comparison function. The pCtx argument points to
135945 ** a UCollator structure previously allocated using ucol_open().
135946 */
135947 static int icuCollationColl(
135948   void *pCtx,
135949   int nLeft,
135950   const void *zLeft,
135951   int nRight,
135952   const void *zRight
135953 ){
135954   UCollationResult res;
135955   UCollator *p = (UCollator *)pCtx;
135956   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
135957   switch( res ){
135958     case UCOL_LESS:    return -1;
135959     case UCOL_GREATER: return +1;
135960     case UCOL_EQUAL:   return 0;
135961   }
135962   assert(!"Unexpected return value from ucol_strcoll()");
135963   return 0;
135964 }
135965
135966 /*
135967 ** Implementation of the scalar function icu_load_collation().
135968 **
135969 ** This scalar function is used to add ICU collation based collation 
135970 ** types to an SQLite database connection. It is intended to be called
135971 ** as follows:
135972 **
135973 **     SELECT icu_load_collation(<locale>, <collation-name>);
135974 **
135975 ** Where <locale> is a string containing an ICU locale identifier (i.e.
135976 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
135977 ** collation sequence to create.
135978 */
135979 static void icuLoadCollation(
135980   sqlite3_context *p, 
135981   int nArg, 
135982   sqlite3_value **apArg
135983 ){
135984   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
135985   UErrorCode status = U_ZERO_ERROR;
135986   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
135987   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
135988   UCollator *pUCollator;    /* ICU library collation object */
135989   int rc;                   /* Return code from sqlite3_create_collation_x() */
135990
135991   assert(nArg==2);
135992   zLocale = (const char *)sqlite3_value_text(apArg[0]);
135993   zName = (const char *)sqlite3_value_text(apArg[1]);
135994
135995   if( !zLocale || !zName ){
135996     return;
135997   }
135998
135999   pUCollator = ucol_open(zLocale, &status);
136000   if( !U_SUCCESS(status) ){
136001     icuFunctionError(p, "ucol_open", status);
136002     return;
136003   }
136004   assert(p);
136005
136006   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
136007       icuCollationColl, icuCollationDel
136008   );
136009   if( rc!=SQLITE_OK ){
136010     ucol_close(pUCollator);
136011     sqlite3_result_error(p, "Error registering collation function", -1);
136012   }
136013 }
136014
136015 /*
136016 ** Register the ICU extension functions with database db.
136017 */
136018 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
136019   struct IcuScalar {
136020     const char *zName;                        /* Function name */
136021     int nArg;                                 /* Number of arguments */
136022     int enc;                                  /* Optimal text encoding */
136023     void *pContext;                           /* sqlite3_user_data() context */
136024     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
136025   } scalars[] = {
136026     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
136027
136028     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
136029     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
136030     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
136031     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
136032
136033     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
136034     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
136035     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
136036     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
136037
136038     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
136039     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
136040
136041     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
136042   };
136043
136044   int rc = SQLITE_OK;
136045   int i;
136046
136047   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
136048     struct IcuScalar *p = &scalars[i];
136049     rc = sqlite3_create_function(
136050         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
136051     );
136052   }
136053
136054   return rc;
136055 }
136056
136057 #if !SQLITE_CORE
136058 SQLITE_API int sqlite3_extension_init(
136059   sqlite3 *db, 
136060   char **pzErrMsg,
136061   const sqlite3_api_routines *pApi
136062 ){
136063   SQLITE_EXTENSION_INIT2(pApi)
136064   return sqlite3IcuInit(db);
136065 }
136066 #endif
136067
136068 #endif
136069
136070 /************** End of icu.c *************************************************/
136071 /************** Begin file fts3_icu.c ****************************************/
136072 /*
136073 ** 2007 June 22
136074 **
136075 ** The author disclaims copyright to this source code.  In place of
136076 ** a legal notice, here is a blessing:
136077 **
136078 **    May you do good and not evil.
136079 **    May you find forgiveness for yourself and forgive others.
136080 **    May you share freely, never taking more than you give.
136081 **
136082 *************************************************************************
136083 ** This file implements a tokenizer for fts3 based on the ICU library.
136084 */
136085 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
136086 #ifdef SQLITE_ENABLE_ICU
136087
136088 /* #include <assert.h> */
136089 /* #include <string.h> */
136090
136091 #include <unicode/ubrk.h>
136092 /* #include <unicode/ucol.h> */
136093 /* #include <unicode/ustring.h> */
136094 #include <unicode/utf16.h>
136095
136096 typedef struct IcuTokenizer IcuTokenizer;
136097 typedef struct IcuCursor IcuCursor;
136098
136099 struct IcuTokenizer {
136100   sqlite3_tokenizer base;
136101   char *zLocale;
136102 };
136103
136104 struct IcuCursor {
136105   sqlite3_tokenizer_cursor base;
136106
136107   UBreakIterator *pIter;      /* ICU break-iterator object */
136108   int nChar;                  /* Number of UChar elements in pInput */
136109   UChar *aChar;               /* Copy of input using utf-16 encoding */
136110   int *aOffset;               /* Offsets of each character in utf-8 input */
136111
136112   int nBuffer;
136113   char *zBuffer;
136114
136115   int iToken;
136116 };
136117
136118 /*
136119 ** Create a new tokenizer instance.
136120 */
136121 static int icuCreate(
136122   int argc,                            /* Number of entries in argv[] */
136123   const char * const *argv,            /* Tokenizer creation arguments */
136124   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
136125 ){
136126   IcuTokenizer *p;
136127   int n = 0;
136128
136129   if( argc>0 ){
136130     n = strlen(argv[0])+1;
136131   }
136132   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
136133   if( !p ){
136134     return SQLITE_NOMEM;
136135   }
136136   memset(p, 0, sizeof(IcuTokenizer));
136137
136138   if( n ){
136139     p->zLocale = (char *)&p[1];
136140     memcpy(p->zLocale, argv[0], n);
136141   }
136142
136143   *ppTokenizer = (sqlite3_tokenizer *)p;
136144
136145   return SQLITE_OK;
136146 }
136147
136148 /*
136149 ** Destroy a tokenizer
136150 */
136151 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
136152   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
136153   sqlite3_free(p);
136154   return SQLITE_OK;
136155 }
136156
136157 /*
136158 ** Prepare to begin tokenizing a particular string.  The input
136159 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
136160 ** used to incrementally tokenize this string is returned in 
136161 ** *ppCursor.
136162 */
136163 static int icuOpen(
136164   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
136165   const char *zInput,                    /* Input string */
136166   int nInput,                            /* Length of zInput in bytes */
136167   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
136168 ){
136169   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
136170   IcuCursor *pCsr;
136171
136172   const int32_t opt = U_FOLD_CASE_DEFAULT;
136173   UErrorCode status = U_ZERO_ERROR;
136174   int nChar;
136175
136176   UChar32 c;
136177   int iInput = 0;
136178   int iOut = 0;
136179
136180   *ppCursor = 0;
136181
136182   if( zInput==0 ){
136183     nInput = 0;
136184     zInput = "";
136185   }else if( nInput<0 ){
136186     nInput = strlen(zInput);
136187   }
136188   nChar = nInput+1;
136189   pCsr = (IcuCursor *)sqlite3_malloc(
136190       sizeof(IcuCursor) +                /* IcuCursor */
136191       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
136192       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
136193   );
136194   if( !pCsr ){
136195     return SQLITE_NOMEM;
136196   }
136197   memset(pCsr, 0, sizeof(IcuCursor));
136198   pCsr->aChar = (UChar *)&pCsr[1];
136199   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
136200
136201   pCsr->aOffset[iOut] = iInput;
136202   U8_NEXT(zInput, iInput, nInput, c); 
136203   while( c>0 ){
136204     int isError = 0;
136205     c = u_foldCase(c, opt);
136206     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
136207     if( isError ){
136208       sqlite3_free(pCsr);
136209       return SQLITE_ERROR;
136210     }
136211     pCsr->aOffset[iOut] = iInput;
136212
136213     if( iInput<nInput ){
136214       U8_NEXT(zInput, iInput, nInput, c);
136215     }else{
136216       c = 0;
136217     }
136218   }
136219
136220   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
136221   if( !U_SUCCESS(status) ){
136222     sqlite3_free(pCsr);
136223     return SQLITE_ERROR;
136224   }
136225   pCsr->nChar = iOut;
136226
136227   ubrk_first(pCsr->pIter);
136228   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
136229   return SQLITE_OK;
136230 }
136231
136232 /*
136233 ** Close a tokenization cursor previously opened by a call to icuOpen().
136234 */
136235 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
136236   IcuCursor *pCsr = (IcuCursor *)pCursor;
136237   ubrk_close(pCsr->pIter);
136238   sqlite3_free(pCsr->zBuffer);
136239   sqlite3_free(pCsr);
136240   return SQLITE_OK;
136241 }
136242
136243 /*
136244 ** Extract the next token from a tokenization cursor.
136245 */
136246 static int icuNext(
136247   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
136248   const char **ppToken,               /* OUT: *ppToken is the token text */
136249   int *pnBytes,                       /* OUT: Number of bytes in token */
136250   int *piStartOffset,                 /* OUT: Starting offset of token */
136251   int *piEndOffset,                   /* OUT: Ending offset of token */
136252   int *piPosition                     /* OUT: Position integer of token */
136253 ){
136254   IcuCursor *pCsr = (IcuCursor *)pCursor;
136255
136256   int iStart = 0;
136257   int iEnd = 0;
136258   int nByte = 0;
136259
136260   while( iStart==iEnd ){
136261     UChar32 c;
136262
136263     iStart = ubrk_current(pCsr->pIter);
136264     iEnd = ubrk_next(pCsr->pIter);
136265     if( iEnd==UBRK_DONE ){
136266       return SQLITE_DONE;
136267     }
136268
136269     while( iStart<iEnd ){
136270       int iWhite = iStart;
136271       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
136272       if( u_isspace(c) ){
136273         iStart = iWhite;
136274       }else{
136275         break;
136276       }
136277     }
136278     assert(iStart<=iEnd);
136279   }
136280
136281   do {
136282     UErrorCode status = U_ZERO_ERROR;
136283     if( nByte ){
136284       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
136285       if( !zNew ){
136286         return SQLITE_NOMEM;
136287       }
136288       pCsr->zBuffer = zNew;
136289       pCsr->nBuffer = nByte;
136290     }
136291
136292     u_strToUTF8(
136293         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
136294         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
136295         &status                                  /* Output success/failure */
136296     );
136297   } while( nByte>pCsr->nBuffer );
136298
136299   *ppToken = pCsr->zBuffer;
136300   *pnBytes = nByte;
136301   *piStartOffset = pCsr->aOffset[iStart];
136302   *piEndOffset = pCsr->aOffset[iEnd];
136303   *piPosition = pCsr->iToken++;
136304
136305   return SQLITE_OK;
136306 }
136307
136308 /*
136309 ** The set of routines that implement the simple tokenizer
136310 */
136311 static const sqlite3_tokenizer_module icuTokenizerModule = {
136312   0,                           /* iVersion */
136313   icuCreate,                   /* xCreate  */
136314   icuDestroy,                  /* xCreate  */
136315   icuOpen,                     /* xOpen    */
136316   icuClose,                    /* xClose   */
136317   icuNext,                     /* xNext    */
136318 };
136319
136320 /*
136321 ** Set *ppModule to point at the implementation of the ICU tokenizer.
136322 */
136323 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
136324   sqlite3_tokenizer_module const**ppModule
136325 ){
136326   *ppModule = &icuTokenizerModule;
136327 }
136328
136329 #endif /* defined(SQLITE_ENABLE_ICU) */
136330 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
136331
136332 /************** End of fts3_icu.c ********************************************/